Spaces:
Running
Running
Add LLM optimizer tab with iterative constrained text improvements
Browse filesIntroduce an OpenAI-compatible optimizer workflow with user-provided API key, local sentence-level edits, per-iteration rescoring, and before/after metric tracking in a dedicated UI tab.
Made-with: Cursor
- app.py +12 -0
- models.py +28 -1
- optimizer.py +538 -0
- templates/index.html +182 -2
app.py
CHANGED
|
@@ -17,6 +17,8 @@ from models import (
|
|
| 17 |
UrlFetchRequest,
|
| 18 |
UrlFetchResponse,
|
| 19 |
UserAgentsResponse,
|
|
|
|
|
|
|
| 20 |
)
|
| 21 |
import logic
|
| 22 |
import nlp_processor
|
|
@@ -25,6 +27,7 @@ import highlighter
|
|
| 25 |
import summarizer
|
| 26 |
import search
|
| 27 |
import url_fetcher
|
|
|
|
| 28 |
|
| 29 |
app = FastAPI(title="SEO AI Editor MVP")
|
| 30 |
|
|
@@ -246,6 +249,15 @@ async def fetch_url_endpoint(request: UrlFetchRequest):
|
|
| 246 |
error=str(e),
|
| 247 |
)
|
| 248 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
# Hugging Face Spaces использует порт 7860
|
| 250 |
if __name__ == "__main__":
|
| 251 |
port = int(os.environ.get("PORT", 7860))
|
|
|
|
| 17 |
UrlFetchRequest,
|
| 18 |
UrlFetchResponse,
|
| 19 |
UserAgentsResponse,
|
| 20 |
+
OptimizerRequest,
|
| 21 |
+
OptimizerResponse,
|
| 22 |
)
|
| 23 |
import logic
|
| 24 |
import nlp_processor
|
|
|
|
| 27 |
import summarizer
|
| 28 |
import search
|
| 29 |
import url_fetcher
|
| 30 |
+
import optimizer
|
| 31 |
|
| 32 |
app = FastAPI(title="SEO AI Editor MVP")
|
| 33 |
|
|
|
|
| 249 |
error=str(e),
|
| 250 |
)
|
| 251 |
|
| 252 |
+
|
| 253 |
+
@app.post("/api/v1/optimizer/run", response_model=OptimizerResponse)
|
| 254 |
+
async def run_optimizer(request: OptimizerRequest):
|
| 255 |
+
try:
|
| 256 |
+
result = optimizer.optimize_text(request.model_dump())
|
| 257 |
+
return OptimizerResponse(**result)
|
| 258 |
+
except Exception as e:
|
| 259 |
+
return OptimizerResponse(ok=False, error=str(e))
|
| 260 |
+
|
| 261 |
# Hugging Face Spaces использует порт 7860
|
| 262 |
if __name__ == "__main__":
|
| 263 |
port = int(os.environ.get("PORT", 7860))
|
models.py
CHANGED
|
@@ -72,4 +72,31 @@ class UserAgentInfo(BaseModel):
|
|
| 72 |
|
| 73 |
|
| 74 |
class UserAgentsResponse(BaseModel):
|
| 75 |
-
user_agents: List[UserAgentInfo] = Field(default_factory=list)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
class UserAgentsResponse(BaseModel):
|
| 75 |
+
user_agents: List[UserAgentInfo] = Field(default_factory=list)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class OptimizerRequest(BaseModel):
|
| 79 |
+
target_text: str
|
| 80 |
+
competitors: List[str] = Field(default_factory=list)
|
| 81 |
+
keywords: List[str] = Field(default_factory=list)
|
| 82 |
+
language: str = "en"
|
| 83 |
+
target_title: str = ""
|
| 84 |
+
competitor_titles: List[str] = Field(default_factory=list)
|
| 85 |
+
|
| 86 |
+
api_key: str
|
| 87 |
+
api_base_url: str = "https://api.deepseek.com/v1"
|
| 88 |
+
model: str = "deepseek-chat"
|
| 89 |
+
|
| 90 |
+
max_iterations: int = 2
|
| 91 |
+
candidates_per_iteration: int = 2
|
| 92 |
+
temperature: float = 0.25
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class OptimizerResponse(BaseModel):
|
| 96 |
+
ok: bool = True
|
| 97 |
+
optimized_text: str = ""
|
| 98 |
+
baseline_metrics: Dict[str, Any] = Field(default_factory=dict)
|
| 99 |
+
final_metrics: Dict[str, Any] = Field(default_factory=dict)
|
| 100 |
+
iterations: List[Dict[str, Any]] = Field(default_factory=list)
|
| 101 |
+
applied_changes: int = 0
|
| 102 |
+
error: str = ""
|
optimizer.py
ADDED
|
@@ -0,0 +1,538 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import re
|
| 3 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 4 |
+
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
import logic
|
| 8 |
+
import nlp_processor
|
| 9 |
+
import semantic_graph
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
STOP_WORDS = {
|
| 13 |
+
"en": {"a", "an", "and", "or", "the", "to", "of", "for", "in", "on", "at", "by", "with", "from", "as", "is", "are", "be", "was", "were"},
|
| 14 |
+
"ru": {"и", "или", "в", "во", "на", "по", "с", "со", "к", "ко", "для", "из", "за", "что", "это", "как", "а", "но", "у", "о", "от"},
|
| 15 |
+
"de": {"und", "oder", "der", "die", "das", "zu", "von", "mit", "fur", "in", "auf", "ist", "sind"},
|
| 16 |
+
"es": {"y", "o", "el", "la", "los", "las", "de", "del", "en", "con", "para", "por", "es", "son"},
|
| 17 |
+
"it": {"e", "o", "il", "lo", "la", "i", "gli", "le", "di", "del", "in", "con", "per", "da", "e", "sono"},
|
| 18 |
+
"pl": {"i", "oraz", "lub", "w", "na", "z", "ze", "do", "od", "po", "dla", "to", "jest", "sa"},
|
| 19 |
+
"pt": {"e", "ou", "o", "a", "os", "as", "de", "do", "da", "em", "no", "na", "com", "para", "por", "e", "sao"},
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _tokenize(text: str) -> List[str]:
|
| 24 |
+
return [
|
| 25 |
+
x
|
| 26 |
+
for x in re.sub(r"[^\w\s-]+", " ", (text or "").lower(), flags=re.UNICODE).split()
|
| 27 |
+
if len(x) >= 2
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _filter_stopwords(tokens: List[str], language: str) -> List[str]:
|
| 32 |
+
stop = STOP_WORDS.get(language, STOP_WORDS["en"])
|
| 33 |
+
return [t for t in tokens if t not in stop]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _split_sentences(text: str) -> List[str]:
|
| 37 |
+
text = (text or "").strip()
|
| 38 |
+
if not text:
|
| 39 |
+
return []
|
| 40 |
+
parts = re.split(r"(?<=[\.\!\?])\s+", text)
|
| 41 |
+
parts = [p.strip() for p in parts if p.strip()]
|
| 42 |
+
if len(parts) <= 1:
|
| 43 |
+
parts = [p.strip() for p in re.split(r"\n+", text) if p.strip()]
|
| 44 |
+
return parts
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _build_analysis_snapshot(
|
| 48 |
+
target_text: str,
|
| 49 |
+
competitors: List[str],
|
| 50 |
+
keywords: List[str],
|
| 51 |
+
language: str,
|
| 52 |
+
target_title: str,
|
| 53 |
+
competitor_titles: List[str],
|
| 54 |
+
) -> Dict[str, Any]:
|
| 55 |
+
wc_target = logic.count_words(target_text, language)
|
| 56 |
+
wc_comp = [logic.count_words(t, language) for t in competitors]
|
| 57 |
+
if wc_comp:
|
| 58 |
+
avg_total = sum(c["total"] for c in wc_comp) / len(wc_comp)
|
| 59 |
+
avg_sig = sum(c["significant"] for c in wc_comp) / len(wc_comp)
|
| 60 |
+
else:
|
| 61 |
+
avg_total = 0
|
| 62 |
+
avg_sig = 0
|
| 63 |
+
|
| 64 |
+
ngram_stats = logic.calculate_ngram_stats(target_text, competitors, language)
|
| 65 |
+
key_phrases, _ = logic.parse_keywords(keywords, language)
|
| 66 |
+
bm25 = logic.calculate_bm25_recommendations(target_text, competitors, keywords, language)
|
| 67 |
+
bert = logic.perform_bert_analysis(target_text, competitors, key_phrases, language)
|
| 68 |
+
|
| 69 |
+
title_data = {}
|
| 70 |
+
if (target_title or "").strip():
|
| 71 |
+
title_data = logic.analyze_title(target_title, competitor_titles, keywords, language)
|
| 72 |
+
|
| 73 |
+
return {
|
| 74 |
+
"word_counts": {
|
| 75 |
+
"target": wc_target,
|
| 76 |
+
"competitors": wc_comp,
|
| 77 |
+
"avg": {"total": round(avg_total), "significant": round(avg_sig)},
|
| 78 |
+
},
|
| 79 |
+
"ngram_stats": ngram_stats,
|
| 80 |
+
"bm25_recommendations": bm25,
|
| 81 |
+
"bert_analysis": bert,
|
| 82 |
+
"title_analysis": title_data,
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _build_semantic_snapshot(
|
| 87 |
+
target_text: str,
|
| 88 |
+
competitors: List[str],
|
| 89 |
+
language: str,
|
| 90 |
+
) -> Dict[str, Any]:
|
| 91 |
+
def _build_doc(text: str, doc_id: int) -> Dict[str, Any]:
|
| 92 |
+
sentences_data = nlp_processor.preprocess_text(text, language)
|
| 93 |
+
graph, word_weights = semantic_graph.build_semantic_graph(sentences_data, lang=language)
|
| 94 |
+
graph_data = semantic_graph.get_graph_data_for_frontend(graph)
|
| 95 |
+
return {
|
| 96 |
+
"id": doc_id,
|
| 97 |
+
"text": text,
|
| 98 |
+
"word_weights": word_weights,
|
| 99 |
+
"stats": {
|
| 100 |
+
"nodes": len(graph_data.get("nodes", [])),
|
| 101 |
+
"links": len(graph_data.get("links", [])),
|
| 102 |
+
},
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
target_doc = _build_doc(target_text, 0)
|
| 106 |
+
comp_docs = []
|
| 107 |
+
for idx, c in enumerate([x for x in competitors if (x or "").strip()]):
|
| 108 |
+
comp_docs.append(_build_doc(c, idx + 1))
|
| 109 |
+
|
| 110 |
+
num_comp = len(comp_docs)
|
| 111 |
+
target_weights = target_doc["word_weights"]
|
| 112 |
+
all_terms = set(target_weights.keys())
|
| 113 |
+
for c in comp_docs:
|
| 114 |
+
all_terms.update(c["word_weights"].keys())
|
| 115 |
+
|
| 116 |
+
term_power_table = []
|
| 117 |
+
for term in all_terms:
|
| 118 |
+
target_weight = int(target_weights.get(term, 0))
|
| 119 |
+
comp_weights = [int(c["word_weights"].get(term, 0)) for c in comp_docs]
|
| 120 |
+
comp_avg = round(sum(comp_weights) / max(1, num_comp), 2)
|
| 121 |
+
comp_occ = sum(1 for w in comp_weights if w > 0)
|
| 122 |
+
term_power_table.append(
|
| 123 |
+
{
|
| 124 |
+
"term": term,
|
| 125 |
+
"target_weight": target_weight,
|
| 126 |
+
"competitor_avg_weight": comp_avg,
|
| 127 |
+
"comp_occurrence": comp_occ,
|
| 128 |
+
"comp_total": num_comp,
|
| 129 |
+
}
|
| 130 |
+
)
|
| 131 |
+
return {"comparison": {"term_power_table": term_power_table, "num_competitors": num_comp}}
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _compute_metrics(analysis: Dict[str, Any], semantic: Dict[str, Any], keywords: List[str], language: str) -> Dict[str, Any]:
|
| 135 |
+
competitor_count = len(analysis.get("word_counts", {}).get("competitors", []))
|
| 136 |
+
min_signal = 1 if competitor_count <= 1 else 2
|
| 137 |
+
|
| 138 |
+
bert_details = analysis.get("bert_analysis", {}).get("detailed", []) or []
|
| 139 |
+
bert_low = [d for d in bert_details if float(d.get("my_max_score", 0)) < 0.7]
|
| 140 |
+
|
| 141 |
+
bm25_remove = [x for x in (analysis.get("bm25_recommendations") or []) if x.get("action") == "remove"]
|
| 142 |
+
bm25_remove_count = len(bm25_remove)
|
| 143 |
+
|
| 144 |
+
ngram_signal_count = 0
|
| 145 |
+
ngrams = analysis.get("ngram_stats", {}) or {}
|
| 146 |
+
for bucket_name in ("unigrams", "bigrams"):
|
| 147 |
+
for item in (ngrams.get(bucket_name) or []):
|
| 148 |
+
comp_occ = int(item.get("comp_occurrence", 0))
|
| 149 |
+
if comp_occ < min_signal:
|
| 150 |
+
continue
|
| 151 |
+
target = float(item.get("target_count", 0))
|
| 152 |
+
comp_avg = float(item.get("competitor_avg", 0))
|
| 153 |
+
ratio_signal = comp_avg > 0 if target == 0 else comp_avg >= target * 2
|
| 154 |
+
if ratio_signal:
|
| 155 |
+
ngram_signal_count += 1
|
| 156 |
+
|
| 157 |
+
title_score = None
|
| 158 |
+
title_bert = analysis.get("title_analysis", {}).get("bert", {})
|
| 159 |
+
if title_bert and title_bert.get("target_score") is not None:
|
| 160 |
+
title_score = float(title_bert.get("target_score", 0))
|
| 161 |
+
|
| 162 |
+
keyword_terms = set()
|
| 163 |
+
for kw in keywords:
|
| 164 |
+
tokens = _filter_stopwords(_tokenize(kw), language)
|
| 165 |
+
for t in tokens:
|
| 166 |
+
keyword_terms.add(t)
|
| 167 |
+
for n in (2, 3):
|
| 168 |
+
for i in range(0, max(0, len(tokens) - n + 1)):
|
| 169 |
+
keyword_terms.add(" ".join(tokens[i : i + n]))
|
| 170 |
+
|
| 171 |
+
table = semantic.get("comparison", {}).get("term_power_table", []) or []
|
| 172 |
+
by_term = {str(r.get("term", "")).lower(): r for r in table}
|
| 173 |
+
semantic_gap_count = 0
|
| 174 |
+
for term in keyword_terms:
|
| 175 |
+
row = by_term.get(term)
|
| 176 |
+
if not row:
|
| 177 |
+
continue
|
| 178 |
+
gap = float(row.get("competitor_avg_weight", 0)) - float(row.get("target_weight", 0))
|
| 179 |
+
if gap > 0 and int(row.get("comp_occurrence", 0)) >= min_signal:
|
| 180 |
+
semantic_gap_count += 1
|
| 181 |
+
|
| 182 |
+
# Composite score (0..100)
|
| 183 |
+
w_bert, w_bm25, w_ng, w_title, w_sem = 30, 20, 15, 10, 25
|
| 184 |
+
bert_comp = 1.0 - (len(bert_low) / max(1, len(bert_details)))
|
| 185 |
+
bm25_comp = 1.0 if bm25_remove_count <= 3 else max(0.0, 1.0 - ((bm25_remove_count - 3) / 10.0))
|
| 186 |
+
ng_comp = max(0.0, 1.0 - (ngram_signal_count / 15.0))
|
| 187 |
+
title_comp = 1.0 if title_score is None else min(1.0, max(0.0, title_score / 0.65))
|
| 188 |
+
sem_comp = max(0.0, 1.0 - (semantic_gap_count / 20.0))
|
| 189 |
+
|
| 190 |
+
weighted = (
|
| 191 |
+
w_bert * bert_comp
|
| 192 |
+
+ w_bm25 * bm25_comp
|
| 193 |
+
+ w_ng * ng_comp
|
| 194 |
+
+ w_title * title_comp
|
| 195 |
+
+ w_sem * sem_comp
|
| 196 |
+
)
|
| 197 |
+
total_w = w_bert + w_bm25 + w_ng + w_title + w_sem
|
| 198 |
+
score = round((weighted / total_w) * 100.0, 2)
|
| 199 |
+
|
| 200 |
+
return {
|
| 201 |
+
"score": score,
|
| 202 |
+
"competitor_count": competitor_count,
|
| 203 |
+
"min_competitor_signal": min_signal,
|
| 204 |
+
"bert_low_count": len(bert_low),
|
| 205 |
+
"bert_total_keywords": len(bert_details),
|
| 206 |
+
"bm25_remove_count": bm25_remove_count,
|
| 207 |
+
"ngram_signal_count": ngram_signal_count,
|
| 208 |
+
"title_bert_score": title_score,
|
| 209 |
+
"semantic_gap_count": semantic_gap_count,
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _choose_optimization_goal(analysis: Dict[str, Any], semantic: Dict[str, Any], keywords: List[str], language: str) -> Dict[str, Any]:
|
| 214 |
+
bert_details = analysis.get("bert_analysis", {}).get("detailed", []) or []
|
| 215 |
+
low_bert = [x for x in bert_details if float(x.get("my_max_score", 0)) < 0.7]
|
| 216 |
+
if low_bert:
|
| 217 |
+
worst = sorted(low_bert, key=lambda x: float(x.get("my_max_score", 0)))[0]
|
| 218 |
+
focus_terms = _filter_stopwords(_tokenize(worst.get("phrase", "")), language)[:4]
|
| 219 |
+
return {"type": "bert", "label": str(worst.get("phrase", "")), "focus_terms": focus_terms, "avoid_terms": []}
|
| 220 |
+
|
| 221 |
+
bm25_remove = [x for x in (analysis.get("bm25_recommendations") or []) if x.get("action") == "remove"]
|
| 222 |
+
if len(bm25_remove) >= 4:
|
| 223 |
+
spam_terms = [str(x.get("word", "")) for x in sorted(bm25_remove, key=lambda r: int(r.get("count", 0)), reverse=True)[:4]]
|
| 224 |
+
return {"type": "bm25", "label": "reduce spam", "focus_terms": [], "avoid_terms": spam_terms}
|
| 225 |
+
|
| 226 |
+
# Semantic keyword gaps
|
| 227 |
+
lang_stop = STOP_WORDS.get(language, STOP_WORDS["en"])
|
| 228 |
+
keyword_terms = set()
|
| 229 |
+
for kw in keywords:
|
| 230 |
+
toks = [t for t in _tokenize(kw) if t not in lang_stop]
|
| 231 |
+
keyword_terms.update(toks)
|
| 232 |
+
for n in (2, 3):
|
| 233 |
+
for i in range(0, max(0, len(toks) - n + 1)):
|
| 234 |
+
keyword_terms.add(" ".join(toks[i : i + n]))
|
| 235 |
+
table = semantic.get("comparison", {}).get("term_power_table", []) or []
|
| 236 |
+
candidate_rows: List[Tuple[str, float]] = []
|
| 237 |
+
for row in table:
|
| 238 |
+
term = str(row.get("term", "")).lower()
|
| 239 |
+
if term not in keyword_terms:
|
| 240 |
+
continue
|
| 241 |
+
gap = float(row.get("competitor_avg_weight", 0)) - float(row.get("target_weight", 0))
|
| 242 |
+
if gap > 0:
|
| 243 |
+
candidate_rows.append((term, gap))
|
| 244 |
+
if candidate_rows:
|
| 245 |
+
top_term = sorted(candidate_rows, key=lambda x: x[1], reverse=True)[0][0]
|
| 246 |
+
return {"type": "semantic", "label": top_term, "focus_terms": [top_term], "avoid_terms": []}
|
| 247 |
+
|
| 248 |
+
# Fallback: ngram add signal
|
| 249 |
+
for bucket_name in ("unigrams", "bigrams"):
|
| 250 |
+
bucket = analysis.get("ngram_stats", {}).get(bucket_name, []) or []
|
| 251 |
+
for item in bucket:
|
| 252 |
+
target = float(item.get("target_count", 0))
|
| 253 |
+
comp_avg = float(item.get("competitor_avg", 0))
|
| 254 |
+
if (target == 0 and comp_avg > 0) or (target > 0 and comp_avg >= target * 2):
|
| 255 |
+
return {"type": "ngram", "label": str(item.get("ngram", "")), "focus_terms": _tokenize(str(item.get("ngram", "")))[:3], "avoid_terms": []}
|
| 256 |
+
|
| 257 |
+
return {"type": "none", "label": "no-op", "focus_terms": [], "avoid_terms": []}
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def _choose_sentence_idx(sentences: List[str], focus_terms: List[str], avoid_terms: List[str], language: str) -> int:
|
| 261 |
+
if not sentences:
|
| 262 |
+
return 0
|
| 263 |
+
stop = STOP_WORDS.get(language, STOP_WORDS["en"])
|
| 264 |
+
focus = [x for x in focus_terms if x and x not in stop]
|
| 265 |
+
|
| 266 |
+
if avoid_terms:
|
| 267 |
+
best_idx, best_score = 0, -1.0
|
| 268 |
+
for i, s in enumerate(sentences):
|
| 269 |
+
lower = s.lower()
|
| 270 |
+
score = sum(lower.count(t.lower()) for t in avoid_terms if t)
|
| 271 |
+
if score > best_score:
|
| 272 |
+
best_idx, best_score = i, score
|
| 273 |
+
return best_idx
|
| 274 |
+
|
| 275 |
+
if focus:
|
| 276 |
+
best_idx, best_score = 0, -1.0
|
| 277 |
+
for i, s in enumerate(sentences):
|
| 278 |
+
lower = s.lower()
|
| 279 |
+
score = sum(lower.count(t.lower()) for t in focus)
|
| 280 |
+
if score > best_score:
|
| 281 |
+
best_idx, best_score = i, score
|
| 282 |
+
return best_idx
|
| 283 |
+
|
| 284 |
+
return min(2, len(sentences) - 1)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def _extract_json_object(text: str) -> Optional[Dict[str, Any]]:
|
| 288 |
+
raw = (text or "").strip()
|
| 289 |
+
if not raw:
|
| 290 |
+
return None
|
| 291 |
+
try:
|
| 292 |
+
return json.loads(raw)
|
| 293 |
+
except Exception:
|
| 294 |
+
pass
|
| 295 |
+
m = re.search(r"\{[\s\S]*\}", raw)
|
| 296 |
+
if not m:
|
| 297 |
+
return None
|
| 298 |
+
try:
|
| 299 |
+
return json.loads(m.group(0))
|
| 300 |
+
except Exception:
|
| 301 |
+
return None
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _llm_rewrite_sentence(
|
| 305 |
+
*,
|
| 306 |
+
api_key: str,
|
| 307 |
+
base_url: str,
|
| 308 |
+
model: str,
|
| 309 |
+
language: str,
|
| 310 |
+
full_text: str,
|
| 311 |
+
original_sentence: str,
|
| 312 |
+
goal_type: str,
|
| 313 |
+
goal_label: str,
|
| 314 |
+
focus_terms: List[str],
|
| 315 |
+
avoid_terms: List[str],
|
| 316 |
+
temperature: float,
|
| 317 |
+
) -> str:
|
| 318 |
+
endpoint = base_url.rstrip("/") + "/chat/completions"
|
| 319 |
+
system_msg = (
|
| 320 |
+
"You are an SEO copy editor. Edit only one sentence while preserving narrative flow, factual tone, and language. "
|
| 321 |
+
"Return strict JSON only: {\"revised_sentence\": \"...\"}. "
|
| 322 |
+
"Do not rewrite the whole text."
|
| 323 |
+
)
|
| 324 |
+
user_msg = (
|
| 325 |
+
f"Language: {language}\n"
|
| 326 |
+
f"Goal: {goal_type} ({goal_label})\n"
|
| 327 |
+
f"Must preserve overall narrative and style.\n"
|
| 328 |
+
f"Focus terms to strengthen: {', '.join(focus_terms) if focus_terms else '-'}\n"
|
| 329 |
+
f"Terms to de-emphasize/avoid overuse: {', '.join(avoid_terms) if avoid_terms else '-'}\n\n"
|
| 330 |
+
f"Original sentence:\n{original_sentence}\n\n"
|
| 331 |
+
f"Context text:\n{full_text[:6000]}\n\n"
|
| 332 |
+
"Constraints:\n"
|
| 333 |
+
"1) Keep sentence length reasonable.\n"
|
| 334 |
+
"2) Keep local coherence with surrounding text.\n"
|
| 335 |
+
"3) Only output JSON object."
|
| 336 |
+
)
|
| 337 |
+
payload = {
|
| 338 |
+
"model": model,
|
| 339 |
+
"temperature": float(max(0.0, min(1.2, temperature))),
|
| 340 |
+
"messages": [
|
| 341 |
+
{"role": "system", "content": system_msg},
|
| 342 |
+
{"role": "user", "content": user_msg},
|
| 343 |
+
],
|
| 344 |
+
"response_format": {"type": "json_object"},
|
| 345 |
+
}
|
| 346 |
+
headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
|
| 347 |
+
response = requests.post(endpoint, headers=headers, json=payload, timeout=60)
|
| 348 |
+
response.raise_for_status()
|
| 349 |
+
data = response.json()
|
| 350 |
+
content = (
|
| 351 |
+
data.get("choices", [{}])[0]
|
| 352 |
+
.get("message", {})
|
| 353 |
+
.get("content", "")
|
| 354 |
+
)
|
| 355 |
+
parsed = _extract_json_object(content)
|
| 356 |
+
if not parsed or not str(parsed.get("revised_sentence", "")).strip():
|
| 357 |
+
raise ValueError("LLM returned invalid JSON edit payload.")
|
| 358 |
+
return str(parsed["revised_sentence"]).strip()
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def _is_candidate_valid(prev_metrics: Dict[str, Any], next_metrics: Dict[str, Any]) -> bool:
|
| 362 |
+
if next_metrics["bert_low_count"] > prev_metrics["bert_low_count"]:
|
| 363 |
+
return False
|
| 364 |
+
if next_metrics["bm25_remove_count"] > prev_metrics["bm25_remove_count"]:
|
| 365 |
+
return False
|
| 366 |
+
if next_metrics["semantic_gap_count"] > prev_metrics["semantic_gap_count"]:
|
| 367 |
+
return False
|
| 368 |
+
prev_title = prev_metrics.get("title_bert_score")
|
| 369 |
+
next_title = next_metrics.get("title_bert_score")
|
| 370 |
+
if prev_title is not None and next_title is not None and next_title < (prev_title - 0.03):
|
| 371 |
+
return False
|
| 372 |
+
return True
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def optimize_text(request_data: Dict[str, Any]) -> Dict[str, Any]:
|
| 376 |
+
target_text = str(request_data.get("target_text", "")).strip()
|
| 377 |
+
competitors = [str(x) for x in (request_data.get("competitors") or []) if str(x).strip()]
|
| 378 |
+
keywords = [str(x) for x in (request_data.get("keywords") or []) if str(x).strip()]
|
| 379 |
+
language = str(request_data.get("language", "en")).strip() or "en"
|
| 380 |
+
target_title = str(request_data.get("target_title", "") or "")
|
| 381 |
+
competitor_titles = [str(x) for x in (request_data.get("competitor_titles") or [])]
|
| 382 |
+
|
| 383 |
+
api_key = str(request_data.get("api_key", "")).strip()
|
| 384 |
+
if not api_key:
|
| 385 |
+
raise ValueError("API key is required.")
|
| 386 |
+
base_url = str(request_data.get("api_base_url", "https://api.deepseek.com/v1")).strip() or "https://api.deepseek.com/v1"
|
| 387 |
+
model = str(request_data.get("model", "deepseek-chat")).strip() or "deepseek-chat"
|
| 388 |
+
max_iterations = int(request_data.get("max_iterations", 2) or 2)
|
| 389 |
+
max_iterations = max(1, min(8, max_iterations))
|
| 390 |
+
candidates_per_iteration = int(request_data.get("candidates_per_iteration", 2) or 2)
|
| 391 |
+
candidates_per_iteration = max(1, min(5, candidates_per_iteration))
|
| 392 |
+
temperature = float(request_data.get("temperature", 0.25) or 0.25)
|
| 393 |
+
|
| 394 |
+
baseline_analysis = _build_analysis_snapshot(
|
| 395 |
+
target_text, competitors, keywords, language, target_title, competitor_titles
|
| 396 |
+
)
|
| 397 |
+
baseline_semantic = _build_semantic_snapshot(target_text, competitors, language)
|
| 398 |
+
baseline_metrics = _compute_metrics(baseline_analysis, baseline_semantic, keywords, language)
|
| 399 |
+
|
| 400 |
+
current_text = target_text
|
| 401 |
+
current_analysis = baseline_analysis
|
| 402 |
+
current_semantic = baseline_semantic
|
| 403 |
+
current_metrics = baseline_metrics
|
| 404 |
+
logs: List[Dict[str, Any]] = []
|
| 405 |
+
applied_changes = 0
|
| 406 |
+
|
| 407 |
+
for step in range(max_iterations):
|
| 408 |
+
goal = _choose_optimization_goal(current_analysis, current_semantic, keywords, language)
|
| 409 |
+
if goal["type"] == "none":
|
| 410 |
+
logs.append({"step": step + 1, "status": "stopped", "reason": "No optimization goals left."})
|
| 411 |
+
break
|
| 412 |
+
|
| 413 |
+
sentences = _split_sentences(current_text)
|
| 414 |
+
if not sentences:
|
| 415 |
+
logs.append({"step": step + 1, "status": "stopped", "reason": "No sentences available for editing."})
|
| 416 |
+
break
|
| 417 |
+
|
| 418 |
+
sent_idx = _choose_sentence_idx(sentences, goal["focus_terms"], goal["avoid_terms"], language)
|
| 419 |
+
original_sentence = sentences[sent_idx]
|
| 420 |
+
candidates = []
|
| 421 |
+
|
| 422 |
+
for ci in range(candidates_per_iteration):
|
| 423 |
+
temp = min(1.1, max(0.0, temperature + ci * 0.1))
|
| 424 |
+
try:
|
| 425 |
+
revised_sentence = _llm_rewrite_sentence(
|
| 426 |
+
api_key=api_key,
|
| 427 |
+
base_url=base_url,
|
| 428 |
+
model=model,
|
| 429 |
+
language=language,
|
| 430 |
+
full_text=current_text,
|
| 431 |
+
original_sentence=original_sentence,
|
| 432 |
+
goal_type=goal["type"],
|
| 433 |
+
goal_label=goal["label"],
|
| 434 |
+
focus_terms=goal["focus_terms"],
|
| 435 |
+
avoid_terms=goal["avoid_terms"],
|
| 436 |
+
temperature=temp,
|
| 437 |
+
)
|
| 438 |
+
if not revised_sentence or revised_sentence == original_sentence:
|
| 439 |
+
continue
|
| 440 |
+
|
| 441 |
+
candidate_sentences = sentences[:]
|
| 442 |
+
candidate_sentences[sent_idx] = revised_sentence
|
| 443 |
+
candidate_text = " ".join(candidate_sentences).strip()
|
| 444 |
+
|
| 445 |
+
cand_analysis = _build_analysis_snapshot(
|
| 446 |
+
candidate_text, competitors, keywords, language, target_title, competitor_titles
|
| 447 |
+
)
|
| 448 |
+
cand_semantic = _build_semantic_snapshot(candidate_text, competitors, language)
|
| 449 |
+
cand_metrics = _compute_metrics(cand_analysis, cand_semantic, keywords, language)
|
| 450 |
+
valid = _is_candidate_valid(current_metrics, cand_metrics)
|
| 451 |
+
delta_score = round(cand_metrics["score"] - current_metrics["score"], 3)
|
| 452 |
+
candidates.append(
|
| 453 |
+
{
|
| 454 |
+
"candidate_index": ci + 1,
|
| 455 |
+
"sentence_after": revised_sentence,
|
| 456 |
+
"text": candidate_text,
|
| 457 |
+
"analysis": cand_analysis,
|
| 458 |
+
"semantic": cand_semantic,
|
| 459 |
+
"metrics": cand_metrics,
|
| 460 |
+
"valid": valid,
|
| 461 |
+
"delta_score": delta_score,
|
| 462 |
+
}
|
| 463 |
+
)
|
| 464 |
+
except Exception as e:
|
| 465 |
+
candidates.append(
|
| 466 |
+
{
|
| 467 |
+
"candidate_index": ci + 1,
|
| 468 |
+
"error": str(e),
|
| 469 |
+
"valid": False,
|
| 470 |
+
"delta_score": -999.0,
|
| 471 |
+
}
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
valid_candidates = [c for c in candidates if c.get("valid")]
|
| 475 |
+
if not valid_candidates:
|
| 476 |
+
logs.append(
|
| 477 |
+
{
|
| 478 |
+
"step": step + 1,
|
| 479 |
+
"status": "rejected",
|
| 480 |
+
"goal": goal,
|
| 481 |
+
"sentence_before": original_sentence,
|
| 482 |
+
"reason": "No valid candidate satisfied constraints.",
|
| 483 |
+
"candidates": [
|
| 484 |
+
{
|
| 485 |
+
"candidate_index": c.get("candidate_index"),
|
| 486 |
+
"valid": c.get("valid", False),
|
| 487 |
+
"delta_score": c.get("delta_score"),
|
| 488 |
+
"error": c.get("error"),
|
| 489 |
+
}
|
| 490 |
+
for c in candidates
|
| 491 |
+
],
|
| 492 |
+
}
|
| 493 |
+
)
|
| 494 |
+
break
|
| 495 |
+
|
| 496 |
+
best = sorted(valid_candidates, key=lambda c: c["metrics"]["score"], reverse=True)[0]
|
| 497 |
+
if best["metrics"]["score"] <= current_metrics["score"]:
|
| 498 |
+
logs.append(
|
| 499 |
+
{
|
| 500 |
+
"step": step + 1,
|
| 501 |
+
"status": "rejected",
|
| 502 |
+
"goal": goal,
|
| 503 |
+
"sentence_before": original_sentence,
|
| 504 |
+
"reason": "Best valid candidate did not improve total score.",
|
| 505 |
+
"best_candidate_score": best["metrics"]["score"],
|
| 506 |
+
"current_score": current_metrics["score"],
|
| 507 |
+
}
|
| 508 |
+
)
|
| 509 |
+
break
|
| 510 |
+
|
| 511 |
+
prev_metrics = current_metrics
|
| 512 |
+
current_text = best["text"]
|
| 513 |
+
current_analysis = best["analysis"]
|
| 514 |
+
current_semantic = best["semantic"]
|
| 515 |
+
current_metrics = best["metrics"]
|
| 516 |
+
applied_changes += 1
|
| 517 |
+
|
| 518 |
+
logs.append(
|
| 519 |
+
{
|
| 520 |
+
"step": step + 1,
|
| 521 |
+
"status": "applied",
|
| 522 |
+
"goal": goal,
|
| 523 |
+
"sentence_before": original_sentence,
|
| 524 |
+
"sentence_after": best["sentence_after"],
|
| 525 |
+
"metrics_before": prev_metrics,
|
| 526 |
+
"metrics_after": current_metrics,
|
| 527 |
+
"delta_score": round(current_metrics["score"] - prev_metrics["score"], 3),
|
| 528 |
+
}
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
return {
|
| 532 |
+
"ok": True,
|
| 533 |
+
"optimized_text": current_text,
|
| 534 |
+
"baseline_metrics": baseline_metrics,
|
| 535 |
+
"final_metrics": current_metrics,
|
| 536 |
+
"iterations": logs,
|
| 537 |
+
"applied_changes": applied_changes,
|
| 538 |
+
}
|
templates/index.html
CHANGED
|
@@ -146,6 +146,9 @@
|
|
| 146 |
<li class="nav-item">
|
| 147 |
<button class="nav-link" id="summary-tab" data-bs-toggle="tab" data-bs-target="#summaryPane" type="button">✅ Сводка</button>
|
| 148 |
</li>
|
|
|
|
|
|
|
|
|
|
| 149 |
</ul>
|
| 150 |
|
| 151 |
<div class="tab-content" id="resultsContent">
|
|
@@ -270,6 +273,47 @@
|
|
| 270 |
</div>
|
| 271 |
</div>
|
| 272 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
</div>
|
| 274 |
</div>
|
| 275 |
</div>
|
|
@@ -281,6 +325,7 @@
|
|
| 281 |
<script>
|
| 282 |
let currentData = null;
|
| 283 |
let semanticData = null;
|
|
|
|
| 284 |
let semanticTermSortBy = 'target_weight';
|
| 285 |
let semanticTermSortDir = 'desc';
|
| 286 |
let availableUserAgents = [];
|
|
@@ -486,11 +531,17 @@
|
|
| 486 |
competitor_titles: collectCompetitorTitles(),
|
| 487 |
semantic_threshold: Number(document.getElementById('semanticThreshold').value || 50),
|
| 488 |
semantic_compression: Number(document.getElementById('semanticCompression').value || 0.1),
|
| 489 |
-
semantic_query: document.getElementById('semanticQueryInput').value
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 490 |
},
|
| 491 |
state: {
|
| 492 |
analysis_result: currentData,
|
| 493 |
-
semantic_result: semanticData
|
|
|
|
| 494 |
}
|
| 495 |
};
|
| 496 |
|
|
@@ -529,6 +580,12 @@
|
|
| 529 |
document.getElementById('semanticThreshold').value = 50;
|
| 530 |
document.getElementById('semanticCompression').value = 0.1;
|
| 531 |
document.getElementById('semanticQueryInput').value = '';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 532 |
|
| 533 |
// Competitor text fields
|
| 534 |
const competitorsList = document.getElementById('competitorsList');
|
|
@@ -541,6 +598,7 @@
|
|
| 541 |
// Clear state
|
| 542 |
currentData = null;
|
| 543 |
semanticData = null;
|
|
|
|
| 544 |
|
| 545 |
// Reset result blocks
|
| 546 |
document.getElementById('generalStats').innerHTML = '';
|
|
@@ -554,6 +612,7 @@
|
|
| 554 |
document.getElementById('semanticDocSelect').innerHTML = '<option value="target">Мой текст</option>';
|
| 555 |
document.getElementById('semanticResultsContainer').innerHTML = '<div class="text-center text-muted py-5">Нажмите "Запустить Semantic Core", чтобы построить граф и разметку.</div>';
|
| 556 |
document.getElementById('summaryResultsContainer').innerHTML = '<div class="text-center text-muted py-5">Запустите анализ, чтобы увидеть итоговые рекомендации.</div>';
|
|
|
|
| 557 |
}
|
| 558 |
|
| 559 |
function applyProjectData(project) {
|
|
@@ -574,6 +633,11 @@
|
|
| 574 |
document.getElementById('semanticThreshold').value = inp.semantic_threshold ?? 50;
|
| 575 |
document.getElementById('semanticCompression').value = inp.semantic_compression ?? 0.1;
|
| 576 |
document.getElementById('semanticQueryInput').value = inp.semantic_query || '';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 577 |
|
| 578 |
// Title character counter refresh
|
| 579 |
const titleLen = (inp.target_title || '').length;
|
|
@@ -611,10 +675,12 @@
|
|
| 611 |
// Restore cached analysis results if present
|
| 612 |
currentData = project.state && project.state.analysis_result ? project.state.analysis_result : null;
|
| 613 |
semanticData = project.state && project.state.semantic_result ? project.state.semantic_result : null;
|
|
|
|
| 614 |
|
| 615 |
if (currentData) renderResults(currentData);
|
| 616 |
if (semanticData) renderSemanticResults(semanticData);
|
| 617 |
renderActionSummary(currentData, semanticData);
|
|
|
|
| 618 |
}
|
| 619 |
|
| 620 |
document.getElementById('projectFileInput').addEventListener('change', function(e) {
|
|
@@ -675,6 +741,8 @@
|
|
| 675 |
const data = await response.json();
|
| 676 |
currentData = data;
|
| 677 |
renderResults(data);
|
|
|
|
|
|
|
| 678 |
|
| 679 |
} catch (error) {
|
| 680 |
alert("Ошибка: " + error.message);
|
|
@@ -723,6 +791,118 @@
|
|
| 723 |
}
|
| 724 |
}
|
| 725 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 726 |
async function runSemanticSearch() {
|
| 727 |
const query = document.getElementById('semanticQueryInput').value;
|
| 728 |
const lang = document.getElementById('languageSelect').value;
|
|
|
|
| 146 |
<li class="nav-item">
|
| 147 |
<button class="nav-link" id="summary-tab" data-bs-toggle="tab" data-bs-target="#summaryPane" type="button">✅ Сводка</button>
|
| 148 |
</li>
|
| 149 |
+
<li class="nav-item">
|
| 150 |
+
<button class="nav-link" id="optimizer-tab" data-bs-toggle="tab" data-bs-target="#optimizerPane" type="button">🤖 LLM Optimizer</button>
|
| 151 |
+
</li>
|
| 152 |
</ul>
|
| 153 |
|
| 154 |
<div class="tab-content" id="resultsContent">
|
|
|
|
| 273 |
</div>
|
| 274 |
</div>
|
| 275 |
|
| 276 |
+
<!-- OPTIMIZER TAB -->
|
| 277 |
+
<div class="tab-pane fade" id="optimizerPane" role="tabpanel">
|
| 278 |
+
<div class="stat-card">
|
| 279 |
+
<h5 class="card-title mb-3">LLM Optimizer (итеративная доработка текста)</h5>
|
| 280 |
+
<div class="row g-2">
|
| 281 |
+
<div class="col-md-6">
|
| 282 |
+
<label class="form-label small text-muted mb-1">API Key (пользовательский)</label>
|
| 283 |
+
<input type="password" id="optimizerApiKey" class="form-control" placeholder="sk-...">
|
| 284 |
+
</div>
|
| 285 |
+
<div class="col-md-6">
|
| 286 |
+
<label class="form-label small text-muted mb-1">Base URL (OpenAI-compatible)</label>
|
| 287 |
+
<input type="text" id="optimizerBaseUrl" class="form-control" value="https://api.deepseek.com/v1">
|
| 288 |
+
</div>
|
| 289 |
+
<div class="col-md-4">
|
| 290 |
+
<label class="form-label small text-muted mb-1">Model</label>
|
| 291 |
+
<input type="text" id="optimizerModel" class="form-control" value="deepseek-chat">
|
| 292 |
+
</div>
|
| 293 |
+
<div class="col-md-3">
|
| 294 |
+
<label class="form-label small text-muted mb-1">Итерации</label>
|
| 295 |
+
<input type="number" id="optimizerIterations" class="form-control" min="1" max="8" value="2">
|
| 296 |
+
</div>
|
| 297 |
+
<div class="col-md-3">
|
| 298 |
+
<label class="form-label small text-muted mb-1">Кандидатов/шаг</label>
|
| 299 |
+
<input type="number" id="optimizerCandidates" class="form-control" min="1" max="5" value="2">
|
| 300 |
+
</div>
|
| 301 |
+
<div class="col-md-2">
|
| 302 |
+
<label class="form-label small text-muted mb-1">Temp</label>
|
| 303 |
+
<input type="number" id="optimizerTemp" class="form-control" min="0" max="1.2" step="0.05" value="0.25">
|
| 304 |
+
</div>
|
| 305 |
+
</div>
|
| 306 |
+
<div class="d-flex gap-2 mt-3">
|
| 307 |
+
<button class="btn btn-dark" onclick="runLlmOptimization()">Запустить оптимизацию</button>
|
| 308 |
+
<button class="btn btn-outline-secondary" onclick="applyOptimizedText()">Применить в Target</button>
|
| 309 |
+
</div>
|
| 310 |
+
<p class="small text-muted mt-2 mb-0">API key не сохраняется в проект и используется только для текущего запроса.</p>
|
| 311 |
+
</div>
|
| 312 |
+
<div id="optimizerResultsContainer">
|
| 313 |
+
<div class="text-center text-muted py-5">Запустите основной анализ и затем оптимизацию.</div>
|
| 314 |
+
</div>
|
| 315 |
+
</div>
|
| 316 |
+
|
| 317 |
</div>
|
| 318 |
</div>
|
| 319 |
</div>
|
|
|
|
| 325 |
<script>
|
| 326 |
let currentData = null;
|
| 327 |
let semanticData = null;
|
| 328 |
+
let optimizerData = null;
|
| 329 |
let semanticTermSortBy = 'target_weight';
|
| 330 |
let semanticTermSortDir = 'desc';
|
| 331 |
let availableUserAgents = [];
|
|
|
|
| 531 |
competitor_titles: collectCompetitorTitles(),
|
| 532 |
semantic_threshold: Number(document.getElementById('semanticThreshold').value || 50),
|
| 533 |
semantic_compression: Number(document.getElementById('semanticCompression').value || 0.1),
|
| 534 |
+
semantic_query: document.getElementById('semanticQueryInput').value,
|
| 535 |
+
optimizer_base_url: document.getElementById('optimizerBaseUrl').value,
|
| 536 |
+
optimizer_model: document.getElementById('optimizerModel').value,
|
| 537 |
+
optimizer_iterations: Number(document.getElementById('optimizerIterations').value || 2),
|
| 538 |
+
optimizer_candidates: Number(document.getElementById('optimizerCandidates').value || 2),
|
| 539 |
+
optimizer_temperature: Number(document.getElementById('optimizerTemp').value || 0.25)
|
| 540 |
},
|
| 541 |
state: {
|
| 542 |
analysis_result: currentData,
|
| 543 |
+
semantic_result: semanticData,
|
| 544 |
+
optimizer_result: optimizerData
|
| 545 |
}
|
| 546 |
};
|
| 547 |
|
|
|
|
| 580 |
document.getElementById('semanticThreshold').value = 50;
|
| 581 |
document.getElementById('semanticCompression').value = 0.1;
|
| 582 |
document.getElementById('semanticQueryInput').value = '';
|
| 583 |
+
document.getElementById('optimizerApiKey').value = '';
|
| 584 |
+
document.getElementById('optimizerBaseUrl').value = 'https://api.deepseek.com/v1';
|
| 585 |
+
document.getElementById('optimizerModel').value = 'deepseek-chat';
|
| 586 |
+
document.getElementById('optimizerIterations').value = 2;
|
| 587 |
+
document.getElementById('optimizerCandidates').value = 2;
|
| 588 |
+
document.getElementById('optimizerTemp').value = 0.25;
|
| 589 |
|
| 590 |
// Competitor text fields
|
| 591 |
const competitorsList = document.getElementById('competitorsList');
|
|
|
|
| 598 |
// Clear state
|
| 599 |
currentData = null;
|
| 600 |
semanticData = null;
|
| 601 |
+
optimizerData = null;
|
| 602 |
|
| 603 |
// Reset result blocks
|
| 604 |
document.getElementById('generalStats').innerHTML = '';
|
|
|
|
| 612 |
document.getElementById('semanticDocSelect').innerHTML = '<option value="target">Мой текст</option>';
|
| 613 |
document.getElementById('semanticResultsContainer').innerHTML = '<div class="text-center text-muted py-5">Нажмите "Запустить Semantic Core", чтобы построить граф и разметку.</div>';
|
| 614 |
document.getElementById('summaryResultsContainer').innerHTML = '<div class="text-center text-muted py-5">Запустите анализ, чтобы увидеть итоговые рекомендации.</div>';
|
| 615 |
+
document.getElementById('optimizerResultsContainer').innerHTML = '<div class="text-center text-muted py-5">Запустите основной анализ и затем оптимизацию.</div>';
|
| 616 |
}
|
| 617 |
|
| 618 |
function applyProjectData(project) {
|
|
|
|
| 633 |
document.getElementById('semanticThreshold').value = inp.semantic_threshold ?? 50;
|
| 634 |
document.getElementById('semanticCompression').value = inp.semantic_compression ?? 0.1;
|
| 635 |
document.getElementById('semanticQueryInput').value = inp.semantic_query || '';
|
| 636 |
+
document.getElementById('optimizerBaseUrl').value = inp.optimizer_base_url || 'https://api.deepseek.com/v1';
|
| 637 |
+
document.getElementById('optimizerModel').value = inp.optimizer_model || 'deepseek-chat';
|
| 638 |
+
document.getElementById('optimizerIterations').value = inp.optimizer_iterations ?? 2;
|
| 639 |
+
document.getElementById('optimizerCandidates').value = inp.optimizer_candidates ?? 2;
|
| 640 |
+
document.getElementById('optimizerTemp').value = inp.optimizer_temperature ?? 0.25;
|
| 641 |
|
| 642 |
// Title character counter refresh
|
| 643 |
const titleLen = (inp.target_title || '').length;
|
|
|
|
| 675 |
// Restore cached analysis results if present
|
| 676 |
currentData = project.state && project.state.analysis_result ? project.state.analysis_result : null;
|
| 677 |
semanticData = project.state && project.state.semantic_result ? project.state.semantic_result : null;
|
| 678 |
+
optimizerData = project.state && project.state.optimizer_result ? project.state.optimizer_result : null;
|
| 679 |
|
| 680 |
if (currentData) renderResults(currentData);
|
| 681 |
if (semanticData) renderSemanticResults(semanticData);
|
| 682 |
renderActionSummary(currentData, semanticData);
|
| 683 |
+
renderOptimizerResults(optimizerData);
|
| 684 |
}
|
| 685 |
|
| 686 |
document.getElementById('projectFileInput').addEventListener('change', function(e) {
|
|
|
|
| 741 |
const data = await response.json();
|
| 742 |
currentData = data;
|
| 743 |
renderResults(data);
|
| 744 |
+
optimizerData = null;
|
| 745 |
+
renderOptimizerResults(null);
|
| 746 |
|
| 747 |
} catch (error) {
|
| 748 |
alert("Ошибка: " + error.message);
|
|
|
|
| 791 |
}
|
| 792 |
}
|
| 793 |
|
| 794 |
+
function renderOptimizerResults(data) {
|
| 795 |
+
const container = document.getElementById('optimizerResultsContainer');
|
| 796 |
+
if (!container) return;
|
| 797 |
+
if (!data) {
|
| 798 |
+
container.innerHTML = '<div class="text-center text-muted py-5">Запустите основной анализ и затем оптимизацию.</div>';
|
| 799 |
+
return;
|
| 800 |
+
}
|
| 801 |
+
if (!data.ok) {
|
| 802 |
+
container.innerHTML = `<div class="alert alert-danger">Ошибка оптимизации: ${data.error || 'unknown'}</div>`;
|
| 803 |
+
return;
|
| 804 |
+
}
|
| 805 |
+
|
| 806 |
+
const base = data.baseline_metrics || {};
|
| 807 |
+
const fin = data.final_metrics || {};
|
| 808 |
+
const rows = [
|
| 809 |
+
['Composite score', base.score, fin.score],
|
| 810 |
+
['BERT низких ключей', base.bert_low_count, fin.bert_low_count],
|
| 811 |
+
['BM25 remove', base.bm25_remove_count, fin.bm25_remove_count],
|
| 812 |
+
['N-gram signals', base.ngram_signal_count, fin.ngram_signal_count],
|
| 813 |
+
['Title BERT', base.title_bert_score ?? '-', fin.title_bert_score ?? '-'],
|
| 814 |
+
['Semantic gaps', base.semantic_gap_count, fin.semantic_gap_count],
|
| 815 |
+
].map(r => `<tr><td>${r[0]}</td><td>${r[1]}</td><td>${r[2]}</td></tr>`).join('');
|
| 816 |
+
|
| 817 |
+
const iterRows = (data.iterations || []).map(it => {
|
| 818 |
+
const before = it.metrics_before ? it.metrics_before.score : '-';
|
| 819 |
+
const after = it.metrics_after ? it.metrics_after.score : '-';
|
| 820 |
+
return `<tr>
|
| 821 |
+
<td>${it.step}</td>
|
| 822 |
+
<td>${it.status}</td>
|
| 823 |
+
<td>${it.goal ? (it.goal.type + ': ' + (it.goal.label || '')) : '-'}</td>
|
| 824 |
+
<td>${before}</td>
|
| 825 |
+
<td>${after}</td>
|
| 826 |
+
<td>${it.delta_score ?? '-'}</td>
|
| 827 |
+
</tr>`;
|
| 828 |
+
}).join('');
|
| 829 |
+
|
| 830 |
+
container.innerHTML = `
|
| 831 |
+
<div class="stat-card">
|
| 832 |
+
<h6 class="card-title">Результат оптимизации</h6>
|
| 833 |
+
<div class="small mb-2">Применено правок: <strong>${data.applied_changes || 0}</strong></div>
|
| 834 |
+
<div class="table-responsive">
|
| 835 |
+
<table class="table table-sm table-bordered mb-0">
|
| 836 |
+
<thead class="table-light"><tr><th>Метрика</th><th>До</th><th>После</th></tr></thead>
|
| 837 |
+
<tbody>${rows}</tbody>
|
| 838 |
+
</table>
|
| 839 |
+
</div>
|
| 840 |
+
</div>
|
| 841 |
+
<div class="stat-card">
|
| 842 |
+
<h6 class="card-title">Лог итераций</h6>
|
| 843 |
+
<div class="table-responsive">
|
| 844 |
+
<table class="table table-sm table-hover mb-0">
|
| 845 |
+
<thead><tr><th>#</th><th>Статус</th><th>Цель</th><th>Score до</th><th>Score после</th><th>Δ</th></tr></thead>
|
| 846 |
+
<tbody>${iterRows || '<tr><td colspan="6" class="text-muted text-center">Нет данных</td></tr>'}</tbody>
|
| 847 |
+
</table>
|
| 848 |
+
</div>
|
| 849 |
+
</div>`;
|
| 850 |
+
}
|
| 851 |
+
|
| 852 |
+
function applyOptimizedText() {
|
| 853 |
+
if (!optimizerData || !optimizerData.ok || !optimizerData.optimized_text) {
|
| 854 |
+
alert('Нет результата оптимизации для применения.');
|
| 855 |
+
return;
|
| 856 |
+
}
|
| 857 |
+
document.getElementById('targetText').value = optimizerData.optimized_text;
|
| 858 |
+
alert('Оптимизированный текст подставлен в поле Target. Рекомендуется заново запустить анализ.');
|
| 859 |
+
}
|
| 860 |
+
|
| 861 |
+
async function runLlmOptimization() {
|
| 862 |
+
if (!currentData) {
|
| 863 |
+
alert('Сначала выполните основной анализ текста.');
|
| 864 |
+
return;
|
| 865 |
+
}
|
| 866 |
+
|
| 867 |
+
const apiKey = (document.getElementById('optimizerApiKey').value || '').trim();
|
| 868 |
+
if (!apiKey) {
|
| 869 |
+
alert('Введите API key для LLM.');
|
| 870 |
+
return;
|
| 871 |
+
}
|
| 872 |
+
|
| 873 |
+
const payload = {
|
| 874 |
+
target_text: document.getElementById('targetText').value || '',
|
| 875 |
+
competitors: collectCompetitorTexts(),
|
| 876 |
+
keywords: (document.getElementById('keywordsInput').value || '').split('\n').map(v => v.trim()).filter(Boolean),
|
| 877 |
+
language: document.getElementById('languageSelect').value || 'en',
|
| 878 |
+
target_title: document.getElementById('targetTitle').value || '',
|
| 879 |
+
competitor_titles: collectCompetitorTitles(),
|
| 880 |
+
api_key: apiKey,
|
| 881 |
+
api_base_url: (document.getElementById('optimizerBaseUrl').value || '').trim(),
|
| 882 |
+
model: (document.getElementById('optimizerModel').value || '').trim(),
|
| 883 |
+
max_iterations: Number(document.getElementById('optimizerIterations').value || 2),
|
| 884 |
+
candidates_per_iteration: Number(document.getElementById('optimizerCandidates').value || 2),
|
| 885 |
+
temperature: Number(document.getElementById('optimizerTemp').value || 0.25)
|
| 886 |
+
};
|
| 887 |
+
|
| 888 |
+
document.getElementById('loader').style.display = 'block';
|
| 889 |
+
try {
|
| 890 |
+
const response = await fetch('/api/v1/optimizer/run', {
|
| 891 |
+
method: 'POST',
|
| 892 |
+
headers: { 'Content-Type': 'application/json' },
|
| 893 |
+
body: JSON.stringify(payload)
|
| 894 |
+
});
|
| 895 |
+
if (!response.ok) throw new Error("Ошибка сервера: " + response.statusText);
|
| 896 |
+
optimizerData = await response.json();
|
| 897 |
+
renderOptimizerResults(optimizerData);
|
| 898 |
+
} catch (error) {
|
| 899 |
+
alert('Ошибка LLM оптимизации: ' + error.message);
|
| 900 |
+
console.error(error);
|
| 901 |
+
} finally {
|
| 902 |
+
document.getElementById('loader').style.display = 'none';
|
| 903 |
+
}
|
| 904 |
+
}
|
| 905 |
+
|
| 906 |
async function runSemanticSearch() {
|
| 907 |
const query = document.getElementById('semanticQueryInput').value;
|
| 908 |
const lang = document.getElementById('languageSelect').value;
|