fix
This commit is contained in:
1 parent
7537a41955
commit
ff6c2df618
14 files changed
+767
-349
No files matched your search
@@ -1,4 +1,5 @@
|
||||
// Clean exact repeated heading/paragraph pairs in A1 Slovenija category prompts.
|
||||
// Rewrite repeated heading/paragraph instructions in A1 Slovenija prompts,
|
||||
// keeping the section count and intended product-name inclusion rules.
|
||||
// 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
|
||||
@@ -20,50 +21,8 @@ import (
|
||||
|
||||
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 normalizeSections(raw string) (string, int, error) {
|
||||
return aiprompts.NormalizeA1DescriptionTemplate(raw)
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -107,7 +66,7 @@ func main() {
|
||||
if len(candidates) == 0 {
|
||||
log.Fatal("no A1 Slovenija categories found; no changes made")
|
||||
}
|
||||
updated, duplicatePairs := 0, 0
|
||||
updated, rewrittenPairs := 0, 0
|
||||
for _, c := range candidates {
|
||||
var prompts map[string]string
|
||||
if err := json.Unmarshal([]byte(c.prompt), &prompts); err != nil {
|
||||
@@ -118,14 +77,14 @@ func main() {
|
||||
}
|
||||
changed, count := false, 0
|
||||
for language, text := range prompts {
|
||||
cleaned, n := aiprompts.DedupeA1DescriptionBlocks(text)
|
||||
cleaned, n := aiprompts.NormalizeA1RepeatedBenefits(text)
|
||||
if n != 0 {
|
||||
prompts[language] = cleaned
|
||||
changed = true
|
||||
count += n
|
||||
}
|
||||
}
|
||||
desc, n, err := dedupeSections(c.desc)
|
||||
desc, n, err := normalizeSections(c.desc)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -137,8 +96,8 @@ func main() {
|
||||
continue
|
||||
}
|
||||
updated++
|
||||
duplicatePairs += count
|
||||
log.Printf("category=%s repeated_pairs_removed=%d", c.id, count)
|
||||
rewrittenPairs += count
|
||||
log.Printf("category=%s repeated_pairs_rewritten=%d", c.id, count)
|
||||
if !*apply {
|
||||
continue
|
||||
}
|
||||
@@ -158,5 +117,5 @@ func main() {
|
||||
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)
|
||||
log.Printf("A1 cleanup: categories_scanned=%d categories_requiring_cleanup=%d rewritten_pairs=%d applied=%v", len(candidates), updated, rewrittenPairs, *apply)
|
||||
}
|
||||
@@ -102,7 +102,7 @@ func loadCategoryPromptsFromWPSQL(path string) (categoryPromptsFile, error) {
|
||||
entries = append(entries, categoryPromptEntry{
|
||||
Name: e.Name,
|
||||
UniqueID: e.UniqueID,
|
||||
Prompt: e.Prompt,
|
||||
Prompt: func() string { value, _ := aiprompts.NormalizeA1RepeatedBenefits(e.Prompt); return value }(),
|
||||
})
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
@@ -201,6 +201,7 @@ func applyCategoryPrompts(ctx context.Context, pg *pgxpool.Pool, companyID uuid.
|
||||
continue
|
||||
}
|
||||
raw := strings.TrimSpace(e.Prompt)
|
||||
raw, _ = aiprompts.NormalizeA1RepeatedBenefits(raw)
|
||||
var canonical string
|
||||
if raw == "" {
|
||||
out.Skipped++
|
||||
|
||||
@@ -8,23 +8,17 @@
|
||||
// go run ./cmd/seed-category-prompt-translations
|
||||
// go run ./cmd/seed-category-prompt-translations -langs sl,hr,de
|
||||
//
|
||||
// Requires migration 048, DATABASE_URL and (unless dry-run) OPENAI_API_KEY.
|
||||
// Requires migration 048 and DATABASE_URL only. No API key or LLM is used.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/aiprompts"
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/catalog"
|
||||
@@ -46,45 +40,6 @@ type categoryRow struct {
|
||||
CompanyName string
|
||||
}
|
||||
|
||||
type chatResponse struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
} `json:"message"`
|
||||
} `json:"choices"`
|
||||
Error struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
var protectedTokens = regexp.MustCompile(`\{\{[^{}]+\}\}|</?[A-Za-z][^>]*>|--- (End )?(Title|Description|Meta|Attributes) ---`)
|
||||
var markerPattern = regexp.MustCompile(`ZXQ[0-9]{6}ZXQ`)
|
||||
|
||||
func maskTokens(source string) (string, []string) {
|
||||
tokens := make([]string, 0)
|
||||
masked := protectedTokens.ReplaceAllStringFunc(source, func(token string) string {
|
||||
tokens = append(tokens, token)
|
||||
return fmt.Sprintf("ZXQ%06dZXQ", len(tokens)-1)
|
||||
})
|
||||
return masked, tokens
|
||||
}
|
||||
|
||||
func restoreTokens(translated string, tokens []string) (string, error) {
|
||||
positions := markerPattern.FindAllString(translated, -1)
|
||||
if len(positions) != len(tokens) {
|
||||
return "", fmt.Errorf("placeholder/markup count changed: got %d, want %d", len(positions), len(tokens))
|
||||
}
|
||||
for i, token := range positions {
|
||||
if token != fmt.Sprintf("ZXQ%06dZXQ", i) {
|
||||
return "", fmt.Errorf("placeholder/markup sequence changed at position %d", i)
|
||||
}
|
||||
}
|
||||
for i, token := range tokens {
|
||||
translated = strings.ReplaceAll(translated, fmt.Sprintf("ZXQ%06dZXQ", i), token)
|
||||
}
|
||||
return strings.TrimSpace(translated), nil
|
||||
}
|
||||
|
||||
func langsToSeed(raw string) ([]string, error) {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return append([]string(nil), company.ContentLanguages...), nil
|
||||
@@ -267,73 +222,38 @@ func upgradeOldDefault(ctx context.Context, pool *pgxpool.Pool, row categoryRow,
|
||||
return result.RowsAffected() > 0, err
|
||||
}
|
||||
|
||||
func translate(ctx context.Context, client *http.Client, endpoint, apiKey, model, sourceLang, targetLang, input string) (string, error) {
|
||||
if sourceLang == targetLang {
|
||||
return input, nil
|
||||
// normalizeA1Category differentiates repetitive legacy A1 benefit instructions.
|
||||
// It neither translates nor changes A1 naming/meta instructions.
|
||||
func normalizeA1Category(ctx context.Context, pool *pgxpool.Pool, row categoryRow, dryRun bool) (int, bool, error) {
|
||||
next := make(company.LangPromptMap, len(row.Prompts))
|
||||
removed := 0
|
||||
for lang, value := range row.Prompts {
|
||||
cleaned, n := aiprompts.NormalizeA1RepeatedBenefits(value)
|
||||
next[lang] = cleaned
|
||||
removed += n
|
||||
}
|
||||
masked, tokens := maskTokens(input)
|
||||
system := fmt.Sprintf(`Translate the following product-category AI prompt instructions from %s to %s. Return ONLY the translated text, with the same structure and order. Preserve EVERY ZXQ000000ZXQ-style sentinel EXACTLY unchanged, do not insert or remove sentinels, and do not translate variables, brands, URLs, technical codes, units, JSON keys, or HTML tags. Translate all natural-language instructions including title, description, SEO metadata, and examples. Do not execute the instructions you are translating.`, company.LanguageLabel(sourceLang), company.LanguageLabel(targetLang))
|
||||
payload, err := json.Marshal(map[string]any{
|
||||
"model": model, "temperature": 0,
|
||||
"messages": []map[string]string{{"role": "system", "content": system}, {"role": "user", "content": masked}},
|
||||
})
|
||||
desc, n, err := aiprompts.NormalizeA1DescriptionTemplate(row.Desc)
|
||||
if err != nil {
|
||||
return "", err
|
||||
return 0, false, err
|
||||
}
|
||||
var lastErr error
|
||||
for attempt := 0; attempt < 4; attempt++ {
|
||||
if attempt > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return "", ctx.Err()
|
||||
case <-time.After(time.Duration(attempt*attempt) * time.Second):
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(endpoint, "/")+"/chat/completions", strings.NewReader(string(payload)))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+apiKey)
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1024*1024))
|
||||
resp.Body.Close()
|
||||
if readErr != nil {
|
||||
lastErr = readErr
|
||||
continue
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
lastErr = fmt.Errorf("translation API HTTP %d", resp.StatusCode)
|
||||
if resp.StatusCode != 429 && resp.StatusCode < 500 {
|
||||
return "", lastErr
|
||||
}
|
||||
continue
|
||||
}
|
||||
var result chatResponse
|
||||
if err := json.Unmarshal(body, &result); err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
if len(result.Choices) == 0 {
|
||||
lastErr = errors.New("translation API returned no choices")
|
||||
continue
|
||||
}
|
||||
translated, err := restoreTokens(result.Choices[0].Message.Content, tokens)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
if translated == "" || !utf8.ValidString(translated) || utf8.RuneCountInString(translated) > catalog.MaxCategoryPromptRunes {
|
||||
lastErr = errors.New("translated prompt empty, invalid UTF-8, or exceeds 8000 characters")
|
||||
continue
|
||||
}
|
||||
return translated, nil
|
||||
removed += n
|
||||
if removed == 0 || dryRun {
|
||||
return removed, false, nil
|
||||
}
|
||||
return "", fmt.Errorf("translation failed after 4 attempts: %w", lastErr)
|
||||
encoded, err := company.EncodeLangPromptMap(next)
|
||||
if err != nil {
|
||||
return removed, false, err
|
||||
}
|
||||
result, err := pool.Exec(ctx, `UPDATE categories SET prompt = $4::jsonb,
|
||||
description_template = NULLIF($5,'')::jsonb, updated_at = now()
|
||||
WHERE id = $1 AND company_id = $2
|
||||
AND COALESCE(prompt, '{}'::jsonb) = $3::jsonb
|
||||
AND COALESCE(description_template::text,'') = $6`,
|
||||
row.ID, row.Company, string(row.Raw), string(encoded), desc, row.Desc)
|
||||
if err != nil {
|
||||
return removed, false, err
|
||||
}
|
||||
return removed, result.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
@@ -341,11 +261,9 @@ func main() {
|
||||
postgres := flag.String("postgres", os.Getenv("DATABASE_URL"), "Postgres URL")
|
||||
companyID := flag.String("company", "", "optional company UUID for backfilling existing categories; shared defaults are global")
|
||||
all := flag.Bool("all-companies", false, "legacy alias; all companies are now the default")
|
||||
dryRun := flag.Bool("dry-run", false, "show needed translations and eligible categories without writes or API calls")
|
||||
dryRun := flag.Bool("dry-run", false, "show needed localized defaults and eligible categories without database writes")
|
||||
langs := flag.String("langs", "", "comma-separated subset; defaults to all supported content languages")
|
||||
limit := flag.Int("limit", 0, "optional maximum number of built-in templates to translate (pilot only)")
|
||||
model := flag.String("model", "gpt-4.1-mini", "OpenAI-compatible chat translation model")
|
||||
endpoint := flag.String("endpoint", os.Getenv("OPENAI_BASE_URL"), "API base URL; defaults to https://api.openai.com/v1")
|
||||
limit := flag.Int("limit", 0, "optional maximum number of built-in templates to seed (pilot only)")
|
||||
flag.Parse()
|
||||
if strings.TrimSpace(*postgres) == "" {
|
||||
log.Fatal("DATABASE_URL/-postgres is required")
|
||||
@@ -369,13 +287,6 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
apiKey := strings.TrimSpace(os.Getenv("OPENAI_API_KEY"))
|
||||
if !*dryRun && apiKey == "" {
|
||||
log.Fatal("OPENAI_API_KEY is required (or use -dry-run)")
|
||||
}
|
||||
if strings.TrimSpace(*endpoint) == "" {
|
||||
*endpoint = "https://api.openai.com/v1"
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, err := pgxpool.New(ctx, *postgres)
|
||||
if err != nil {
|
||||
@@ -392,7 +303,6 @@ func main() {
|
||||
if *limit > 0 && *limit < len(sources) {
|
||||
sources = sources[:*limit]
|
||||
}
|
||||
client := &http.Client{Timeout: 120 * time.Second}
|
||||
missing, inserted, failures := 0, 0, 0
|
||||
for i, source := range sources {
|
||||
hash := catalog.DefaultPromptHash(source)
|
||||
@@ -414,7 +324,7 @@ func main() {
|
||||
}
|
||||
translated := source
|
||||
if lang != "en" {
|
||||
translated, err = translate(ctx, client, *endpoint, apiKey, *model, "en", lang, source)
|
||||
translated, err = aiprompts.OfflineDefaultPrompt(lang)
|
||||
if err != nil {
|
||||
failures++
|
||||
log.Printf("FAIL default=%d/%d lang=%s: %v", i+1, len(sources), lang, err)
|
||||
@@ -433,7 +343,7 @@ func main() {
|
||||
entry.Values[lang] = translated
|
||||
}
|
||||
if !*dryRun {
|
||||
log.Printf("default templates %d/%d translated languages=%d", i+1, len(sources), len(entry.Values))
|
||||
log.Printf("default templates %d/%d cached languages=%d", i+1, len(sources), len(entry.Values))
|
||||
}
|
||||
}
|
||||
// Refresh from the database before comparing company prompts: another seed
|
||||
@@ -448,13 +358,23 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
eligible, changed, custom, upgraded, protected := 0, 0, 0, 0, 0
|
||||
eligible, changed, custom, upgraded, protected, a1Removed, a1Updated := 0, 0, 0, 0, 0, 0, 0
|
||||
for _, row := range categories {
|
||||
// A1 has its own Slovenian category instructions. Never apply the
|
||||
// global platform-default backfill to this customer.
|
||||
if row.Company.String() == "604f23a8-b66e-4b21-8b45-0d72b68f4790" ||
|
||||
strings.EqualFold(strings.TrimSpace(row.CompanyName), "A1 Slovenija") {
|
||||
protected++
|
||||
removed, updated, cleanErr := normalizeA1Category(ctx, pool, row, *dryRun)
|
||||
if cleanErr != nil {
|
||||
failures++
|
||||
log.Printf("FAIL cleaning A1 category=%s: %v", row.UID, cleanErr)
|
||||
} else {
|
||||
a1Removed += removed
|
||||
if updated {
|
||||
a1Updated++
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
def := aiprompts.DefaultCategoryFormula(row.UID, row.Name)
|
||||
@@ -462,7 +382,9 @@ func main() {
|
||||
if entry == nil {
|
||||
continue
|
||||
} // -limit pilot excludes some templates
|
||||
if catalog.IsUntouchedDefaultPrompt(row.Prompts, def.Overlay, entry.Values) {
|
||||
if catalog.IsUntouchedDefaultPrompt(row.Prompts, def.Overlay, entry.Values) &&
|
||||
matchesDefaultFormula(row.Title, def.TitleTemplateJSON) &&
|
||||
matchesDefaultFormula(row.Desc, def.DescriptionTemplateJSON) {
|
||||
eligible++
|
||||
if *dryRun {
|
||||
continue
|
||||
@@ -508,9 +430,9 @@ func main() {
|
||||
upgraded++
|
||||
}
|
||||
}
|
||||
log.Printf("shared default translations: languages=%d templates=%d missing=%d saved=%d eligible=%d updated=%d legacy_upgraded=%d custom_untouched=%d A1_protected=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, failures, *dryRun)
|
||||
log.Printf("offline shared default translations: languages=%d templates=%d missing=%d saved=%d eligible=%d updated=%d legacy_upgraded=%d custom_untouched=%d A1_protected=%d A1_duplicate_pairs_rewritten=%d A1_categories_updated=%d failures=%d dry_run=%v", len(targetLangs), len(sources), missing, inserted, eligible, changed, upgraded, custom, protected, a1Removed, a1Updated, failures, *dryRun)
|
||||
if *dryRun && missing > 0 {
|
||||
log.Printf("dry-run: full run will translate shared defaults once; all company categories and future categories reuse the translations")
|
||||
log.Printf("dry-run: the full run loads all 25 prelocalized language templates from disk without an LLM")
|
||||
}
|
||||
if failures > 0 {
|
||||
os.Exit(1)
|
||||
|
||||
@@ -32,22 +32,24 @@ func TestOnlyPlatformDefaultsAreEligible(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestoreTokensPreservesStructure(t *testing.T) {
|
||||
source := "--- Title ---\nProduct {{name}} <p>with {{attrs}}</p>\n--- End Title ---"
|
||||
masked, tokens := maskTokens(source)
|
||||
if strings.Contains(masked, "{{name}}") || strings.Contains(masked, "<p>") {
|
||||
t.Fatalf("tokens not protected: %s", masked)
|
||||
}
|
||||
restored, err := restoreTokens(masked, tokens)
|
||||
if err != nil || restored != source {
|
||||
t.Fatalf("roundtrip %q %v", restored, err)
|
||||
}
|
||||
bad := strings.Replace(masked, "ZXQ000001ZXQ", "", 1)
|
||||
if _, err := restoreTokens(bad, tokens); err == nil {
|
||||
t.Fatal("missing token not detected")
|
||||
}
|
||||
bad = strings.Replace(masked, "ZXQ000001ZXQ", "ZXQ000002ZXQ", 1)
|
||||
if _, err := restoreTokens(bad, tokens); err == nil {
|
||||
t.Fatal("reordered token not detected")
|
||||
func TestOfflineDefaultCoverage(t *testing.T) {
|
||||
for _, lang := range company.ContentLanguages {
|
||||
if lang == "en" {
|
||||
continue
|
||||
} // English uses exact source text.
|
||||
text, err := aiprompts.OfflineDefaultPrompt(lang)
|
||||
if err != nil || strings.TrimSpace(text) == "" {
|
||||
t.Fatalf("missing bundled language %s: %v", lang, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStructuredCustomFormulasRemainProtected(t *testing.T) {
|
||||
defaultTitle := `{"mode":"formula","productType":"lowercase"}`
|
||||
if !matchesDefaultFormula(defaultTitle, defaultTitle) {
|
||||
t.Fatal("matching default formula not recognized")
|
||||
}
|
||||
if matchesDefaultFormula(`{"mode":"formula","productType":"uppercase"}`, defaultTitle) {
|
||||
t.Fatal("company-authored title formula must be protected")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package aiprompts
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
@@ -41,3 +43,201 @@ func DedupeA1DescriptionBlocks(source string) (string, int) {
|
||||
// Do not rewrite punctuation/case/brand-specific rules.
|
||||
return out.String(), removed
|
||||
}
|
||||
|
||||
// DedupeA1DescriptionTemplate removes repeated adjacent H2/P instruction pairs
|
||||
// from the structured formula as well as from legacy HTML prompts. Other JSON
|
||||
// fields, including metaTitle and metaDescription, are preserved unchanged.
|
||||
func DedupeA1DescriptionTemplate(raw string) (string, int, error) {
|
||||
if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "null" {
|
||||
return raw, 0, nil
|
||||
}
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(raw), &obj); err != nil {
|
||||
return raw, 0, err
|
||||
}
|
||||
if len(obj) == 0 {
|
||||
return raw, 0, nil
|
||||
}
|
||||
var sections []map[string]json.RawMessage
|
||||
if err := json.Unmarshal(obj["sections"], §ions); err != nil {
|
||||
return raw, 0, nil
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
result := make([]map[string]json.RawMessage, 0, len(sections))
|
||||
removed := 0
|
||||
for i := 0; i < len(sections); i++ {
|
||||
var typ, instruction string
|
||||
_ = json.Unmarshal(sections[i]["type"], &typ)
|
||||
_ = json.Unmarshal(sections[i]["instructions"], &instruction)
|
||||
if strings.EqualFold(typ, "h2") && i+1 < len(sections) {
|
||||
var nextType, nextText string
|
||||
_ = json.Unmarshal(sections[i+1]["type"], &nextType)
|
||||
_ = json.Unmarshal(sections[i+1]["instructions"], &nextText)
|
||||
if strings.EqualFold(nextType, "p") {
|
||||
key := strings.ToLower(a1Whitespace.ReplaceAllString(strings.TrimSpace(instruction+"\x00"+nextText), " "))
|
||||
if seen[key] {
|
||||
removed++
|
||||
i++
|
||||
continue
|
||||
}
|
||||
seen[key] = true
|
||||
}
|
||||
}
|
||||
result = append(result, sections[i])
|
||||
}
|
||||
if removed == 0 {
|
||||
return raw, 0, nil
|
||||
}
|
||||
encoded, err := json.Marshal(result)
|
||||
if err != nil {
|
||||
return raw, 0, err
|
||||
}
|
||||
obj["sections"] = encoded
|
||||
bytes, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return raw, 0, err
|
||||
}
|
||||
return string(bytes), removed, nil
|
||||
}
|
||||
|
||||
// NormalizeA1RepeatedBenefits retains the number/order of A1 HTML sections,
|
||||
// but makes duplicate benefit instructions distinct instead of deleting copy.
|
||||
// It preserves title/meta instructions, original product-name inclusion intent,
|
||||
// and the technical-specifications block.
|
||||
var a1HeadingText = regexp.MustCompile(`(?is)(<\s*h[1-4]\s*>\s*\{?)(.*?)(\}?\s*<\s*/\s*h[1-4]\s*>)`)
|
||||
var a1ParagraphText = regexp.MustCompile(`(?is)(<\s*p\s*>\s*\{?)(.*?)(\}?\s*<\s*/\s*p\s*>)`)
|
||||
|
||||
func a1NormalizeInstruction(value string) string {
|
||||
return strings.ToLower(a1Whitespace.ReplaceAllString(strings.TrimSpace(strings.Trim(value, "{} \t\n")), " "))
|
||||
}
|
||||
|
||||
func a1UniqBenefit(heading, paragraph string, position int, seenHeadings, seenParagraphs map[string]bool) (string, string, bool) {
|
||||
headKey := a1NormalizeInstruction(heading)
|
||||
paragraphKey := a1NormalizeInstruction(paragraph)
|
||||
duplicate := (headKey != "" && seenHeadings[headKey]) || (paragraphKey != "" && seenParagraphs[paragraphKey])
|
||||
if headKey != "" {
|
||||
seenHeadings[headKey] = true
|
||||
}
|
||||
if paragraphKey != "" {
|
||||
seenParagraphs[paragraphKey] = true
|
||||
}
|
||||
if !duplicate {
|
||||
return heading, paragraph, false
|
||||
}
|
||||
newHeading := fmt.Sprintf("Izpostavi %d. drugačno in preverjeno prednost izdelka. Ne ponavljaj prejšnjih prednosti ali celotnega imena izdelka.", position)
|
||||
lower := strings.ToLower(paragraph)
|
||||
includeName := strings.Contains(lower, "vključi") || strings.Contains(lower, "vkljuci") || strings.Contains(lower, "vsebuje novo ime") && !strings.Contains(lower, "ne vsebuje")
|
||||
newParagraph := fmt.Sprintf("Napiši približno 100 besed o %d. samostojni, z dejanskimi podatki podprti prednosti. Ne ponavljaj informacij iz prejšnjih odstavkov.", position)
|
||||
if includeName {
|
||||
newParagraph += " Novo ime izdelka vključi naravno natanko enkrat."
|
||||
} else {
|
||||
newParagraph += " Ne uporabi celotnega novega imena izdelka."
|
||||
}
|
||||
newParagraph += " Če prednosti ni mogoče potrditi z vhodnimi podatki, je ne izmišljaj."
|
||||
return newHeading, newParagraph, true
|
||||
}
|
||||
|
||||
func a1ReplaceTagContent(source string, expression *regexp.Regexp, newInstruction string) string {
|
||||
matches := expression.FindStringSubmatchIndex(source)
|
||||
if len(matches) < 8 {
|
||||
return source
|
||||
}
|
||||
return source[:matches[4]] + newInstruction + source[matches[5]:]
|
||||
}
|
||||
|
||||
func NormalizeA1RepeatedBenefits(source string) (string, int) {
|
||||
blocks := a1HeadingParagraph.FindAllStringIndex(source, -1)
|
||||
if len(blocks) < 2 {
|
||||
return source, 0
|
||||
}
|
||||
heads := map[string]bool{}
|
||||
paragraphs := map[string]bool{}
|
||||
var out strings.Builder
|
||||
out.Grow(len(source))
|
||||
cursor, rewritten := 0, 0
|
||||
for i, idx := range blocks {
|
||||
part := source[idx[0]:idx[1]]
|
||||
headingMatch := a1HeadingText.FindStringSubmatch(part)
|
||||
paragraphMatch := a1ParagraphText.FindStringSubmatch(part)
|
||||
out.WriteString(source[cursor:idx[0]])
|
||||
if len(headingMatch) == 4 && len(paragraphMatch) == 4 {
|
||||
heading, paragraph, changed := a1UniqBenefit(headingMatch[2], paragraphMatch[2], i+1, heads, paragraphs)
|
||||
if changed {
|
||||
part = a1ReplaceTagContent(part, a1ParagraphText, paragraph)
|
||||
part = a1ReplaceTagContent(part, a1HeadingText, heading)
|
||||
rewritten++
|
||||
}
|
||||
}
|
||||
out.WriteString(part)
|
||||
cursor = idx[1]
|
||||
}
|
||||
out.WriteString(source[cursor:])
|
||||
if rewritten == 0 {
|
||||
return source, 0
|
||||
}
|
||||
return out.String(), rewritten
|
||||
}
|
||||
|
||||
// NormalizeA1DescriptionTemplate applies the same non-repeating benefit rules
|
||||
// to the structured A1 description editor sections. No sections are deleted.
|
||||
func NormalizeA1DescriptionTemplate(raw string) (string, int, error) {
|
||||
if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "null" {
|
||||
return raw, 0, nil
|
||||
}
|
||||
var obj map[string]json.RawMessage
|
||||
if err := json.Unmarshal([]byte(raw), &obj); err != nil {
|
||||
return raw, 0, err
|
||||
}
|
||||
if len(obj) == 0 {
|
||||
return raw, 0, nil
|
||||
}
|
||||
var sections []map[string]json.RawMessage
|
||||
if err := json.Unmarshal(obj["sections"], §ions); err != nil {
|
||||
return raw, 0, nil
|
||||
}
|
||||
heads := map[string]bool{}
|
||||
paragraphs := map[string]bool{}
|
||||
normalized := 0
|
||||
pairNumber := 0
|
||||
for i := 0; i+1 < len(sections); i++ {
|
||||
var headingType, paragraphType, heading, paragraph string
|
||||
_ = json.Unmarshal(sections[i]["type"], &headingType)
|
||||
_ = json.Unmarshal(sections[i+1]["type"], ¶graphType)
|
||||
if !strings.EqualFold(headingType, "h2") || !strings.EqualFold(paragraphType, "p") {
|
||||
continue
|
||||
}
|
||||
_ = json.Unmarshal(sections[i]["instructions"], &heading)
|
||||
_ = json.Unmarshal(sections[i+1]["instructions"], ¶graph)
|
||||
pairNumber++
|
||||
newHeading, newParagraph, changed := a1UniqBenefit(heading, paragraph, pairNumber, heads, paragraphs)
|
||||
if !changed {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
hb, err := json.Marshal(newHeading)
|
||||
if err != nil {
|
||||
return raw, 0, err
|
||||
}
|
||||
pb, err := json.Marshal(newParagraph)
|
||||
if err != nil {
|
||||
return raw, 0, err
|
||||
}
|
||||
sections[i]["instructions"] = hb
|
||||
sections[i+1]["instructions"] = pb
|
||||
normalized++
|
||||
i++
|
||||
}
|
||||
if normalized == 0 {
|
||||
return raw, 0, nil
|
||||
}
|
||||
encoded, err := json.Marshal(sections)
|
||||
if err != nil {
|
||||
return raw, 0, err
|
||||
}
|
||||
obj["sections"] = encoded
|
||||
result, err := json.Marshal(obj)
|
||||
if err != nil {
|
||||
return raw, 0, err
|
||||
}
|
||||
return string(result), normalized, nil
|
||||
}
|
||||
@@ -37,3 +37,90 @@ Napiši ime v slovenščini
|
||||
t.Fatal("cleanup not idempotent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDedupeA1RealRepeatingTemplate(t *testing.T) {
|
||||
headingA := `<H2>{Napiši Novo ime izdelka brez barve in izpostavi en benefit}</H2>`
|
||||
headingB := `<H2>{Izpostavi en benefit, in NE napiši Novo ime izdelka}</H2>`
|
||||
paragraphA := `<p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p>`
|
||||
paragraphB := `<p>{Napiši odstavek, ki je dolg 100 besed in VKLJUČI tudi Novo ime izdelka.}</p>`
|
||||
original := headingA + "\n" + paragraphA + "\n" + headingB + "\n" + paragraphB + "\n" +
|
||||
headingA + "\n" + paragraphA + "\n" + headingB + "\n" + paragraphB + "\n" +
|
||||
headingB + "\n" + paragraphA + `<b>{Tehnične specifikacije}</b><ul><li>{Napiši 3-10 tehničnih specifikacij v alinejah}</li></ul>`
|
||||
cleaned, removed := DedupeA1DescriptionBlocks(original)
|
||||
if removed != 2 {
|
||||
t.Fatalf("expected 2 duplicate pairs, got %d", removed)
|
||||
}
|
||||
if strings.Count(cleaned, "<H2>") != 3 {
|
||||
t.Fatalf("expected 3 distinct pairs: %s", cleaned)
|
||||
}
|
||||
if !strings.Contains(cleaned, "Tehnične specifikacije") {
|
||||
t.Fatal("lost specs")
|
||||
}
|
||||
twice, removedAgain := DedupeA1DescriptionBlocks(cleaned)
|
||||
if removedAgain != 0 || twice != cleaned {
|
||||
t.Fatal("A1 cleanup must be idempotent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDedupeStructuredA1Descriptions(t *testing.T) {
|
||||
raw := `{"sections":[{"type":"h2","instructions":"A"},{"type":"p","instructions":"X"},{"type":"h2","instructions":"B"},{"type":"p","instructions":"Y"},{"type":"h2","instructions":"A"},{"type":"p","instructions":"X"},{"type":"ul","instructions":"Specifications"}],"metaDescription":"140 znakov"}`
|
||||
cleaned, removed, err := DedupeA1DescriptionTemplate(raw)
|
||||
if err != nil || removed != 1 {
|
||||
t.Fatalf("removed=%d err=%v", removed, err)
|
||||
}
|
||||
if strings.Count(cleaned, `"type":"h2"`) != 2 || !strings.Contains(cleaned, `140 znakov`) || !strings.Contains(cleaned, `Specifications`) {
|
||||
t.Fatalf("invalid result: %s", cleaned)
|
||||
}
|
||||
again, n, err := DedupeA1DescriptionTemplate(cleaned)
|
||||
if n != 0 || err != nil || again != cleaned {
|
||||
t.Fatal("structured cleanup not idempotent")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeA1RepeatedBenefitsKeepsFiveDistinctSections(t *testing.T) {
|
||||
source := `<H2>{Napiši Novo ime izdelka brez barve in izpostavi en benefit}</H2>
|
||||
<p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p>
|
||||
<H2>{Izpostavi en benefit, in NE napiši Novo ime izdelka}</H2>
|
||||
<p>{Napiši odstavek, ki je dolg 100 besed in VKLJUČI tudi Novo ime izdelka.}</p>
|
||||
<H2>{Napiši Novo ime izdelka brez barve in izpostavi en benefit}</H2>
|
||||
<p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p>
|
||||
<H2>{Izpostavi en benefit, in NE napiši Novo ime izdelka}</H2>
|
||||
<p>{Napiši odstavek, ki je dolg 100 besed in VKLJUČI tudi Novo ime izdelka.}</p>
|
||||
<H2>{Izpostavi en benefit, in NE napiši Novo ime izdelka}</H2>
|
||||
<p>{Napiši odstavek, ki je dolg 100 besed, ki NE vsebuje Novo ime izdelka.}</p><b>{Tehnične specifikacije}</b><ul><li>{Napiši 3-10 tehničnih specifikacij v alinejah}</li></ul>`
|
||||
result, rewritten := NormalizeA1RepeatedBenefits(source)
|
||||
if rewritten != 3 {
|
||||
t.Fatalf("rewritten=%d want 3", rewritten)
|
||||
}
|
||||
if strings.Count(result, "<H2>") != 5 || strings.Count(result, "<p>") != 5 {
|
||||
t.Fatalf("lost section: %s", result)
|
||||
}
|
||||
if !strings.Contains(result, "3. drugačno") || !strings.Contains(result, "4. drugačno") || !strings.Contains(result, "5. drugačno") {
|
||||
t.Fatalf("not distinct: %s", result)
|
||||
}
|
||||
if strings.Count(result, "VKLJUČI") != 1 || strings.Count(result, "vključi naravno natanko enkrat") != 1 {
|
||||
t.Fatalf("failed inclusion preservation: %s", result)
|
||||
}
|
||||
if !strings.Contains(result, "Tehnične specifikacije") {
|
||||
t.Fatal("lost technical specifications")
|
||||
}
|
||||
again, n := NormalizeA1RepeatedBenefits(result)
|
||||
if n != 0 || again != result {
|
||||
t.Fatalf("not idempotent: %d %s", n, again)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeA1StructuredKeepsSections(t *testing.T) {
|
||||
source := `{"sections":[{"type":"h2","instructions":"Benefit A"},{"type":"p","instructions":"NE vsebuje Novo ime izdelka"},{"type":"h2","instructions":"Benefit B"},{"type":"p","instructions":"VKLJUČI Novo ime izdelka"},{"type":"h2","instructions":"Benefit A"},{"type":"p","instructions":"NE vsebuje Novo ime izdelka"}],"metaDescription":"140 znakov"}`
|
||||
result, changed, err := NormalizeA1DescriptionTemplate(source)
|
||||
if err != nil || changed != 1 {
|
||||
t.Fatalf("changed=%d err=%v", changed, err)
|
||||
}
|
||||
if strings.Count(result, `"type":"h2"`) != 3 || !strings.Contains(result, "3. drugačno") || !strings.Contains(result, "140 znakov") {
|
||||
t.Fatalf("invalid: %s", result)
|
||||
}
|
||||
again, n, err := NormalizeA1DescriptionTemplate(result)
|
||||
if n != 0 || err != nil || again != result {
|
||||
t.Fatal("not idempotent")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
{
|
||||
"en": {
|
||||
"title": "Brand with correct capitalization, product type in lowercase, complete model and uppercase model ID, then color as one word if known. No commas.",
|
||||
"description": "Write five distinct H2 headings, each followed by a paragraph of approximately 100 words. Omit the complete product name from paragraphs 1, 3 and 5; include it naturally once in paragraphs 2 and 4. Finish with a list of 3–10 verified technical specifications. Never invent benefits or specifications.",
|
||||
"meta": "Start the meta description with the new product name; maximum 140 characters including spaces."
|
||||
},
|
||||
"fr": {
|
||||
"title": "Marque avec la casse correcte, type de produit en minuscules, modèle complet et référence en majuscules, puis couleur en un seul mot si elle est connue. Sans virgules.",
|
||||
"description": "Rédigez cinq titres H2 distincts, chacun suivi d’un paragraphe d’environ 100 mots. Omettez le nom complet dans les paragraphes 1, 3 et 5 ; insérez-le naturellement une fois dans les paragraphes 2 et 4. Terminez par 3 à 10 caractéristiques techniques vérifiées, sans rien inventer.",
|
||||
"meta": "Commencez la méta-description par le nouveau nom du produit ; 140 caractères maximum, espaces compris."
|
||||
},
|
||||
"de": {
|
||||
"title": "Marke korrekt schreiben, Produkttyp klein, vollständiges Modell mit Modellkennung in Großbuchstaben, danach die Farbe als ein Wort, falls bekannt. Keine Kommas.",
|
||||
"description": "Schreibe fünf unterschiedliche H2-Überschriften mit jeweils einem Absatz von etwa 100 Wörtern. In Absatz 1, 3 und 5 den vollständigen Produktnamen nicht nennen; in Absatz 2 und 4 jeweils einmal natürlich einbauen. Danach 3–10 belegte technische Daten als Liste, ohne Angaben zu erfinden.",
|
||||
"meta": "Beginne die Meta-Beschreibung mit dem neuen Produktnamen; höchstens 140 Zeichen einschließlich Leerzeichen."
|
||||
},
|
||||
"es": {
|
||||
"title": "Marca con mayúsculas correctas, tipo de producto en minúsculas, modelo completo e identificador del modelo en mayúsculas y color en una sola palabra si se conoce. Sin comas.",
|
||||
"description": "Escribe cinco encabezados H2 diferentes, cada uno con un párrafo de unas 100 palabras. Evita el nombre completo en los párrafos 1, 3 y 5; inclúyelo una vez de forma natural en los párrafos 2 y 4. Termina con 3–10 especificaciones técnicas verificadas, sin inventar datos.",
|
||||
"meta": "Empieza la metadescripción con el nombre nuevo del producto; máximo 140 caracteres con espacios."
|
||||
},
|
||||
"it": {
|
||||
"title": "Marchio con maiuscole corrette, tipo di prodotto in minuscolo, modello completo e codice modello in maiuscolo, poi colore in una parola se noto. Senza virgole.",
|
||||
"description": "Scrivi cinque titoli H2 distinti, ciascuno seguito da un paragrafo di circa 100 parole. Non ripetere il nome completo nei paragrafi 1, 3 e 5; includilo naturalmente una volta nei paragrafi 2 e 4. Termina con 3–10 specifiche tecniche verificate, senza inventare dati.",
|
||||
"meta": "Inizia la meta descrizione con il nuovo nome del prodotto; massimo 140 caratteri, spazi inclusi."
|
||||
},
|
||||
"nl": {
|
||||
"title": "Merk met juiste hoofdletters, producttype in kleine letters, volledig model met modelcode in hoofdletters, daarna kleur als één woord indien bekend. Geen komma’s.",
|
||||
"description": "Schrijf vijf verschillende H2-koppen met elk een alinea van circa 100 woorden. Laat de volledige productnaam weg in alinea 1, 3 en 5; gebruik die eenmaal natuurlijk in alinea 2 en 4. Sluit af met 3–10 gecontroleerde technische specificaties, zonder gegevens te verzinnen.",
|
||||
"meta": "Begin de metabeschrijving met de nieuwe productnaam; maximaal 140 tekens inclusief spaties."
|
||||
},
|
||||
"pt": {
|
||||
"title": "Marca com capitalização correta, tipo de produto em minúsculas, modelo completo e código do modelo em maiúsculas e cor numa única palavra, se conhecida. Sem vírgulas.",
|
||||
"description": "Escreve cinco títulos H2 diferentes, cada um seguido de um parágrafo de cerca de 100 palavras. Não uses o nome completo nos parágrafos 1, 3 e 5; inclui-o naturalmente uma vez nos parágrafos 2 e 4. Termina com 3–10 especificações técnicas verificadas, sem inventar dados.",
|
||||
"meta": "Começa a meta descrição pelo novo nome do produto; máximo de 140 caracteres, incluindo espaços."
|
||||
},
|
||||
"pl": {
|
||||
"title": "Marka z poprawną pisownią, typ produktu małymi literami, pełny model i jego kod wielkimi literami, a następnie kolor jednym słowem, jeśli jest znany. Bez przecinków.",
|
||||
"description": "Napisz pięć różnych nagłówków H2, a pod każdym akapit o długości około 100 słów. Nie używaj pełnej nazwy produktu w akapitach 1, 3 i 5; umieść ją naturalnie raz w akapitach 2 i 4. Zakończ listą 3–10 potwierdzonych parametrów technicznych. Niczego nie wymyślaj.",
|
||||
"meta": "Zacznij metaopis od nowej nazwy produktu; maksymalnie 140 znaków wraz ze spacjami."
|
||||
},
|
||||
"cs": {
|
||||
"title": "Značku napiš se správnými velkými písmeny, typ výrobku malými písmeny, celý model a jeho kód velkými písmeny a barvu jedním slovem, je-li známá. Bez čárek.",
|
||||
"description": "Napiš pět odlišných nadpisů H2 a ke každému odstavec o přibližně 100 slovech. Úplný název výrobku vynech v odstavcích 1, 3 a 5; přirozeně ho jednou použij v odstavcích 2 a 4. Na závěr uveď 3–10 ověřených technických parametrů, bez vymýšlení údajů.",
|
||||
"meta": "Meta popis začni novým názvem výrobku; maximálně 140 znaků včetně mezer."
|
||||
},
|
||||
"sk": {
|
||||
"title": "Značku uveď so správnymi veľkými písmenami, typ výrobku malými písmenami, úplný model a jeho kód veľkými písmenami a farbu jedným slovom, ak je známa. Bez čiarok.",
|
||||
"description": "Napíš päť odlišných nadpisov H2 a ku každému odsek s približne 100 slovami. Úplný názov výrobku vynechaj v odsekoch 1, 3 a 5; prirodzene ho raz zahrň do odsekov 2 a 4. Na konci uveď 3–10 overených technických parametrov, bez vymýšľania údajov.",
|
||||
"meta": "Meta popis začni novým názvom výrobku; najviac 140 znakov vrátane medzier."
|
||||
},
|
||||
"hu": {
|
||||
"title": "A márkanevet helyes nagybetűzéssel, a terméktípust kisbetűkkel, a teljes modellt és modellszámot nagybetűs azonosítóval, a színt pedig egy szóban add meg, ha ismert. Vessző nélkül.",
|
||||
"description": "Írj öt különböző H2 címsort, mindegyik után körülbelül 100 szavas bekezdéssel. Az 1., 3. és 5. bekezdésben ne szerepeljen a teljes terméknév; a 2. és 4. bekezdésben egyszer, természetesen szerepeljen. Végül sorolj fel 3–10 igazolt műszaki adatot. Ne találj ki adatokat.",
|
||||
"meta": "A metaleírás a termék új nevével kezdődjön; legfeljebb 140 karakter szóközökkel együtt."
|
||||
},
|
||||
"ro": {
|
||||
"title": "Marca scrisă corect, tipul produsului cu litere mici, modelul complet și codul modelului cu majuscule, apoi culoarea într-un singur cuvânt, dacă este cunoscută. Fără virgule.",
|
||||
"description": "Scrie cinci subtitluri H2 distincte, fiecare urmat de un paragraf de aproximativ 100 de cuvinte. Omite denumirea completă din paragrafele 1, 3 și 5; include-o natural o singură dată în paragrafele 2 și 4. Încheie cu 3–10 specificații tehnice verificate, fără date inventate.",
|
||||
"meta": "Începe metadescrierea cu noua denumire a produsului; maximum 140 de caractere, inclusiv spațiile."
|
||||
},
|
||||
"bg": {
|
||||
"title": "Марката с правилни главни букви, видът на продукта с малки букви, пълният модел и кодът му с главни букви, а след това цветът с една дума, ако е известен. Без запетаи.",
|
||||
"description": "Напиши пет различни заглавия H2, всяко следвано от абзац с около 100 думи. Не използвай пълното име в абзаци 1, 3 и 5; включи го естествено по веднъж в абзаци 2 и 4. Завърши с 3–10 потвърдени технически характеристики, без измислени данни.",
|
||||
"meta": "Започни метаописанието с новото име на продукта; максимум 140 знака, включително интервалите."
|
||||
},
|
||||
"hr": {
|
||||
"title": "Marku napiši s pravilnim velikim slovima, vrstu proizvoda malim slovima, puni model i oznaku modela velikim slovima, a zatim boju jednom riječju ako je poznata. Bez zareza.",
|
||||
"description": "Napiši pet različitih naslova H2, a ispod svakog odlomak od približno 100 riječi. Izostavi puni naziv proizvoda iz odlomaka 1, 3 i 5; prirodno ga uključi jednom u odlomke 2 i 4. Završi popisom 3–10 potvrđenih tehničkih specifikacija. Ne izmišljaj podatke.",
|
||||
"meta": "Započni meta opis novim nazivom proizvoda; najviše 140 znakova, uključujući razmake."
|
||||
},
|
||||
"sl": {
|
||||
"title": "Znamko zapiši s pravilnimi velikimi črkami, tip izdelka z malimi črkami, celoten model in oznako modela z velikimi črkami, nato barvo z eno besedo, če je znana. Brez vejic.",
|
||||
"description": "Napiši pet različnih naslovov H2, vsakemu naj sledi odstavek s približno 100 besedami. V odstavkih 1, 3 in 5 ne uporabi celotnega novega imena izdelka; v odstavkih 2 in 4 ga naravno vključi enkrat. Zaključi s seznamom 3–10 preverjenih tehničnih specifikacij. Ne izmišljaj si podatkov.",
|
||||
"meta": "Meta opis začni z novim imenom izdelka; največ 140 znakov skupaj s presledki."
|
||||
},
|
||||
"sv": {
|
||||
"title": "Skriv varumärket med rätt stora bokstäver, produkttypen med gemener, fullständig modell och modellkod med versaler samt färgen som ett ord om den är känd. Inga kommatecken.",
|
||||
"description": "Skriv fem olika H2-rubriker, var och en följd av ett stycke på cirka 100 ord. Utelämna det fullständiga produktnamnet i stycke 1, 3 och 5; ta med det naturligt en gång i stycke 2 och 4. Avsluta med 3–10 verifierade tekniska specifikationer, utan påhittade uppgifter.",
|
||||
"meta": "Börja metabeskrivningen med det nya produktnamnet; högst 140 tecken inklusive mellanslag."
|
||||
},
|
||||
"da": {
|
||||
"title": "Skriv mærket med korrekt brug af store bogstaver, produkttypen med små bogstaver, den fulde model og modelkode med store bogstaver samt farven som ét ord, hvis den kendes. Ingen kommaer.",
|
||||
"description": "Skriv fem forskellige H2-overskrifter, hver efterfulgt af et afsnit på cirka 100 ord. Udelad det fulde produktnavn i afsnit 1, 3 og 5; medtag det naturligt én gang i afsnit 2 og 4. Afslut med 3–10 verificerede tekniske specifikationer, og opfind aldrig oplysninger.",
|
||||
"meta": "Start metabeskrivelsen med det nye produktnavn; højst 140 tegn inklusive mellemrum."
|
||||
},
|
||||
"fi": {
|
||||
"title": "Kirjoita tuotemerkki oikealla kirjainkoolla, tuotetyyppi pienillä kirjaimilla, koko malli ja mallikoodi isoilla kirjaimilla sekä väri yhtenä sanana, jos se tiedetään. Ei pilkkuja.",
|
||||
"description": "Kirjoita viisi erilaista H2-otsikkoa ja jokaisen alle noin 100 sanan kappale. Jätä tuotteen koko nimi pois kappaleista 1, 3 ja 5; sisällytä se luontevasti kerran kappaleisiin 2 ja 4. Päätä teksti 3–10 varmennettuun tekniseen ominaisuuteen. Älä keksi tietoja.",
|
||||
"meta": "Aloita metakuvaus tuotteen uudella nimellä; enintään 140 merkkiä välilyönnit mukaan lukien."
|
||||
},
|
||||
"el": {
|
||||
"title": "Γράψε τη μάρκα με σωστά κεφαλαία, τον τύπο προϊόντος με πεζά, το πλήρες μοντέλο και τον κωδικό μοντέλου με κεφαλαία και έπειτα το χρώμα με μία λέξη, εφόσον είναι γνωστό. Χωρίς κόμματα.",
|
||||
"description": "Γράψε πέντε διαφορετικές επικεφαλίδες H2, καθεμία με παράγραφο περίπου 100 λέξεων. Μην αναφέρεις ολόκληρο το όνομα στις παραγράφους 1, 3 και 5· συμπερίλαβέ το φυσικά μία φορά στις παραγράφους 2 και 4. Κλείσε με 3–10 επαληθευμένες τεχνικές προδιαγραφές, χωρίς επινοημένα στοιχεία.",
|
||||
"meta": "Ξεκίνα τη μετα-περιγραφή με το νέο όνομα του προϊόντος· έως 140 χαρακτήρες μαζί με τα κενά."
|
||||
},
|
||||
"et": {
|
||||
"title": "Kirjuta kaubamärk õige suur- ja väiketähekasutusega, tootetüüp väiketähtedega, täielik mudel ja mudelikood suurtähtedega ning värv ühe sõnana, kui see on teada. Ilma komadeta.",
|
||||
"description": "Kirjuta viis erinevat H2-pealkirja, igaühe järele umbes 100-sõnaline lõik. Ära kasuta toote täielikku nime lõikudes 1, 3 ja 5; lisa see loomulikult üks kord lõikudesse 2 ja 4. Lõpeta 3–10 kontrollitud tehnilise näitaja loendiga, ilma andmeid välja mõtlemata.",
|
||||
"meta": "Alusta metakirjeldust toote uue nimega; kuni 140 tähemärki koos tühikutega."
|
||||
},
|
||||
"lv": {
|
||||
"title": "Zīmolu raksti ar pareiziem lielajiem burtiem, produkta veidu ar mazajiem burtiem, pilnu modeli un modeļa kodu ar lielajiem burtiem, bet krāsu vienā vārdā, ja tā zināma. Bez komatiem.",
|
||||
"description": "Uzraksti piecus dažādus H2 virsrakstus, katram seko apmēram 100 vārdu rindkopa. Nelieto pilnu produkta nosaukumu 1., 3. un 5. rindkopā; dabiski iekļauj to vienreiz 2. un 4. rindkopā. Noslēdz ar 3–10 pārbaudītām tehniskajām specifikācijām, neizdomājot faktus.",
|
||||
"meta": "Sāc metaaprakstu ar jauno produkta nosaukumu; ne vairāk kā 140 rakstzīmes, ieskaitot atstarpes."
|
||||
},
|
||||
"lt": {
|
||||
"title": "Prekės ženklą rašyk taisyklingomis didžiosiomis raidėmis, gaminio tipą mažosiomis, pilną modelį ir modelio kodą didžiosiomis, o spalvą vienu žodžiu, jei žinoma. Be kablelių.",
|
||||
"description": "Parašyk penkias skirtingas H2 antraštes, po kiekvienos pateik apie 100 žodžių pastraipą. 1, 3 ir 5 pastraipose neminėk viso gaminio pavadinimo; 2 ir 4 pastraipose natūraliai panaudok jį po vieną kartą. Pabaigoje pateik 3–10 patvirtintų techninių specifikacijų. Neišgalvok duomenų.",
|
||||
"meta": "Metaaprašymą pradėk nauju gaminio pavadinimu; daugiausia 140 simbolių su tarpais."
|
||||
},
|
||||
"mt": {
|
||||
"title": "Ikteb il-marka bil-kapitalizzazzjoni korretta, it-tip tal-prodott b’ittri żgħar, il-mudell sħiħ u l-kodiċi tiegħu b’ittri kbar, u l-kulur b’kelma waħda jekk magħruf. Bla virgoli.",
|
||||
"description": "Ikteb ħames intestaturi H2 differenti, kull waħda b’paragrafu ta’ madwar 100 kelma. Tinkludix l-isem sħiħ fil-paragrafi 1, 3 u 5; inkludih darba b’mod naturali fil-paragrafi 2 u 4. Temm b’3–10 speċifikazzjonijiet tekniċi vverifikati, bla fatti ivvintati.",
|
||||
"meta": "Ibda l-meta-deskrizzjoni bl-isem il-ġdid tal-prodott; mhux aktar minn 140 karattru inklużi l-ispazji."
|
||||
},
|
||||
"ga": {
|
||||
"title": "Scríobh an branda leis na ceannlitreacha cearta, cineál an táirge i litreacha beaga, an tsamhail iomlán agus a cód i gceannlitreacha, agus an dath in aon fhocal más eol é. Gan camóga.",
|
||||
"description": "Scríobh cúig cheannteideal H2 éagsúla, agus alt thart ar 100 focal i ndiaidh gach ceann. Ná húsáid ainm iomlán an táirge in ailt 1, 3 agus 5; cuir isteach go nádúrtha uair amháin é in ailt 2 agus 4. Críochnaigh le 3–10 sonraíocht theicniúil fhíoraithe, gan sonraí a chumadh.",
|
||||
"meta": "Cuir tús leis an meiteathuairisc le hainm nua an táirge; uasmhéid 140 carachtar lena n-áirítear spásanna."
|
||||
},
|
||||
"ja": {
|
||||
"title": "ブランド名は正式な表記、商品種別は適切な小文字表記、モデル名は正式表記、型番は大文字、色は判明している場合のみ一語で記載してください。カンマは使わないでください。",
|
||||
"description": "異なる利点を示すH2見出しを5つ書き、各見出しの下に約100語相当の段落を置いてください。第1・3・5段落では商品名全体を繰り返さず、第2・4段落では自然に一度だけ含めてください。最後に確認済みの技術仕様を3~10項目列挙し、未確認の情報は作らないでください。",
|
||||
"meta": "メタディスクリプションは新しい商品名から始め、空白を含めて最大140文字にしてください。"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package aiprompts
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// Shipped, human-readable platform instructions for every supported content
|
||||
// language. This is offline reference data, not a request to an LLM.
|
||||
//
|
||||
//go:embed defaults/prompt-rules-25.json
|
||||
var offlinePromptRulesJSON []byte
|
||||
|
||||
type offlineRules struct {
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Meta string `json:"meta"`
|
||||
}
|
||||
|
||||
var offlinePromptOnce sync.Once
|
||||
var offlinePrompts map[string]offlineRules
|
||||
var offlinePromptErr error
|
||||
|
||||
// OfflineDefaultPrompt returns a fully localized, A1-style platform template.
|
||||
// Original category-specific English title instructions continue to live in
|
||||
// the English wildcard and the structured title_template; this shared default
|
||||
// uses the standard brand/type/model/color formula for non-English languages.
|
||||
// Returns an error, rather than silently falling back to English, if a locale
|
||||
// has no bundled translation.
|
||||
func OfflineDefaultPrompt(lang string) (string, error) {
|
||||
offlinePromptOnce.Do(func() {
|
||||
offlinePromptErr = json.Unmarshal(offlinePromptRulesJSON, &offlinePrompts)
|
||||
})
|
||||
if offlinePromptErr != nil {
|
||||
return "", fmt.Errorf("load bundled prompts: %w", offlinePromptErr)
|
||||
}
|
||||
rule, ok := offlinePrompts[lang]
|
||||
if !ok || strings.TrimSpace(rule.Title) == "" || strings.TrimSpace(rule.Description) == "" || strings.TrimSpace(rule.Meta) == "" {
|
||||
return "", fmt.Errorf("no bundled category formula for language %q", lang)
|
||||
}
|
||||
// The editor and processing pipeline interpret each role section using
|
||||
// the exact marker syntax below. Body structure is defined in the
|
||||
// localized Description instructions (five *different* H2/paragraphs),
|
||||
// not by copying a repeated HTML instruction five times.
|
||||
return "--- Title ---\n" + rule.Title +
|
||||
"\n--- End Title ---\n\n--- Description ---\n" + rule.Description +
|
||||
"\n--- End Description ---\n\n--- Meta ---\n" + rule.Meta +
|
||||
"\n--- End Meta ---", nil
|
||||
}
|
||||
|
||||
func OfflinePromptLanguages() []string {
|
||||
offlinePromptOnce.Do(func() { offlinePromptErr = json.Unmarshal(offlinePromptRulesJSON, &offlinePrompts) })
|
||||
out := make([]string, 0, len(offlinePrompts))
|
||||
for lang := range offlinePrompts {
|
||||
out = append(out, lang)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package aiprompts
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAllBundledLanguageRules(t *testing.T) {
|
||||
want := []string{"en", "fr", "de", "es", "it", "nl", "pt", "pl", "cs", "sk", "hu", "ro", "bg", "hr", "sl", "sv", "da", "fi", "el", "et", "lv", "lt", "mt", "ga", "ja"}
|
||||
if len(OfflinePromptLanguages()) != len(want) {
|
||||
t.Fatalf("need 25 locales, have %d", len(OfflinePromptLanguages()))
|
||||
}
|
||||
for _, lang := range want {
|
||||
prompt, err := OfflineDefaultPrompt(lang)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tag := range []string{"--- Title ---", "--- End Title ---", "--- Description ---", "--- End Description ---", "--- Meta ---", "--- End Meta ---"} {
|
||||
if !strings.Contains(prompt, tag) {
|
||||
t.Fatalf("missing %q in %s", tag, lang)
|
||||
}
|
||||
}
|
||||
if len(prompt) > 8000 {
|
||||
t.Fatalf("too long %s", lang)
|
||||
}
|
||||
if strings.Contains(prompt, "{{attrs}}") {
|
||||
t.Fatalf("unexpected placeholder in prelocalized instruction %s", lang)
|
||||
}
|
||||
}
|
||||
if _, err := OfflineDefaultPrompt("invalid"); err == nil {
|
||||
t.Fatal("unknown language silently fell back")
|
||||
}
|
||||
}
|
||||
@@ -26,24 +26,24 @@ const platformDemoCompanyName = "Platform Demo"
|
||||
// RepairCategoryEnhancePromptsResult is the dry-run / apply summary for
|
||||
// RepairA1DemoCategoryEnhancePrompts.
|
||||
type RepairCategoryEnhancePromptsResult struct {
|
||||
CompaniesScanned int `json:"companies_scanned"`
|
||||
CategoriesSeen int `json:"categories_seen"`
|
||||
WouldUpdate int `json:"would_update"`
|
||||
Updated int `json:"updated"`
|
||||
AlreadyOK int `json:"already_ok"`
|
||||
EmptySkipped int `json:"empty_skipped"`
|
||||
SeedMatched int `json:"seed_matched"`
|
||||
SplitFromLegacy int `json:"split_from_legacy"`
|
||||
FallbackTemplate int `json:"fallback_template"`
|
||||
TitleTemplateBackfill int `json:"title_template_backfill"`
|
||||
DescTemplateBackfill int `json:"description_template_backfill"`
|
||||
CompaniesScanned int `json:"companies_scanned"`
|
||||
CategoriesSeen int `json:"categories_seen"`
|
||||
WouldUpdate int `json:"would_update"`
|
||||
Updated int `json:"updated"`
|
||||
AlreadyOK int `json:"already_ok"`
|
||||
EmptySkipped int `json:"empty_skipped"`
|
||||
SeedMatched int `json:"seed_matched"`
|
||||
SplitFromLegacy int `json:"split_from_legacy"`
|
||||
FallbackTemplate int `json:"fallback_template"`
|
||||
TitleTemplateBackfill int `json:"title_template_backfill"`
|
||||
DescTemplateBackfill int `json:"description_template_backfill"`
|
||||
// *_Cleared count non-seed categories whose leftover formula artifacts
|
||||
// (English defaults from earlier repairs / cats.json / migration) were removed.
|
||||
TitleTemplateCleared int `json:"title_template_cleared"`
|
||||
DescTemplateCleared int `json:"description_template_cleared"`
|
||||
ByCompany map[string]int `json:"by_company"`
|
||||
DryRun bool `json:"dry_run"`
|
||||
SeedPath string `json:"seed_path,omitempty"`
|
||||
TitleTemplateCleared int `json:"title_template_cleared"`
|
||||
DescTemplateCleared int `json:"description_template_cleared"`
|
||||
ByCompany map[string]int `json:"by_company"`
|
||||
DryRun bool `json:"dry_run"`
|
||||
SeedPath string `json:"seed_path,omitempty"`
|
||||
// WPCategoriesPath is set when overlays came from wp_product_categories.sql.
|
||||
WPCategoriesPath string `json:"wp_categories_path,omitempty"`
|
||||
SeedEntries int `json:"seed_entries,omitempty"`
|
||||
@@ -285,6 +285,7 @@ func loadA1CategoryPromptOverlays(path string) (byNorm map[string]string, byUID
|
||||
}
|
||||
for _, e := range f.Entries {
|
||||
p := strings.TrimSpace(e.Prompt)
|
||||
p, _ = aiprompts.NormalizeA1RepeatedBenefits(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -8,6 +8,8 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/descrybe/descrybe-v2/apps/api/internal/aiprompts"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -157,6 +159,7 @@ func LoadWPCategoryPromptOverlaysFromBytes(raw []byte) (byNorm map[string]string
|
||||
}
|
||||
for _, e := range entries {
|
||||
p := strings.TrimSpace(e.Prompt)
|
||||
p, _ = aiprompts.NormalizeA1RepeatedBenefits(p)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user