Repository navigation
Expand file tree
/
Copy pathphase3_kg.py
More file actions
109 lines (87 loc) · 3.07 KB
/
Copy pathphase3_kg.py
File metadata and controls
109 lines (87 loc) · 3.07 KB
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
import os
import json
import networkx as nx
import re
# =========================================================
# CONFIG
# =========================================================
META_DIR = os.path.join("processed_data", "metadata")
OUT_GRAPH = os.path.join("processed_data", "knowledge_graph.gml")
CLIP_DURATION = 10 # seconds
# =========================================================
# NORMALIZATION
# =========================================================
def normalize_entity(name: str) -> str:
"""
Normalize entity strings so the graph is stable.
Minimal on purpose (reviewer-safe).
"""
name = name.lower().strip()
name = re.sub(r"\s+", " ", name)
return name
def event_node_id(clip_name: str) -> str:
return f"EVENT::{clip_name}"
def entity_node_id(entity_name: str) -> str:
return f"ENTITY::{entity_name}"
# =========================================================
# MAIN
# =========================================================
def build_knowledge_graph():
G = nx.DiGraph()
vlm_files = sorted(
f for f in os.listdir(META_DIR)
if f.endswith("_vlm.json")
)
previous_event = None
for idx, fname in enumerate(vlm_files):
clip_name = fname.replace("_vlm.json", "")
meta_path = os.path.join(META_DIR, fname)
with open(meta_path, "r", encoding="utf-8") as f:
data = json.load(f)
# ---------------- EVENT NODE ----------------
start_time = idx * CLIP_DURATION
end_time = start_time + CLIP_DURATION
event_id = event_node_id(clip_name)
G.add_node(
event_id,
type="event",
clip=clip_name,
start_time=start_time,
end_time=end_time,
temporal_phases=data.get("temporal_phases", {}),
actions=data.get("actions", [])
)
# ---------------- TEMPORAL EDGE ----------------
if previous_event is not None:
G.add_edge(
previous_event,
event_id,
relation="HAPPENS_BEFORE"
)
previous_event = event_id
# ---------------- ENTITY PROMOTION ----------------
raw_entities = data.get("entities", [])
for raw_ent in raw_entities:
ent = normalize_entity(raw_ent)
if not ent:
continue
ent_id = entity_node_id(ent)
if not G.has_node(ent_id):
G.add_node(
ent_id,
type="entity",
name=ent
)
G.add_edge(
event_id,
ent_id,
relation="HAS_ENTITY"
)
return G
# =========================================================
# ENTRY
# =========================================================
if __name__ == "__main__":
graph = build_knowledge_graph()
nx.write_gml(graph, OUT_GRAPH)
print(f"[OK] Knowledge graph rebuilt → {OUT_GRAPH}")