Files
junk2jive-server/internal/services/robowflow.go
2025-05-06 13:31:09 -07:00

85 lines
2.0 KiB
Go

package services
import (
"bytes"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
type RoboflowService struct {
apiKey string
}
type RoboflowResponse struct {
Predictions []struct {
Class string `json:"class"`
Confidence float64 `json:"confidence"`
} `json:"predictions"`
}
func NewRoboflowService(apiKey string) *RoboflowService {
return &RoboflowService{apiKey: apiKey}
}
func (s *RoboflowService) DetectObjects(imagePath string) ([]string, error) {
// Open the file
file, err := os.Open(imagePath)
if err != nil {
return nil, err
}
defer file.Close()
// Create a new multipart writer
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
// Create a form file field
part, err := writer.CreateFormFile("file", filepath.Base(imagePath))
if err != nil {
return nil, err
}
// Copy the file content to the form field
if _, err = io.Copy(part, file); err != nil {
return nil, err
}
// Close the writer to finalize the form
writer.Close()
// Create the request
url := fmt.Sprintf("https://detect.roboflow.com/taco-puuof/1?api_key=%s&confidence=60&overlap=30", s.apiKey)
req, err := http.NewRequest("POST", url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
// Send the request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Parse the response
var response RoboflowResponse
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return nil, err
}
// Extract object classes
var objects []string
for _, prediction := range response.Predictions {
objects = append(objects, prediction.Class)
}
return objects, nil
}