Files
pipeline_backend/workers/transcribe/internal/prompts/prompts.go

101 lines
2.3 KiB
Go
Raw Normal View History

2026-06-10 17:12:58 +03:00
package prompts
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
2026-06-10 17:18:37 +03:00
"github.com/postmet/transcribe/internal/models"
2026-06-10 17:12:58 +03:00
)
type Loader struct {
source string
filePath string
baseURL string
apiKey string
sectionID int
client *http.Client
}
func New(source, filePath, baseURL, apiKey string, sectionID int) *Loader {
return &Loader{
source: source,
filePath: filePath,
baseURL: strings.TrimRight(baseURL, "/"),
apiKey: apiKey,
sectionID: sectionID,
client: &http.Client{Timeout: 30 * time.Second},
}
}
func (l *Loader) Load(ctx context.Context) ([]models.Prompt, error) {
switch strings.ToLower(l.source) {
case "http":
return l.loadHTTP(ctx)
default:
return l.loadStatic()
}
}
func (l *Loader) loadStatic() ([]models.Prompt, error) {
data, err := os.ReadFile(l.filePath)
if err != nil {
return nil, fmt.Errorf("read prompts file: %w", err)
}
var prompts []models.Prompt
if err := json.Unmarshal(data, &prompts); err != nil {
return nil, fmt.Errorf("parse prompts file: %w", err)
}
return filterSection(prompts, l.sectionID), nil
}
func (l *Loader) loadHTTP(ctx context.Context) ([]models.Prompt, error) {
if l.baseURL == "" {
return nil, fmt.Errorf("PROMPTS_BASE_URL is required for http source")
}
url := fmt.Sprintf("%s/metrics/?id_section=%s", l.baseURL, strconv.Itoa(l.sectionID))
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
if l.apiKey != "" {
req.Header.Set("Authorization", "Bearer "+l.apiKey)
}
resp, err := l.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("prompts api status %d: %s", resp.StatusCode, string(body))
}
var prompts []models.Prompt
if err := json.Unmarshal(body, &prompts); err != nil {
return nil, fmt.Errorf("parse prompts response: %w", err)
}
return filterSection(prompts, l.sectionID), nil
}
func filterSection(prompts []models.Prompt, sectionID int) []models.Prompt {
if sectionID <= 0 {
return prompts
}
out := make([]models.Prompt, 0, len(prompts))
for _, p := range prompts {
if p.IDSection == sectionID {
out = append(out, p)
}
}
return out
}