wuhp commited on
Commit
40f1e90
·
verified ·
1 Parent(s): 34285ab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -97
app.py CHANGED
@@ -7,9 +7,9 @@ from pyvis.network import Network
7
 
8
  # --- SETTINGS ---
9
  NEWS_FILTER = [r"\bcnn\b", r"\bfox\b", r"\bbbc\b", r"\bmsnbc\b", r"\breuters\b"]
10
- THEME = "gradio/soft" # bring back the default soft theme
11
 
12
- # --- VirusTotal scan (unchanged) ---
13
  def scan_url_vt(url, api_key):
14
  headers = {"x-apikey": api_key}
15
  resp = requests.post("https://www.virustotal.com/api/v3/urls", headers=headers, data={"url": url})
@@ -17,130 +17,125 @@ def scan_url_vt(url, api_key):
17
  analysis_id = resp.json()["data"]["id"]
18
  while True:
19
  time.sleep(5)
20
- st = requests.get(f"https://www.virustotal.com/api/v3/analyses/{analysis_id}", headers=headers)
21
- attr = st.json()["data"]["attributes"]
22
- if attr.get("status")=="completed":
23
- return attr["stats"].get("malicious",0)==0
24
 
25
- # --- FFprobe metadata (unchanged) ---
26
  def extract_ffprobe_metadata(path):
27
- out = subprocess.check_output([
28
- "ffprobe","-v","error","-print_format","json","-show_format","-show_streams", path
29
  ])
30
- return json.loads(out)
31
 
32
- # --- Fetch page metadata + favicon URL ---
33
  def fetch_page_metadata(url):
34
  try:
35
- r = requests.get(url, timeout=5); r.raise_for_status()
36
- bs = BeautifulSoup(r.text,"html.parser")
37
- meta = {"url":url, "title": bs.title.string if bs.title else ""}
38
- # og: and twitter:
39
- for m in bs.find_all("meta"):
40
- p = m.get("property") or m.get("name")
41
- if p and p.startswith(("og:","twitter:")):
42
- meta[p] = m.get("content")
43
- # find favicon
44
- icon = bs.find("link", rel=lambda v:v and "icon" in v.lower())
45
- meta["favicon"] = icon["href"] if icon else ""
46
  return meta
47
  except Exception as e:
48
- return {"url":url, "error":str(e), "favicon":""}
49
 
50
- # --- Core IA search + filter ---
51
  def fetch_clean_videos(keywords, api_key, scan_enabled):
52
- # build query
53
- q = " OR ".join(kw.strip().replace(" ","+") for kw in keywords.split(","))
54
- items = list(search_items(f"mediatype:(movies) AND ({q})"))[:50]
55
- clean = []
56
- for it in items:
57
- title = it.get("title","").lower()
58
- # filter out news
59
  if any(re.search(p, title) for p in NEWS_FILTER):
60
  continue
61
- # find video files
62
- for f in get_item(it["identifier"]).files:
63
- fmt = f.get("format","").lower()
64
  if fmt.startswith(("mpeg","mp4","avi","mov","webm","m4v")):
65
- url = f"https://archive.org/download/{it['identifier']}/{f['name']}"
66
  if scan_enabled and api_key:
67
  try:
68
- ok = scan_url_vt(url, api_key)
 
69
  except:
70
  continue
71
- else:
72
- ok = True
73
- if ok:
74
- clean.append(url)
75
- return clean
76
 
77
- # --- Build a PyVis graph and return its HTML path ---
78
- def build_graph(chain):
79
- G = Network(height="300px", width="100%", directed=True)
80
- for node in chain:
81
- label = node.get("metadata",{}).get("title","origin")
82
- icon = node.get("metadata",{}).get("favicon","")
83
- G.add_node(node["url"], label="", shape="image", image=icon or None, title=label)
84
- # link them in order
 
 
 
 
85
  for i in range(len(chain)-1):
86
- G.add_edge(chain[i]["url"], chain[i+1]["url"])
87
- tmp = tempfile.NamedTemporaryFile(suffix=".html", delete=False)
88
- G.show(tmp.name)
89
- return tmp.name
 
 
90
 
91
- # --- UI ---
92
  with gr.Blocks(theme=THEME) as demo:
93
- gr.Markdown("## 📼 Raw-Footage Chain Explorer")
94
  with gr.Row():
95
- kw = gr.Textbox("Keywords (comma-sep)", value="drone strike, military uav")
96
- vt = gr.Textbox("VT API Key", type="password")
97
- scan_toggle = gr.Checkbox("Enable VT scan", True)
98
- ff_toggle = gr.Checkbox("Enable FFprobe", False)
99
- run_btn = gr.Button("Search & Scan")
100
 
101
- url_dd = gr.Dropdown("Clean Video URLs", choices=[])
102
- vid_player = gr.Video()
103
- ia_json = gr.JSON()
104
- ff_json = gr.JSON()
105
- graph_html = gr.HTML()
106
- origin_meta = gr.JSON()
107
 
108
- def search_and_populate(k, api, s):
109
- urls = fetch_clean_videos(k, api, s)
110
  return gr.update(choices=urls, value=urls[0] if urls else None)
111
 
112
- def update_all(sel, ff_on, api_key):
113
- if not sel:
114
  return None, {}, {}, "", {}
115
- # 1) IA metadata + files
116
- parts = sel.split("/"); ident = parts[4]
 
117
  item = get_item(ident)
118
- raw = {"metadata":item.metadata, "files": [
119
- {"name":f["name"], "format":f["format"], "size":f.get("size")}
120
- for f in item.files
121
- ]}
122
- # 2) FFprobe
123
- ffm = extract_ffprobe_metadata(sel) if ff_on else {}
124
- # 3) trace origins
125
- desc = raw["metadata"].get("description","")
126
- urls = re.findall(r"https?://[^\s\"']+", desc)
127
  chain = []
128
  for u in urls:
129
- m = fetch_page_metadata(u)
130
- chain.append({"url":u, "metadata":m})
131
- # finally add IA itself as last hop
132
- chain.append({"url":sel, "metadata": {"title": raw["metadata"].get("title"), "favicon": ""}})
133
- # 4) graph
134
- gfile = build_graph(chain)
135
- # 5) default show first origin metadata
136
- om = chain[0]["metadata"] if chain else {}
137
- # embed graph HTML
138
- graph_data = open(gfile,"r",encoding="utf8").read()
139
- os.unlink(gfile)
140
- return sel, raw, ffm, graph_data, om
141
 
142
- run_btn.click(search_and_populate, [kw, vt, scan_toggle], [url_dd])
143
- url_dd.change(update_all, [url_dd, ff_toggle, vt],
144
- [vid_player, ia_json, ff_json, graph_html, origin_meta])
145
 
146
- demo.launch()
 
 
7
 
8
  # --- SETTINGS ---
9
  NEWS_FILTER = [r"\bcnn\b", r"\bfox\b", r"\bbbc\b", r"\bmsnbc\b", r"\breuters\b"]
10
+ THEME = "gradio/soft" # Default Gradio soft theme
11
 
12
+ # --- VirusTotal scan ---
13
  def scan_url_vt(url, api_key):
14
  headers = {"x-apikey": api_key}
15
  resp = requests.post("https://www.virustotal.com/api/v3/urls", headers=headers, data={"url": url})
 
17
  analysis_id = resp.json()["data"]["id"]
18
  while True:
19
  time.sleep(5)
20
+ status = requests.get(f"https://www.virustotal.com/api/v3/analyses/{analysis_id}", headers=headers)
21
+ attr = status.json()["data"]["attributes"]
22
+ if attr.get("status") == "completed":
23
+ return attr["stats"].get("malicious", 0) == 0
24
 
25
+ # --- FFprobe metadata ---
26
  def extract_ffprobe_metadata(path):
27
+ output = subprocess.check_output([
28
+ "ffprobe", "-v", "error", "-print_format", "json", "-show_format", "-show_streams", path
29
  ])
30
+ return json.loads(output)
31
 
32
+ # --- Fetch page metadata + favicon ---
33
  def fetch_page_metadata(url):
34
  try:
35
+ r = requests.get(url, timeout=5)
36
+ r.raise_for_status()
37
+ soup = BeautifulSoup(r.text, "html.parser")
38
+ meta = {"url": url, "title": soup.title.string if soup.title else ""}
39
+ for tag in soup.find_all("meta"):
40
+ key = tag.get("property") or tag.get("name")
41
+ if key and (key.startswith("og:") or key.startswith("twitter:")):
42
+ meta[key] = tag.get("content")
43
+ icon = soup.find("link", rel=lambda v: v and "icon" in v.lower())
44
+ meta["favicon"] = icon.get("href") if icon else ""
 
45
  return meta
46
  except Exception as e:
47
+ return {"url": url, "error": str(e), "favicon": ""}
48
 
49
+ # --- IA search + filter ---
50
  def fetch_clean_videos(keywords, api_key, scan_enabled):
51
+ query = " OR ".join(kw.strip().replace(" ", "+") for kw in keywords.split(","))
52
+ items = list(search_items(f"mediatype:(movies) AND ({query})"))[:50]
53
+ results = []
54
+ for item_meta in items:
55
+ title = item_meta.get("title", "").lower()
 
 
56
  if any(re.search(p, title) for p in NEWS_FILTER):
57
  continue
58
+ item = get_item(item_meta['identifier'])
59
+ for f in item.files:
60
+ fmt = f.get('format', '').lower()
61
  if fmt.startswith(("mpeg","mp4","avi","mov","webm","m4v")):
62
+ url = f"https://archive.org/download/{item_meta['identifier']}/{f['name']}"
63
  if scan_enabled and api_key:
64
  try:
65
+ if not scan_url_vt(url, api_key):
66
+ continue
67
  except:
68
  continue
69
+ results.append(url)
70
+ return results
 
 
 
71
 
72
+ # --- Build graph HTML ---
73
+ def build_graph_html(chain):
74
+ net = Network(height="300px", width="100%", directed=True)
75
+ for hop in chain:
76
+ url = hop['url']
77
+ meta = hop['metadata']
78
+ title = meta.get('title', url)
79
+ favicon = meta.get('favicon', '')
80
+ if favicon:
81
+ net.add_node(url, label="", shape='image', image=favicon, title=title)
82
+ else:
83
+ net.add_node(url, label=title, title=title)
84
  for i in range(len(chain)-1):
85
+ net.add_edge(chain[i]['url'], chain[i+1]['url'])
86
+ tmpf = tempfile.NamedTemporaryFile(suffix='.html', delete=False)
87
+ net.show(tmpf.name)
88
+ html = open(tmpf.name, 'r', encoding='utf8').read()
89
+ os.unlink(tmpf.name)
90
+ return html
91
 
92
+ # --- Gradio UI ---
93
  with gr.Blocks(theme=THEME) as demo:
94
+ gr.Markdown("# 📼 IA Drone‑Strike Explorer")
95
  with gr.Row():
96
+ kw_input = gr.Textbox(label="Search keywords (comma-separated)", value="drone strike, military uav")
97
+ vt_key = gr.Textbox(label="VirusTotal API Key", type="password")
98
+ scan_toggle = gr.Checkbox(label="Enable VirusTotal scan", value=True)
99
+ ffprobe_toggle = gr.Checkbox(label="Enable FFprobe metadata", value=False)
100
+ run_btn = gr.Button(label="Search & Scan")
101
 
102
+ url_dropdown = gr.Dropdown(label="Clean Video URLs", choices=[], interactive=True)
103
+ video_player = gr.Video(label="Video Player")
104
+ ia_meta = gr.JSON(label="► Raw IA Metadata")
105
+ ff_meta = gr.JSON(label="► FFprobe Metadata")
106
+ graph_panel = gr.HTML(label="► Reupload Chain Graph")
107
+ origin_meta = gr.JSON(label="► Origin Node Metadata")
108
 
109
+ def search_and_populate(keywords, api_key, scan_on):
110
+ urls = fetch_clean_videos(keywords, api_key, scan_on)
111
  return gr.update(choices=urls, value=urls[0] if urls else None)
112
 
113
+ def on_url_select(selected_url, ff_on, api_key):
114
+ if not selected_url:
115
  return None, {}, {}, "", {}
116
+ # IA metadata + files
117
+ parts = selected_url.split('/')
118
+ ident = parts[4]
119
  item = get_item(ident)
120
+ ia_data = {'metadata': item.metadata, 'files': item.files}
121
+ # FFprobe
122
+ ff_data = extract_ffprobe_metadata(selected_url) if ff_on else {}
123
+ # origin chain
124
+ desc = item.metadata.get('description', '')
125
+ urls = re.findall(r'https?://[^\s"<]+', desc)
 
 
 
126
  chain = []
127
  for u in urls:
128
+ meta = fetch_page_metadata(u)
129
+ chain.append({'url': u, 'metadata': meta})
130
+ # append IA as last hop
131
+ chain.append({'url': selected_url, 'metadata': {'title': item.metadata.get('title','')} })
132
+ graph_html = build_graph_html(chain)
133
+ origin_node = chain[0]['metadata'] if chain else {}
134
+ return selected_url, ia_data, ff_data, graph_html, origin_node
 
 
 
 
 
135
 
136
+ run_btn.click(search_and_populate, [kw_input, vt_key, scan_toggle], [url_dropdown])
137
+ url_dropdown.change(on_url_select, [url_dropdown, ffprobe_toggle, vt_key],
138
+ [video_player, ia_meta, ff_meta, graph_panel, origin_meta])
139
 
140
+ if __name__ == "__main__":
141
+ demo.launch()