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

72 lines
2.3 KiB
Go

package handlers
import (
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
"gitea.miguelmuniz.com/junk2jive-server/internal/config"
"gitea.miguelmuniz.com/junk2jive-server/internal/services"
)
func VisualAIHandler(cfg *config.Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Parse multipart form with 10MB limit
if err := r.ParseMultipartForm(10 << 20); err != nil {
http.Error(w, "Unable to parse form", http.StatusBadRequest)
return
}
file, handler, err := r.FormFile("file")
if err != nil {
http.Error(w, "Error retrieving the file", http.StatusBadRequest)
return
}
defer file.Close()
// Create temporary file
tempFile, err := os.CreateTemp("", "upload-*"+filepath.Ext(handler.Filename))
if err != nil {
http.Error(w, "Error creating temporary file", http.StatusInternalServerError)
return
}
defer os.Remove(tempFile.Name())
defer tempFile.Close()
// Copy uploaded file to temp file
if _, err = io.Copy(tempFile, file); err != nil {
http.Error(w, "Error saving the file", http.StatusInternalServerError)
return
}
// Process with Roboflow
roboflowService := services.NewRoboflowService(cfg.RoboflowKey)
detectedObjects, err := roboflowService.DetectObjects(tempFile.Name())
if err != nil {
http.Error(w, "Error detecting objects", http.StatusInternalServerError)
return
}
// Generate DIY ideas based on detected objects
openAI := services.NewOpenAIService(cfg.OpenAIKey)
query := strings.Join(detectedObjects, ", ")
result, err := openAI.GenerateDIY(query)
if err != nil {
http.Error(w, "Failed to generate DIY ideas", http.StatusInternalServerError)
return
}
// Prepare response
response := DIYResponse{
Prompt: fmt.Sprintf("AI Suggestions for %s are:", query),
Result: result,
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
}
}