360 lines
12 KiB
Go
360 lines
12 KiB
Go
package aiprompts
|
||
|
||
import (
|
||
"encoding/json"
|
||
"fmt"
|
||
"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
|
||
}
|
||
|
||
// 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]:]
|
||
}
|
||
|
||
// isKnownA1Boilerplate recognizes the exact historical A1-generated
|
||
// instructions, even when a previous cleanup left only one to three pairs.
|
||
// Generic custom HTML with H2/P sections must never be replaced.
|
||
func isKnownA1Boilerplate(body string, blocks int) bool {
|
||
if blocks < 1 {
|
||
return false
|
||
}
|
||
lower := strings.ToLower(a1Whitespace.ReplaceAllString(strings.TrimSpace(body), " "))
|
||
legacy := strings.Contains(lower, "napiši odstavek, ki je dolg 100 besed")
|
||
cableLegacy := strings.Contains(lower, "nadaljuj iz naslova in napiši 100 besed") &&
|
||
strings.Contains(lower, "novo_ime_izdelka")
|
||
if !legacy && !cableLegacy {
|
||
return false
|
||
}
|
||
return (strings.Contains(lower, "novo ime izdelka") || strings.Contains(lower, "novo_ime_izdelka")) &&
|
||
(strings.Contains(lower, "izpostavi en benefit") ||
|
||
strings.Contains(lower, "prednost izdelka") ||
|
||
strings.Contains(lower, "preverjeno prednost"))
|
||
}
|
||
|
||
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*>`)
|
||
var a1RedundantH1 = regexp.MustCompile(`(?is)<\s*h1\s*>\s*\{\s*zapiši\s+novo_ime_izdelka\s*\}\s*<\s*/\s*h1\s*>\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 {
|
||
// Discard only the old generic spec instruction. A category-specific
|
||
// technical specification rule must remain intact.
|
||
trailing := strings.ToLower(source[end : end+match[1]])
|
||
if strings.Contains(trailing, "napiši 3-10 tehničnih specifikacij") ||
|
||
strings.Contains(trailing, "napiši 3–10 tehničnih specifikacij") {
|
||
end += match[1]
|
||
}
|
||
}
|
||
updated := source[:start] + html + source[end:]
|
||
// Only the known imported A1 scaffold generates a redundant page H1.
|
||
// The storefront already renders its own H1 from the product title.
|
||
updated = a1RedundantH1.ReplaceAllString(updated, "")
|
||
return updated, 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) {
|
||
// A1 categories frequently have no structured description_template.
|
||
// The HTML prompt alone is valid; an empty JSON column isn't an error.
|
||
trimmed := strings.TrimSpace(raw)
|
||
if trimmed == "" || trimmed == "null" || trimmed == "{}" {
|
||
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 || len(obj["sections"]) == 0 || string(obj["sections"]) == "null" {
|
||
return raw, 0, nil
|
||
}
|
||
var sections []DescriptionFormulaSection
|
||
if err := json.Unmarshal(obj["sections"], §ions); 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
|
||
}
|
||
|
||
func NormalizeA1RepeatedBenefits(source string) (string, int) {
|
||
if cleaned, n := upgradeKnownA1Boilerplate(source); n > 0 {
|
||
return cleaned, n
|
||
}
|
||
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 upgrades recognizable imported A1 description
|
||
// boilerplate to the semantic SEO sections. For unrelated custom descriptions,
|
||
// only repeated instructions are rewritten and sections remain intact.
|
||
func NormalizeA1DescriptionTemplate(raw string) (string, int, error) {
|
||
if cleaned, n, err := upgradeKnownA1Sections(raw); err != nil || n > 0 {
|
||
return cleaned, n, err
|
||
}
|
||
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
|
||
}
|