ben120-web / MSc-Project

This repository will contain the codebase used to develop various models to remove electrode motion noise from ECG signals using learning models.
0 stars 0 forks source link

Develop an API using GoLang. #3

Open ben120-web opened 1 month ago

ben120-web commented 1 month ago

Develop an API in Go. This API should take a time-series signal as an input, and call the backend model in Python. The time-series signal after having been passed through the model should be output.

ben120-web commented 1 month ago

@Tommytucker26 can you look into this. Front end work that should:

See below:

The repository contains various files and directories. To implement the API using Go, we'll need to create a few components:

  1. Web Server: To handle file uploads and model selection.
  2. Python Script: To process the uploaded ECG signal using the selected model.
  3. Integration: To connect the Go API with the Python scripts.

Here's a step-by-step guide on how to implement this:

Step 1: Create the Go API

First, let's create a basic Go web server that allows file uploads and model selection.

main.go:

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
    "os/exec"
    "path/filepath"
    "text/template"
)

const (
    uploadDir = "./uploads"
)

func uploadHandler(w http.ResponseWriter, r *http.Request) {
    if r.Method == "GET" {
        tmpl, _ := template.ParseFiles("upload.html")
        tmpl.Execute(w, nil)
        return
    }

    if r.Method == "POST" {
        model := r.FormValue("model")
        file, _, err := r.FormFile("file")
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        defer file.Close()

        // Save the uploaded file
        filePath := filepath.Join(uploadDir, "uploaded_signal.csv")
        out, err := os.Create(filePath)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }
        defer out.Close()

        _, err = out.ReadFrom(file)
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        // Call the Python script to process the file
        cmd := exec.Command("python3", "process_signal.py", filePath, model)
        output, err := cmd.CombinedOutput()
        if err != nil {
            http.Error(w, err.Error(), http.StatusInternalServerError)
            return
        }

        // Return the processed file
        w.Header().Set("Content-Disposition", "attachment; filename=denoised_signal.csv")
        w.Header().Set("Content-Type", "text/csv")
        w.Write(output)
    }
}

func main() {
    if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
        os.Mkdir(uploadDir, os.ModePerm)
    }

    http.HandleFunc("/upload", uploadHandler)
    http.Handle("/", http.FileServer(http.Dir("./static")))

    fmt.Println("Starting server at :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

upload.html:

<!DOCTYPE html>
<html>
<head>
    <title>Upload ECG Signal</title>
</head>
<body>
    <h1>Upload ECG Signal</h1>
    <form enctype="multipart/form-data" action="/upload" method="post">
        <label for="model">Select Model:</label>
        <select name="model" id="model">
            <option value="svm">SVM</option>
            <option value="pca_knn">PCA with KNN</option>
            <option value="random_forest">Random Forest</option>
            <option value="auto_encoder">Auto Encoder</option>
            <option value="gan">GAN</option>
            <option value="rnn_lstm">RNN with LSTM</option>
        </select>
        <br><br>
        <input type="file" name="file" />
        <br><br>
        <input type="submit" value="Upload" />
    </form>
</body>
</html>

Step 2: Create the Python Script

Create a Python script to handle the signal processing using the specified model.

process_signal.py:

import sys
import pandas as pd
from some_model_library import load_model, process_signal  # Replace with actual import

def main():
    if len(sys.argv) != 3:
        print("Usage: python process_signal.py <file_path> <model>")
        sys.exit(1)

    file_path = sys.argv[1]
    model_name = sys.argv[2]

    # Load the uploaded ECG signal
    ecg_signal = pd.read_csv(file_path)

    # Load the appropriate model
    model = load_model(model_name)

    # Process the ECG signal
    denoised_signal = process_signal(ecg_signal, model)

    # Return the denoised signal
    print(denoised_signal.to_csv(index=False))

if __name__ == "__main__":
    main()

Step 3: Set Up the Environment

Ensure you have all the necessary dependencies installed.

requirements.txt:

pandas
some_model_library  # Replace with actual library names

Step 4: Run the Application

  1. Set up a virtual environment and install the Python dependencies:

    python3 -m venv venv
    source venv/bin/activate
    pip install -r requirements.txt
  2. Run the Go server:

    go run main.go
  3. Access the application in your web browser at http://localhost:8080/upload.

Final Notes

ben120-web commented 1 month ago

cc/ @jrutledge1996