163 lines
4.5 KiB
Go
163 lines
4.5 KiB
Go
// Clean exact repeated heading/paragraph pairs in A1 Slovenija category prompts.
|
|
// Runs only for the A1 tenant and never rewrites title or meta instructions.
|
|
// Dry run by default; pass -apply to write changes atomically.
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"strings"
|
|
|
|
"github.com/descrybe/descrybe-v2/apps/api/internal/aiprompts"
|
|
"github.com/descrybe/descrybe-v2/apps/api/internal/config"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
const a1ID = "604f23a8-b66e-4b21-8b45-0d72b68f4790"
|
|
|
|
func dedupeSections(raw string) (string, int, error) {
|
|
if raw == "" || raw == "null" {
|
|
return raw, 0, nil
|
|
}
|
|
var obj map[string]json.RawMessage
|
|
if err := json.Unmarshal([]byte(raw), &obj); err != nil {
|
|
return "", 0, err
|
|
}
|
|
if obj == nil {
|
|
return raw, 0, nil
|
|
}
|
|
var entries []map[string]json.RawMessage
|
|
if err := json.Unmarshal(obj["sections"], &entries); err != nil {
|
|
return raw, 0, nil
|
|
}
|
|
seen := make(map[string]bool)
|
|
result := make([]map[string]json.RawMessage, 0, len(entries))
|
|
removed := 0
|
|
for i := 0; i < len(entries); i++ {
|
|
var typ, instr string
|
|
_ = json.Unmarshal(entries[i]["type"], &typ)
|
|
_ = json.Unmarshal(entries[i]["instructions"], &instr)
|
|
if strings.EqualFold(typ, "h2") && i+1 < len(entries) {
|
|
var nextTyp, nextInstr string
|
|
_ = json.Unmarshal(entries[i+1]["type"], &nextTyp)
|
|
_ = json.Unmarshal(entries[i+1]["instructions"], &nextInstr)
|
|
if strings.EqualFold(nextTyp, "p") {
|
|
key := strings.ToLower(strings.Join(strings.Fields(instr+"\x00"+nextInstr), " "))
|
|
if seen[key] {
|
|
removed++
|
|
i++
|
|
continue
|
|
}
|
|
seen[key] = true
|
|
}
|
|
}
|
|
result = append(result, entries[i])
|
|
}
|
|
if removed == 0 {
|
|
return raw, 0, nil
|
|
}
|
|
obj["sections"], _ = json.Marshal(result)
|
|
encoded, err := json.Marshal(obj)
|
|
return string(encoded), removed, err
|
|
}
|
|
|
|
func main() {
|
|
config.LoadDotEnv()
|
|
databaseURL := flag.String("postgres", os.Getenv("DATABASE_URL"), "Postgres connection URL")
|
|
apply := flag.Bool("apply", false, "commit changes (default: dry run)")
|
|
flag.Parse()
|
|
if strings.TrimSpace(*databaseURL) == "" {
|
|
log.Fatal("DATABASE_URL is required")
|
|
}
|
|
ctx := context.Background()
|
|
db, err := pgxpool.New(ctx, *databaseURL)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer db.Close()
|
|
rows, err := db.Query(ctx, `SELECT c.id, COALESCE(c.prompt, '{}'::jsonb)::text,
|
|
COALESCE(c.description_template::text, '')
|
|
FROM categories c JOIN companies co ON co.id = c.company_id
|
|
WHERE (co.id = $1 OR LOWER(BTRIM(co.name)) = 'a1 slovenija')
|
|
ORDER BY c.name`, uuid.MustParse(a1ID))
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
type candidate struct {
|
|
id uuid.UUID
|
|
prompt, desc string
|
|
}
|
|
candidates := make([]candidate, 0)
|
|
for rows.Next() {
|
|
var c candidate
|
|
if err := rows.Scan(&c.id, &c.prompt, &c.desc); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
candidates = append(candidates, c)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
rows.Close()
|
|
if len(candidates) == 0 {
|
|
log.Fatal("no A1 Slovenija categories found; no changes made")
|
|
}
|
|
updated, duplicatePairs := 0, 0
|
|
for _, c := range candidates {
|
|
var prompts map[string]string
|
|
if err := json.Unmarshal([]byte(c.prompt), &prompts); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if prompts == nil {
|
|
prompts = map[string]string{}
|
|
}
|
|
changed, count := false, 0
|
|
for language, text := range prompts {
|
|
cleaned, n := aiprompts.DedupeA1DescriptionBlocks(text)
|
|
if n != 0 {
|
|
prompts[language] = cleaned
|
|
changed = true
|
|
count += n
|
|
}
|
|
}
|
|
desc, n, err := dedupeSections(c.desc)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if n != 0 {
|
|
count += n
|
|
changed = true
|
|
}
|
|
if !changed {
|
|
continue
|
|
}
|
|
updated++
|
|
duplicatePairs += count
|
|
log.Printf("category=%s repeated_pairs_removed=%d", c.id, count)
|
|
if !*apply {
|
|
continue
|
|
}
|
|
encoded, err := json.Marshal(prompts)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
tag, err := db.Exec(ctx, `UPDATE categories SET prompt=$2::jsonb,
|
|
description_template=NULLIF($3, '')::jsonb, updated_at=now()
|
|
WHERE id=$1 AND COALESCE(prompt, '{}'::jsonb)::text=$4
|
|
AND COALESCE(description_template::text, '')=$5`,
|
|
c.id, string(encoded), desc, c.prompt, c.desc)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if tag.RowsAffected() != 1 {
|
|
log.Fatal(fmt.Errorf("category %s changed concurrently; rerun dry-run", c.id))
|
|
}
|
|
}
|
|
log.Printf("A1 cleanup: categories_scanned=%d categories_requiring_cleanup=%d duplicated_pairs=%d applied=%v", len(candidates), updated, duplicatePairs, *apply)
|
|
}
|