- stage1: OCR 591 страниц DjVu через Tesseract (rus+lat) - stage2: сегментация на 158 статей о растениях - stage3: LLM-извлечение структурированных данных (GLM-4.5-air) - stage4: граф знаний (NetworkX), community detection, co-occurrence - stage4b: извлечение связей болезнь→растение из Главы IV - enrich_families: обогащение таксономией (род→семейство) - visualize: 4 интерактивных HTML-графа (pyvis) - output: отчёт, анализ, визуализации Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
262 lines
8.1 KiB
Python
262 lines
8.1 KiB
Python
"""Visualize the plant knowledge graph as an interactive HTML file.
|
|
|
|
Creates two visualizations:
|
|
1. Full graph (all nodes) - may be dense
|
|
2. Filtered graph (top connections only) - more readable
|
|
"""
|
|
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import networkx as nx
|
|
from pyvis.network import Network
|
|
|
|
from config import EXTRACTED_DIR, OUTPUT_DIR
|
|
|
|
# Colors by node type
|
|
COLORS = {
|
|
"plant": "#4CAF50", # green
|
|
"chemical": "#FF9800", # orange
|
|
"property": "#2196F3", # blue
|
|
"disease": "#F44336", # red
|
|
"habitat": "#795548", # brown
|
|
"family": "#9C27B0", # purple
|
|
"disease_ch4": "#E91E63", # pink (from Chapter IV)
|
|
}
|
|
|
|
NODE_TYPE_LABELS = {
|
|
"plant": "Растение",
|
|
"chemical": "Химикат",
|
|
"property": "Свойство",
|
|
"disease": "Болезнь",
|
|
"habitat": "Место",
|
|
"family": "Семейство",
|
|
"disease_ch4": "Болезнь (Гл.IV)",
|
|
}
|
|
|
|
|
|
def build_full_graph() -> nx.Graph:
|
|
"""Build graph from all extracted data including Chapter IV."""
|
|
plants = json.loads((EXTRACTED_DIR / "all_plants.json").read_text())
|
|
G = nx.Graph()
|
|
|
|
for p in plants:
|
|
pid = p.get("name_latin") or p["name_ru"]
|
|
G.add_node(pid, type="plant", label=p["name_ru"],
|
|
family=p.get("family_ru", ""))
|
|
|
|
# Family
|
|
family = p.get("family_ru")
|
|
if family:
|
|
G.add_node(family, type="family")
|
|
G.add_edge(pid, family, rel="BELONGS_TO")
|
|
|
|
# Chemicals
|
|
for chem in p.get("chemicals", []):
|
|
c = chem.lower().strip()
|
|
if c:
|
|
G.add_node(c, type="chemical")
|
|
G.add_edge(pid, c, rel="CONTAINS")
|
|
|
|
# Properties
|
|
for prop in p.get("medicinal_properties", []):
|
|
pr = prop.lower().strip()
|
|
if pr:
|
|
G.add_node(pr, type="property")
|
|
G.add_edge(pid, pr, rel="HAS_PROPERTY")
|
|
|
|
# Diseases (from Chapter III articles)
|
|
for dis in p.get("diseases", []):
|
|
d = dis.lower().strip()
|
|
if d:
|
|
G.add_node(d, type="disease")
|
|
G.add_edge(pid, d, rel="TREATS")
|
|
|
|
# Habitat
|
|
for hab in p.get("habitat", []):
|
|
h = hab.lower().strip()
|
|
if h:
|
|
G.add_node(h, type="habitat")
|
|
G.add_edge(pid, h, rel="GROWS_IN")
|
|
|
|
# Add Chapter IV disease→plant links
|
|
ch4_file = EXTRACTED_DIR / "chapter4_disease_plants.json"
|
|
if ch4_file.exists():
|
|
ch4_data = json.loads(ch4_file.read_text())
|
|
for entry in ch4_data:
|
|
disease = entry["disease"].lower().strip()
|
|
G.add_node(disease, type="disease_ch4")
|
|
for plant_latin in entry["plants"]:
|
|
if plant_latin in G:
|
|
G.add_edge(plant_latin, disease, rel="TREATS_CH4")
|
|
|
|
return G
|
|
|
|
|
|
def create_visualization(G: nx.Graph, filename: str, min_degree: int = 0,
|
|
max_nodes: int = 0, title: str = ""):
|
|
"""Create interactive HTML visualization."""
|
|
# Filter nodes by minimum degree
|
|
if min_degree > 0:
|
|
nodes_to_keep = {n for n in G.nodes if G.degree(n) >= min_degree}
|
|
G = G.subgraph(nodes_to_keep).copy()
|
|
|
|
# Limit to top N nodes by degree if specified
|
|
if max_nodes > 0 and len(G.nodes) > max_nodes:
|
|
top_nodes = sorted(G.nodes, key=lambda n: G.degree(n), reverse=True)[:max_nodes]
|
|
G = G.subgraph(top_nodes).copy()
|
|
|
|
net = Network(
|
|
height="900px",
|
|
width="100%",
|
|
bgcolor="#1a1a2e",
|
|
font_color="white",
|
|
directed=False,
|
|
notebook=False,
|
|
)
|
|
|
|
# Physics settings for better layout
|
|
net.set_options("""
|
|
{
|
|
"physics": {
|
|
"forceAtlas2Based": {
|
|
"gravitationalConstant": -100,
|
|
"centralGravity": 0.01,
|
|
"springLength": 150,
|
|
"springConstant": 0.02,
|
|
"damping": 0.4
|
|
},
|
|
"solver": "forceAtlas2Based",
|
|
"stabilization": {
|
|
"iterations": 200
|
|
}
|
|
},
|
|
"nodes": {
|
|
"font": {
|
|
"size": 12,
|
|
"face": "Arial"
|
|
}
|
|
},
|
|
"edges": {
|
|
"color": {
|
|
"opacity": 0.3
|
|
},
|
|
"smooth": false
|
|
},
|
|
"interaction": {
|
|
"hover": true,
|
|
"tooltipDelay": 100,
|
|
"zoomView": true,
|
|
"dragView": true
|
|
}
|
|
}
|
|
""")
|
|
|
|
# Add nodes
|
|
for node, data in G.nodes(data=True):
|
|
node_type = data.get("type", "unknown")
|
|
color = COLORS.get(node_type, "#888888")
|
|
degree = G.degree(node)
|
|
|
|
# Size based on degree (log scale)
|
|
size = max(5, min(40, 5 + degree * 2))
|
|
|
|
# Label
|
|
label = data.get("label", node)
|
|
if len(label) > 30:
|
|
label = label[:27] + "..."
|
|
|
|
# Tooltip
|
|
type_label = NODE_TYPE_LABELS.get(node_type, node_type)
|
|
tooltip = f"{label}\n{type_label}\nСвязей: {degree}"
|
|
if node_type == "plant":
|
|
tooltip += f"\nСемейство: {data.get('family', '?')}"
|
|
|
|
net.add_node(
|
|
node,
|
|
label=label,
|
|
color=color,
|
|
size=size,
|
|
title=tooltip,
|
|
borderWidth=1,
|
|
borderWidthSelected=3,
|
|
)
|
|
|
|
# Add edges
|
|
for u, v, data in G.edges(data=True):
|
|
net.add_edge(u, v, title=data.get("rel", ""))
|
|
|
|
# Save
|
|
output_path = OUTPUT_DIR / filename
|
|
net.save_graph(str(output_path))
|
|
print(f"Saved: {output_path} ({len(G.nodes)} nodes, {len(G.edges)} edges)")
|
|
|
|
|
|
def create_family_graph(G: nx.Graph, filename: str):
|
|
"""Create a focused graph showing only plants and families."""
|
|
family_nodes = {n for n, d in G.nodes(data=True) if d.get("type") == "family"}
|
|
plant_nodes = {n for n, d in G.nodes(data=True) if d.get("type") == "plant"}
|
|
relevant = family_nodes | plant_nodes
|
|
subG = G.subgraph(relevant).copy()
|
|
create_visualization(subG, filename, title="Растения по семействам")
|
|
|
|
|
|
def create_disease_graph(G: nx.Graph, filename: str):
|
|
"""Create a focused graph: plants + diseases (high degree only)."""
|
|
# Get diseases with 5+ connections
|
|
disease_nodes = {n for n, d in G.nodes(data=True)
|
|
if d.get("type") in ("disease", "disease_ch4") and G.degree(n) >= 5}
|
|
# Get plants connected to those diseases
|
|
plant_nodes = set()
|
|
for d in disease_nodes:
|
|
for neighbor in G.neighbors(d):
|
|
if G.nodes[neighbor].get("type") == "plant":
|
|
plant_nodes.add(neighbor)
|
|
|
|
subG = G.subgraph(disease_nodes | plant_nodes).copy()
|
|
create_visualization(subG, filename, title="Растения и болезни")
|
|
|
|
|
|
def create_chemical_graph(G: nx.Graph, filename: str):
|
|
"""Create a focused graph: plants + chemicals."""
|
|
chem_nodes = {n for n, d in G.nodes(data=True)
|
|
if d.get("type") == "chemical" and G.degree(n) >= 3}
|
|
plant_nodes = set()
|
|
for c in chem_nodes:
|
|
for neighbor in G.neighbors(c):
|
|
if G.nodes[neighbor].get("type") == "plant":
|
|
plant_nodes.add(neighbor)
|
|
|
|
subG = G.subgraph(chem_nodes | plant_nodes).copy()
|
|
create_visualization(subG, filename, title="Растения и химический состав")
|
|
|
|
|
|
def main():
|
|
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
G = build_full_graph()
|
|
print(f"Full graph: {len(G.nodes)} nodes, {len(G.edges)} edges")
|
|
|
|
# 1. Overview graph (top nodes only, readable)
|
|
print("\n1. Overview graph (top connections)...")
|
|
create_visualization(G, "graph_overview.html", min_degree=5)
|
|
|
|
# 2. Disease-focused graph
|
|
print("2. Disease graph...")
|
|
create_disease_graph(G, "graph_diseases.html")
|
|
|
|
# 3. Chemical graph
|
|
print("3. Chemical graph...")
|
|
create_chemical_graph(G, "graph_chemicals.html")
|
|
|
|
# 4. Family graph
|
|
print("4. Family graph...")
|
|
create_family_graph(G, "graph_families.html")
|
|
|
|
print(f"\nAll visualizations saved to {OUTPUT_DIR}/")
|
|
print("Open any .html file in a browser to explore interactively.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|