import os # Oprava konfliktu OpenMP knižníc v Anaconde (Docling/PyTorch vs NumPy) os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" import time import tempfile import textwrap import webbrowser from typing import Literal import requests from bs4 import BeautifulSoup from pydantic import BaseModel, Field import google.genai as genai from google.genai import types import networkx as nx from pyvis.network import Network # --- NASTAVENIA --- API_KEY = "SEM_VLOZ_SVOJ_API_KLUC" # Nahraď svojím kľúčom z aistudio.google.com TARGET_URL = "https://sk.wikipedia.org/wiki/Umel%C3%A1_inteligencia" SKILL_FILE = os.path.join("skills", "mindmap_skill.md") OUTPUT_HTML = "mindmap.html" OUTPUT_TXT = "output.txt" MAX_TEXT_CHARS = 15000 # --- 1. GENERICKÁ ŠTRUKTÚRA DÁT --- class Node(BaseModel): id: str = Field(description="Jedinečný identifikátor pojmu bez medzier a diakritiky.") label: str = Field(description="Stručný názov pojmu zobrazený v uzle podľa pravidiel v skille.") is_central: bool = Field(description="True iba pre hlavný koreňový pojem dokumentu.") level: int = Field(description="Hierarchická úroveň uzla (0 = centrum, 1 = hlavná vetva, 2 = podpojem).") category: Literal["hlavna_tema", "koncept", "metoda", "aplikacia", "vyzva"] = Field( description="Sémantická kategória uzla definovaná v skille." ) description: str = Field(description="Jednovetové vysvetlenie pojmu na základe textu.") class Edge(BaseModel): source: str = Field(description="ID zdrojového uzla.") target: str = Field(description="ID cieľového uzla.") relation: str = Field(description="Sémantický popis vzťahu medzi uzlami.") class MindMapAnalysis(BaseModel): summary: str = Field(description="Zhrnutie textu vygenerované presne podľa pravidiel v systémovom skille.") nodes: list[Node] = Field(description="Zoznam extrahovaných uzlov v rozsahu a štruktúre určenej systémovým skillom.") edges: list[Edge] = Field(description="Zoznam orientovaných vzťahov spájajúcich uzly do jedného súvislého grafu.") # --- 2. NAČÍTANIE SKILLU A EXTRAKCIA TEXTU Z HTML --- def load_skill(skill_path: str) -> str: if not os.path.exists(skill_path): raise FileNotFoundError(f"Súbor so skillom nebol nájdený: {os.path.abspath(skill_path)}") with open(skill_path, "r", encoding="utf-8") as f: return f.read() def fetch_html(source: str) -> str: if source.startswith(("http://", "https://")): headers = {"User-Agent": "Mozilla/5.0 (compatible; MindMapBot/1.0)"} response = requests.get(source, headers=headers, timeout=15) response.raise_for_status() return response.text with open(source, "r", encoding="utf-8") as f: return f.read() def extract_text_with_docling(html_content: str) -> str: try: from docling.document_converter import DocumentConverter with tempfile.NamedTemporaryFile(mode="w", suffix=".html", delete=False, encoding="utf-8") as tmp: tmp.write(html_content) tmp_path = tmp.name try: converter = DocumentConverter() result = converter.convert(tmp_path) text = result.document.export_to_markdown() if text and len(text.strip()) > 50: return text finally: if os.path.exists(tmp_path): os.remove(tmp_path) except Exception as e: print(f"[Info] Docling zlyhal ({e}), používam záložný BeautifulSoup parser...") soup = BeautifulSoup(html_content, "html.parser") for tag in soup(["script", "style", "nav", "footer", "header"]): tag.decompose() return soup.get_text(separator="\n", strip=True) # --- 3. ANALÝZA TEXTU POMOCOU GEMINI API + EXTERNÝ SKILL --- def analyze_text_with_gemini(text: str, api_key: str, skill_instructions: str) -> MindMapAnalysis: if not api_key or api_key == "SEM_VLOZ_SVOJ_API_KLUC": raise ValueError("Vlož svoj Gemini API kľúč do premennej API_KEY na začiatku skriptu.") client = genai.Client( api_key=api_key, http_options=types.HttpOptions(timeout=45000) ) candidate_models = [ "gemini-3.5-flash", "gemini-3.8-flash", "gemini-3.1-flash-lite", "gemini-3.5-flash-lite", "gemini-3.6-flash", "gemini-3.7-flash", "gemini-3.5-flash", # Druhý pokus po krátkej pauze, ak bol prvý 503 ] for m in client.models.list(): name = m.name.replace("models/", "") if "gemini" in name and "2.5" not in name and "embedding" not in name and "image" not in name and "audio" not in name: if name not in candidate_models: candidate_models.append(name) user_prompt = ( "Spracuj nasledujúci extrahovaný text dokumentu. " "Dodrž všetky kvantitatívne, hierarchické a sémantické pravidlá definované v tvojich systémových inštrukciách (skill):\n\n" f"{text[:MAX_TEXT_CHARS]}" ) last_error = None for idx, model_name in enumerate(candidate_models, start=1): try: print(f" [{idx}/{len(candidate_models)}] Skúšam model: {model_name}...") response = client.models.generate_content( model=model_name, contents=user_prompt, config=types.GenerateContentConfig( system_instruction=skill_instructions, response_mime_type="application/json", response_schema=MindMapAnalysis, temperature=0.2, ), ) print(f" [OK] Úspešne spracované modelom: {model_name}") return MindMapAnalysis.model_validate_json(response.text) except Exception as e: err_str = str(e) print(f" [Preskakujem {model_name}]: {err_str[:95]}...") last_error = e if "503" in err_str: time.sleep(3) # Krátka 3s pauza pri špičke záťaže servera raise RuntimeError( f"Všetky Free Tier modely sú momentálne dočasne preťažené (503). Skús to o minútu znova. Detail: {last_error}") # --- 4. ULOŽENIE EXTRAHOVANÝCH DÁT DO TXT SÚBORU --- def save_analysis_to_txt(analysis: MindMapAnalysis, source_url: str, output_file: str = "output.txt"): id_to_label = {node.id: node.label for node in analysis.nodes} with open(output_file, "w", encoding="utf-8") as f: f.write("====================================================================\n") f.write("EXTRAHOVANÉ ZNALOSTNÉ DÁTA PRE MYŠLIENKOVÚ MAPU\n") f.write("====================================================================\n") f.write(f"Zdroj: {source_url}\n") f.write(f"Počet uzlov: {len(analysis.nodes)} | Počet relácií: {len(analysis.edges)}\n\n") f.write("--- ZHRNUTIE TEXTU ---\n") f.write(f"{analysis.summary}\n\n") f.write(f"--- EXTRAHOVANÉ POJMY PODĽA ÚROVNÍ ({len(analysis.nodes)}) ---\n") sorted_nodes = sorted(analysis.nodes, key=lambda n: (n.level, n.category)) for i, node in enumerate(sorted_nodes, start=1): central_tag = " [HLAVNÝ UZOL]" if node.is_central else "" f.write(f"{i}. [Úroveň {node.level} | {node.category.upper()}] {node.label}{central_tag}\n") f.write(f" Definícia: {node.description}\n") f.write("\n") f.write(f"--- SÉMANTICKÉ VZŤAHY / RELÁCIE ({len(analysis.edges)}) ---\n") for i, edge in enumerate(analysis.edges, start=1): src_label = id_to_label.get(edge.source, edge.source) tgt_label = id_to_label.get(edge.target, edge.target) f.write(f"{i}. [{src_label}] --({edge.relation})--> [{tgt_label}]\n") print(f"[OK] Extrahované dáta uložené do: {os.path.realpath(output_file)}") # --- 5. OBOJSTRANNÁ STROMOVÁ MYŠLIENKOVÁ MAPA (NETWORKX + PYVIS) --- def build_and_draw_pyvis_mindmap(analysis: MindMapAnalysis, output_file: str = "mindmap.html"): """ Vypočíta presné obojstranné stromové rozloženie (vľavo a vpravo od centra) cez NetworkX, farebne odlíši jednotlivé vetvy a vykreslí mapu bez prekrývania uzlov. """ G = nx.DiGraph() node_map = {n.id: n for n in analysis.nodes} # 1. Nájdenie koreňového (centrálneho) uzla central_node = next((n for n in analysis.nodes if n.is_central or n.level == 0), analysis.nodes[0]) central_id = central_node.id # 2. Zostavenie stromovej kostry (každému uzlu priradíme presne jedného rodiča, aby sa nič neprekrývalo) children_of: dict[str, list[str]] = {n.id: [] for n in analysis.nodes} parent_of: dict[str, str] = {} edge_relations: dict[tuple[str, str], str] = {} for e in analysis.edges: if e.source in node_map and e.target in node_map and e.source != e.target: edge_relations[(e.source, e.target)] = e.relation # Hlavné vetvy (level 1 alebo priami potomkovia centra) level1_ids = [n.id for n in analysis.nodes if n.id != central_id and n.level == 1] if not level1_ids: level1_ids = [e.target for e in analysis.edges if e.source == central_id and e.target != central_id] for l1_id in level1_ids: parent_of[l1_id] = central_id children_of[central_id].append(l1_id) # Priradenie poduzlov (level 2+) k ich nadradenej vetve for n in analysis.nodes: if n.id == central_id or n.id in parent_of: continue # Hľadáme prichádzajúcu hranu od uzla s nižším levelom (najlepšie level 1) candidates = [ e.source for e in analysis.edges if e.target == n.id and e.source in node_map and e.source != n.id ] # Preferujeme rodiča na úrovni 1 chosen_parent = next((c for c in candidates if c in level1_ids), None) if not chosen_parent and candidates: chosen_parent = candidates[0] if not chosen_parent: # Poistka proti ostrovom: pripojíme pod najmenej zaťaženú hlavnú vetvu alebo priamo pod centrum chosen_parent = min(level1_ids, key=lambda x: len(children_of[x])) if level1_ids else central_id parent_of[n.id] = chosen_parent children_of[chosen_parent].append(n.id) # 3. Výpočet presných súradníc (x, y) — polovica vetiev vpravo, polovica vľavo mid = (len(level1_ids) + 1) // 2 right_branches = level1_ids[:mid] left_branches = level1_ids[mid:] positions: dict[str, tuple[float, float]] = {central_id: (0.0, 0.0)} branch_color_map: dict[str, str] = {} # Farebná paleta pre jednotlivé hlavné vetvy (ako na vzorovom obrázku) branch_palette = [ "#E056FD", # Fialovo-ružová "#3498DB", # Modrá "#2ECC71", # Zelená "#E67E22", # Oranžová "#E74C3C", # Červená "#1ABC9C", # Tyrkysová "#9B59B6", # Fialová "#F39C12", # Zlatá ] def layout_side(branches: list[str], direction: int): """Rozloží vetvy na pravú (direction=+1) alebo ľavú (direction=-1) stranu bez kolízií.""" y_step = 75.0 # Vertikálny rozostup medzi listovými uzlami branch_gap = 45.0 # Extra medzera medzi hlavnými vetvami x_l1 = 340.0 * direction x_l2 = 660.0 * direction x_l3 = 940.0 * direction # Vypočítame výšku každého podstromu podľa počtu jeho listov def subtree_height(uid: str) -> float: kids = children_of.get(uid, []) if not kids: return y_step return sum(subtree_height(k) for k in kids) total_height = sum(subtree_height(b) for b in branches) + max(0, len(branches) - 1) * branch_gap current_y = -total_height / 2.0 for idx, b_id in enumerate(branches): b_height = subtree_height(b_id) b_center_y = current_y + b_height / 2.0 positions[b_id] = (x_l1, b_center_y) # Priradíme farbu vetve aj všetkým jej potomkom color_idx = (idx if direction == 1 else idx + len(right_branches)) % len(branch_palette) b_color = branch_palette[color_idx] branch_color_map[b_id] = b_color # Rozloženie detí úrovne 2 pod touto vetvou child_y = current_y for c_id in children_of.get(b_id, []): c_height = subtree_height(c_id) c_center_y = child_y + c_height / 2.0 positions[c_id] = (x_l2, c_center_y) branch_color_map[c_id] = b_color # Prípadná úroveň 3 gc_y = child_y for gc_id in children_of.get(c_id, []): gc_height = subtree_height(gc_id) positions[gc_id] = (x_l3, gc_y + gc_height / 2.0) branch_color_map[gc_id] = b_color gc_y += gc_height child_y += c_height current_y += b_height + branch_gap layout_side(right_branches, direction=1) layout_side(left_branches, direction=-1) # 4. Pridanie uzlov do NetworkX s fixnými súradnicami a čistým vzhľadom for node in analysis.nodes: nid = node.id x, y = positions.get(nid, (0.0, 0.0)) b_color = branch_color_map.get(nid, "#34495E") wrapped_desc = textwrap.fill(node.description, width=45) tooltip_text = ( f"{node.label}\n" f"Úroveň: {node.level} | Kategória: {node.category}\n" f"----------------------------------------\n" f"{wrapped_desc}" ) if nid == central_id: # Tmavý centrálny oválny/zaoblený box G.add_node( nid, label=f" {node.label} ", title=tooltip_text, x=x, y=y, fixed=True, shape="box", color={"background": "#3B3E54", "border": "#2C2E3E"}, borderWidth=2, shapeProperties={"borderRadius": 16}, margin=14, font={"size": 18, "face": "Segoe UI, Arial", "color": "#FFFFFF", "bold": True} ) elif nid in level1_ids: # Hlavné vetvy: biely box s farebným orámovaním vetvy G.add_node( nid, label=f" {node.label} ", title=tooltip_text, x=x, y=y, fixed=True, shape="box", color={"background": "#FFFFFF", "border": b_color}, borderWidth=2.5, shapeProperties={"borderRadius": 12}, margin=10, font={"size": 14, "face": "Segoe UI, Arial", "color": "#1E272E", "bold": True} ) else: # Poduzly (úroveň 2+): čistý textový štítok na farebnej línii (bez rušivého veľkého obdĺžnika) G.add_node( nid, label=node.label, title=tooltip_text, x=x, y=y, fixed=True, shape="text", font={"size": 13, "face": "Segoe UI, Arial", "color": "#2F3640", "bold": False} ) # 5. Pridanie stromových hrán (plynulé farebné krivky) for child_id, par_id in parent_of.items(): rel_text = edge_relations.get((par_id, child_id), "zahŕňa") b_color = branch_color_map.get(child_id, "#7F8C8D") is_main_branch = (par_id == central_id) G.add_edge( par_id, child_id, title=f"Vzťah: {rel_text}", color={"color": b_color, "highlight": "#111111"}, width=3.0 if is_main_branch else 1.8, arrows={"to": {"enabled": False}}, # Čisté organické vetvy ako v myšlienkovej mape smooth={"enabled": True, "type": "cubicBezier", "forceDirection": "horizontal", "roundness": 0.55} ) # Voliteľné priečne sémantické väzby (jemná prerušovaná čiara, aby nerušili strom) tree_edges = set((p, c) for c, p in parent_of.items()) for (src, tgt), rel_text in edge_relations.items(): if (src, tgt) not in tree_edges and (tgt, src) not in tree_edges and src != central_id and tgt != central_id: G.add_edge( src, tgt, title=f"Priečny vzťah: {rel_text}", color={"color": "#BDC3C7", "highlight": "#E74C3C"}, width=1.0, dashes=True, arrows={"to": {"enabled": True, "scaleFactor": 0.6}}, smooth={"enabled": True, "type": "curvedCW", "roundness": 0.25} ) # 6. Generovanie PyVis HTML s vypnutou náhodnou fyzikou net = Network(height="920px", width="100%", bgcolor="#FFFFFF", font_color="#1A252F", directed=True) net.from_nx(G) net.toggle_physics(False) # Uzly držia presne vypočítané obojstranné pozície bez prekrývania net.save_graph(output_file) full_path = os.path.realpath(output_file) print(f"[OK] Obojstranná myšlienková mapa bola uložená do: {full_path}") webbrowser.open("file://" + full_path) # --- HLAVNÝ BEH PROGRAMU --- if __name__ == "__main__": print(f"0. Načítavam AI skill zo súboru: {SKILL_FILE}") skill_text = load_skill(SKILL_FILE) print(f"1. Sťahujem HTML z: {TARGET_URL}") html_data = fetch_html(TARGET_URL) print("2. Extrahujem text pomocou Docling...") clean_text = extract_text_with_docling(html_data) print(f" Extrahovaných znakov: {len(clean_text)}") print("3. Odosielam text do Gemini API so skill inštrukciami...") mindmap_data = analyze_text_with_gemini(clean_text, api_key=API_KEY, skill_instructions=skill_text) print("\n--- ZHRNUTIE TEXTU ---") print(mindmap_data.summary) print(f"\n4. Ukladám extrahované pojmy a relácie do {OUTPUT_TXT}...") save_analysis_to_txt(mindmap_data, source_url=TARGET_URL, output_file=OUTPUT_TXT) print(f"\n5. Generujem obojstrannú myšlienkovú mapu ({len(mindmap_data.nodes)} pojmov, {len(mindmap_data.edges)} vzťahov)...") build_and_draw_pyvis_mindmap(mindmap_data, output_file=OUTPUT_HTML)