Files
descrybe/apps/api/internal/aiprompts/a1_dedupe.go
T

331 lines
11 KiB
Go
Raw Normal View History

2026-10-14 18:18:54 +02:00
package aiprompts
import (
2026-10-14 18:47:00 +02:00
"encoding/json"
"fmt"
2026-10-14 18:18:54 +02:00
"regexp"
"strings"
)
// A1's historical content sometimes repeats the exact same H2/paragraph pair.
// Remove only identical pairs; different benefits, paragraph inclusion rules,
// technical specifications and all non-description instructions stay intact.
var a1HeadingParagraph = regexp.MustCompile(`(?is)<\s*h[1-4]\s*>.*?<\s*/\s*h[1-4]\s*>\s*<\s*p\s*>.*?<\s*/\s*p\s*>`)
var a1Whitespace = regexp.MustCompile(`\s+`)
func DedupeA1DescriptionBlocks(source string) (string, int) {
blocks := a1HeadingParagraph.FindAllStringIndex(source, -1)
if len(blocks) < 2 {
return source, 0
}
seen := make(map[string]bool, len(blocks))
var out strings.Builder
out.Grow(len(source))
cursor, removed := 0, 0
for _, b := range blocks {
part := source[b[0]:b[1]]
key := strings.ToLower(a1Whitespace.ReplaceAllString(strings.TrimSpace(part), " "))
// Keep non-description content exactly as it was. Removing an exact
// repeated pair must not also delete the next section or specs.
out.WriteString(source[cursor:b[0]])
if seen[key] {
removed++
} else {
seen[key] = true
out.WriteString(part)
}
cursor = b[1]
}
out.WriteString(source[cursor:])
if removed == 0 {
return source, 0
}
// Do not rewrite punctuation/case/brand-specific rules.
return out.String(), removed
}
2026-10-14 18:47:00 +02:00
// 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"], &sections); 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]:]
}
2026-10-14 19:23:16 +02:00
// isKnownA1Boilerplate only targets the old generated five-benefit formula.
// User-authored copy (even if it contains multiple H2s) is never replaced.
func isKnownA1Boilerplate(body string, blocks int) bool {
if blocks < 4 {
return false
}
lower := strings.ToLower(body)
return (strings.Contains(lower, "napiši odstavek, ki je dolg 100 besed") ||
strings.Contains(lower, "drugačno in preverjeno prednost") ||
strings.Contains(lower, "napiši približno 100 besed o")) &&
(strings.Contains(lower, "novo ime izdelka") || strings.Contains(lower, "prednost izdelka"))
}
func localizedA1SEODescription() string {
prompt, err := OfflineDefaultPrompt("sl")
if err != nil {
return ""
}
return DescriptionSectionInstructions(prompt)
}
var a1SpecTrailing = regexp.MustCompile(`(?is)^\s*<\s*b\s*>.*?<\s*/\s*b\s*>\s*<\s*ul\s*>.*?<\s*/\s*ul\s*>`)
// upgradeKnownA1Boilerplate replaces only the recognizable generated legacy
// five-benefit scaffold with short, factual HTML. The title/meta roles and
// surrounding category-specific instructions are kept untouched.
func upgradeKnownA1Boilerplate(source string) (string, int) {
blocks := a1HeadingParagraph.FindAllStringIndex(source, -1)
if !isKnownA1Boilerplate(source, len(blocks)) {
return source, 0
}
html := localizedA1SEODescription()
if html == "" {
return source, 0
}
start, end := blocks[0][0], blocks[len(blocks)-1][1]
if match := a1SpecTrailing.FindStringIndex(source[end:]); len(match) == 2 && match[0] == 0 {
end += match[1]
}
return source[:start] + html + source[end:], len(blocks)
}
// upgradeKnownA1Sections is equally narrow for JSON description_template.
// It retains the existing metaTitle/metaDescription and unknown JSON fields.
func upgradeKnownA1Sections(raw string) (string, int, error) {
var obj map[string]json.RawMessage
if err := json.Unmarshal([]byte(raw), &obj); err != nil {
return raw, 0, err
}
var sections []DescriptionFormulaSection
if err := json.Unmarshal(obj["sections"], &sections); err != nil {
return raw, 0, nil
}
var joined strings.Builder
pairs := 0
for i := 0; i+1 < len(sections); i++ {
if sections[i].Type == "h2" && sections[i+1].Type == "p" {
joined.WriteString(sections[i].Instructions + " " + sections[i+1].Instructions + " ")
pairs++
i++
}
}
if !isKnownA1Boilerplate(joined.String(), pairs) {
return raw, 0, nil
}
seo := localizedA1SEODescription()
parsed := DeriveDescriptionFormulaFromLegacyParts(LegacyEnhanceParts{DescriptionRules: seo, WasLegacy: true})
if len(parsed.Sections) != 5 {
return raw, 0, fmt.Errorf("invalid bundled Slovenian description")
}
encoded, err := json.Marshal(parsed.Sections)
if err != nil {
return raw, 0, err
}
obj["sections"] = encoded
out, err := json.Marshal(obj)
if err != nil {
return raw, 0, err
}
return string(out), pairs, nil
}
2026-10-14 18:47:00 +02:00
func NormalizeA1RepeatedBenefits(source string) (string, int) {
2026-10-14 19:23:16 +02:00
if cleaned, n := upgradeKnownA1Boilerplate(source); n > 0 {
return cleaned, n
}
2026-10-14 18:47:00 +02:00
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) {
2026-10-14 19:23:16 +02:00
if cleaned, n, err := upgradeKnownA1Sections(raw); err != nil || n > 0 {
return cleaned, n, err
}
2026-10-14 18:47:00 +02:00
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"], &sections); 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"], &paragraphType)
if !strings.EqualFold(headingType, "h2") || !strings.EqualFold(paragraphType, "p") {
continue
}
_ = json.Unmarshal(sections[i]["instructions"], &heading)
_ = json.Unmarshal(sections[i+1]["instructions"], &paragraph)
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
}