File size: 8,288 Bytes
811fb95 8cb9144 968fd34 811fb95 4deef40 811fb95 968fd34 811fb95 4deef40 4ba78be a5ffa73 811fb95 4ba78be 4deef40 811fb95 4ba78be 811fb95 4ba78be 4deef40 6594b52 968fd34 a5ffa73 968fd34 a5ffa73 6594b52 968fd34 a5ffa73 4ba78be 811fb95 968fd34 4ba78be a5ffa73 4deef40 4ba78be 811fb95 4deef40 968fd34 811fb95 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
import os
import re
from pathlib import Path
import yaml
# Корень репозитория — отталкиваемся от местоположения скрипта
REPO_ROOT = Path(__file__).resolve().parent.parent
# теги по ключевым словам для автодобавления
KEYWORD_TAGS = [
"CCore", "CShell", "REPL", "Mesh", "Agent", "HMP",
"MeshConsensus", "CogSync", "GMP", "EGP",
"Ethics", "Scenarios", "JSON"
]
ROOT_DIR = Path(".")
STRUCTURED_DIR = ROOT_DIR / "structured_md"
INDEX_FILE = STRUCTURED_DIR / "index.md"
MD_EXT = ".md"
# Шаблон JSON-LD для разных типов
JSON_LD_TEMPLATES = {
"FAQ": """\n```json
{{
"@context": "https://schema.org",
"@type": "FAQPage",
"mainEntity": {main_entity}
}}
```\n""",
"HowTo": """\n```json
{{
"@context": "https://schema.org",
"@type": "HowTo",
"name": "{title}",
"description": "{description}",
"step": {steps}
}}
```\n""",
"Article": """\n```json
{{
"@context": "https://schema.org",
"@type": "Article",
"name": "{title}",
"description": "{description}"
}}
```\n"""
}
FRONT_MATTER_RE = re.compile(r"^---\n(.*?)\n---\n", re.DOTALL)
def is_md_file(path):
return path.suffix.lower() == MD_EXT and STRUCTURED_DIR not in path.parents
def extract_front_matter(content: str):
"""Возвращает (front_matter_dict, clean_content) — без YAML-шапки."""
match = FRONT_MATTER_RE.match(content)
if match:
try:
data = yaml.safe_load(match.group(1)) or {}
except Exception:
data = {}
clean = content[match.end():]
return data, clean
return {}, content
def detect_file_type(content: str, front_matter: dict | None = None) -> str:
"""Определяет тип: FAQ / HowTo / Article (по front-matter или заголовкам)."""
front_matter = front_matter or {}
if "type" in front_matter:
return front_matter["type"]
# Простые эвристики по заголовкам
if re.search(r"^#\s*FAQ\b", content, re.MULTILINE) or re.search(r"^##\s*Q&A\b", content, re.MULTILINE):
return "FAQ"
if re.search(r"^#\s*HowTo\b", content, re.MULTILINE) or re.search(r"^#\s*Как\s+сделать\b", content, re.IGNORECASE | re.MULTILINE):
return "HowTo"
return "Article"
def parse_front_matter(content):
match = FRONT_MATTER_RE.match(content)
if match:
try:
data = yaml.safe_load(match.group(1))
return data
except Exception:
pass
return {}
def determine_type(content, front_matter):
if "type" in front_matter:
return front_matter["type"]
# Простейшее определение по ключевым словам в заголовках
if re.search(r"^#.*FAQ", content, re.MULTILINE):
return "FAQ"
if re.search(r"^#.*HowTo", content, re.MULTILINE):
return "HowTo"
return "Article"
def generate_json_ld(content, front_matter, ftype, title, rel_path):
desc = front_matter.get("description", content[:100].replace("\n", " ") + "...")
url = f"structured_md/{rel_path.as_posix()}"
if ftype == "FAQ":
q_matches = re.findall(r"^##\s*(.+)$", content, re.MULTILINE)
main_entity = []
for q in q_matches:
ans_match = re.search(rf"##\s*{re.escape(q)}\s*\n(.+?)(\n##|\Z)", content, re.DOTALL)
answer_text = ans_match.group(1).strip() if ans_match else ""
main_entity.append({
"@type": "Question",
"name": q,
"acceptedAnswer": {"@type": "Answer", "text": answer_text}
})
import json
return JSON_LD_TEMPLATES["FAQ"].format(
main_entity=json.dumps(main_entity, ensure_ascii=False, indent=2)
).replace("}}", f',\n "url": "{url}"\n}}', 1)
elif ftype == "HowTo":
steps = [{"@type": "HowToStep", "name": s.strip()} for s in re.findall(r"^- (.+)$", content, re.MULTILINE)]
import json
return JSON_LD_TEMPLATES["HowTo"].format(
title=title, description=desc, steps=json.dumps(steps, ensure_ascii=False, indent=2)
).replace("}}", f',\n "url": "{url}"\n}}', 1)
else: # Article
return JSON_LD_TEMPLATES["Article"].format(
title=title, description=desc
).replace("}}", f',\n "url": "{url}"\n}}', 1)
def add_index_link(content, file_path):
# относительный путь от текущего файла до structured_md/index.md
rel_path = os.path.relpath(STRUCTURED_DIR / "index.md", file_path.parent)
link_line = f"\n\n---\n> ⚡ [AI friendly version docs (structured_md)]({rel_path})\n"
if link_line.strip() not in content:
content += link_line
return content
def extract_tags(content, existing_tags):
tags = set(existing_tags or [])
for kw in KEYWORD_TAGS:
if kw.lower() in content.lower():
tags.add(kw)
return list(tags)
def mirror_md_files():
processed = []
for path in REPO_ROOT.rglob("*.md"):
if "structured_md" in path.parts or path.name.lower() == "index.md":
continue
rel_path = path.relative_to(REPO_ROOT)
target_path = STRUCTURED_DIR / rel_path
target_path.parent.mkdir(parents=True, exist_ok=True)
with path.open("r", encoding="utf-8") as f:
content = f.read()
front_matter, clean_content = extract_front_matter(content)
ftype = detect_file_type(clean_content, front_matter)
# ищем заголовок 1-го уровня для title/description
h1_match = re.search(r"^#\s*(.+)$", clean_content, re.MULTILINE)
if h1_match:
title = h1_match.group(1).strip()
rest_content = clean_content[h1_match.end():].strip()
description = front_matter.get("description", rest_content[:200].replace("\n", " ") + "...")
else:
title = front_matter.get("title", path.stem)
description = front_matter.get("description", clean_content[:200].replace("\n", " ") + "...")
tags = extract_tags(clean_content, front_matter.get("tags", []))
# формируем YAML фронт-маттер
fm_dict = {
"title": title,
"description": description,
"type": ftype,
"tags": tags,
}
yaml_fm = "---\n" + yaml.safe_dump(fm_dict, sort_keys=False, allow_unicode=True) + "---\n\n"
# добавляем корректную ссылку на индекс
clean_content = add_index_link(clean_content, target_path)
# формируем JSON-LD
json_ld = generate_json_ld(clean_content, front_matter, ftype, title, rel_path)
# пишем новый Markdown
with target_path.open("w", encoding="utf-8") as f:
f.write(yaml_fm)
f.write(clean_content.rstrip())
f.write("\n\n")
f.write(json_ld)
processed.append(rel_path)
return processed
def generate_index(files):
index_lines = ["# ИИ-дружелюбные версии файлов\n"]
tree = {}
for f in files:
parts = list(f.parts)
d = tree
for p in parts[:-1]:
d = d.setdefault(p, {})
d[parts[-1]] = None
def render_tree(d, parent_path="", level=0):
lines = []
for name, sub in sorted(d.items()):
indent = " " * level
full_path = Path(parent_path) / name
if sub is None:
lines.append(f"{indent}- [{name}]({full_path.as_posix()})")
else:
lines.append(f"{indent}- {name}")
lines.extend(render_tree(sub, full_path, level + 1))
return lines
index_lines.extend(render_tree(tree))
INDEX_FILE.parent.mkdir(parents=True, exist_ok=True)
with open(INDEX_FILE, "w", encoding="utf-8") as f:
f.write("\n".join(index_lines))
if __name__ == "__main__":
STRUCTURED_DIR.mkdir(exist_ok=True)
md_files = mirror_md_files()
generate_index(md_files)
print(f"Обработано {len(md_files)} файлов. Индекс создан: {INDEX_FILE}")
|