FilipL009 commited on
Commit
68a729a
·
verified ·
1 Parent(s): ab3e2d0

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +362 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,364 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
1
  import streamlit as st
2
+ from transformers import pipeline, AutoTokenizer, AutoModelForTokenClassification
3
+ import torch
4
+ import pypdf
5
+ import pandas as pd
6
+ import torch._dynamo
7
+ import re
8
+
9
+ # --- VIZUALIZACE ---
10
+ from streamlit_agraph import agraph, Node, Edge, Config
11
+
12
+ # --- GLIREL IMPORT ---
13
+ from glirel import GLiREL
14
+
15
+ # Potlačení chyb pro Windows
16
+ torch._dynamo.config.suppress_errors = True
17
+
18
+ st.set_page_config(page_title="CTI Intelligence Suite", page_icon="🛡️", layout="wide")
19
+
20
+ # ==========================================
21
+ # 1. NAČÍTÁNÍ MODELŮ
22
+ # ==========================================
23
+
24
+ @st.cache_resource
25
+ def load_ner_model():
26
+ """ Načte SecureModernBERT pro entity. """
27
+ device = 0 if torch.cuda.is_available() else -1
28
+ model_name = "attack-vector/SecureModernBERT-NER"
29
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
30
+ model = AutoModelForTokenClassification.from_pretrained(model_name)
31
+ pipe = pipeline("ner", model=model, tokenizer=tokenizer, aggregation_strategy="simple", device=device)
32
+ return pipe
33
+
34
+ @st.cache_resource
35
+ def load_glirel_model():
36
+ """ Načte GLiREL pro vztahy. """
37
+ device = "cuda" if torch.cuda.is_available() else "cpu"
38
+ try:
39
+ model = GLiREL.from_pretrained("jackboyla/glirel-large-v0")
40
+ model.to(device)
41
+ model.eval()
42
+ return model
43
+ except Exception as e:
44
+ st.error(f"Nepodařilo se stáhnout model GLiREL: {e}")
45
+ return None
46
+
47
+ # ==========================================
48
+ # 2. LOGIKA ZPRACOVÁNÍ TEXTU
49
+ # ==========================================
50
+
51
+ def extract_text_from_pdf(uploaded_file):
52
+ try:
53
+ pdf_reader = pypdf.PdfReader(uploaded_file)
54
+ text = ""
55
+ for page in pdf_reader.pages:
56
+ t = page.extract_text()
57
+ if t: text += t + "\n\n"
58
+ return text
59
+ except Exception as e:
60
+ st.error(f"Error reading PDF: {e}")
61
+ return ""
62
+
63
+ def analyze_ner_batched(pipeline, text, batch_size=8):
64
+ """
65
+ Projde CELÝ text po kusech (nezkracuje ho), aby našel všechny entity.
66
+ """
67
+ chunk_size = 4000
68
+ results = []
69
+
70
+ for i in range(0, len(text), chunk_size):
71
+ chunk = text[i : i + chunk_size]
72
+ if not chunk.strip(): continue
73
+
74
+ # Analýza kusu
75
+ chunk_results = pipeline(chunk)
76
+
77
+ # Posun indexů
78
+ for entity in chunk_results:
79
+ entity['start'] += i
80
+ entity['end'] += i
81
+ results.append(entity)
82
+
83
+ return results
84
+
85
+ def merge_close_entities(results, original_text, max_char_distance=2):
86
+ if not results: return []
87
+ merged = []
88
+ current = results[0].copy()
89
+ for next_entity in results[1:]:
90
+ gap_start = current['end']
91
+ gap_end = next_entity['start']
92
+ if gap_start > gap_end: gap_start = gap_end
93
+ gap_text = original_text[gap_start:gap_end]
94
+
95
+ if (current['entity_group'] == next_entity['entity_group'] and
96
+ len(gap_text) <= max_char_distance and
97
+ "." not in gap_text and "," not in gap_text):
98
+ current['end'] = next_entity['end']
99
+ current['score'] = max(current['score'], next_entity['score'])
100
+ else:
101
+ merged.append(current)
102
+ current = next_entity.copy()
103
+ merged.append(current)
104
+ return merged
105
+
106
+ # ==========================================
107
+ # 3. FILTRACE VĚT (SMART FILTER)
108
+ # ==========================================
109
+
110
+ def filter_text_smartly(text, ner_results):
111
+ """
112
+ Vezme celý text a výsledky NERu.
113
+ Vrátí pouze ty věty, které obsahují alespoň jednu entitu.
114
+ """
115
+ sentence_spans = []
116
+ for match in re.finditer(r'[^.!?]+[.!?]', text):
117
+ sentence_spans.append((match.start(), match.end(), match.group()))
118
+
119
+ if not sentence_spans and text:
120
+ sentence_spans.append((0, len(text), text))
121
+
122
+ relevant_sentences = []
123
+
124
+ for s_start, s_end, s_text in sentence_spans:
125
+ has_entity = False
126
+ for ent in ner_results:
127
+ if ent['start'] >= s_start and ent['end'] <= s_end:
128
+ has_entity = True
129
+ break
130
+
131
+ if has_entity:
132
+ relevant_sentences.append(s_text.strip())
133
+
134
+ clean_text = " ".join(relevant_sentences)
135
+ # Pojistka: Limit pro GLiREL
136
+ return clean_text[:3000]
137
+
138
+ # ==========================================
139
+ # 4. GLIREL LOGIKA (CLEAN & ROBUST)
140
+ # ==========================================
141
+
142
+ def align_and_predict_relations(glirel_model, text, ner_results, threshold=0.4):
143
+ if not glirel_model: return []
144
+
145
+ tokens = text.split()
146
+ token_spans = []
147
+ curr = 0
148
+ for t in tokens:
149
+ start = text.find(t, curr)
150
+ if start == -1: start = curr
151
+ end = start + len(t)
152
+ token_spans.append((start, end))
153
+ curr = end
154
+
155
+ glirel_ner = []
156
+ token_to_full_entity = {}
157
+
158
+ for ent in ner_results:
159
+ c_start, c_end = ent['start'], ent['end']
160
+ full_name = text[c_start:c_end].strip()
161
+ t_start, t_end = -1, -1
162
+ for i, (ts, te) in enumerate(token_spans):
163
+ if ts >= c_start and t_start == -1: t_start = i
164
+ if te <= c_end: t_end = i
165
+
166
+ if t_start != -1 and t_end != -1:
167
+ glirel_ner.append([t_start, t_end, ent['entity_group'], full_name])
168
+ for t_idx in range(t_start, t_end + 1):
169
+ token_to_full_entity[t_idx] = full_name
170
+
171
+ if not glirel_ner: return []
172
+
173
+ labels = [
174
+ "uses", "targets", "communicates_with", "drops",
175
+ "located_at", "attributed_to", "exploits",
176
+ "compromises", "downloads", "resolves_to", "variant_of"
177
+ ]
178
+
179
+ try:
180
+ relations = glirel_model.predict_relations(
181
+ tokens, labels, threshold=threshold, ner=glirel_ner, top_k=3
182
+ )
183
+ except Exception as e:
184
+ st.error(f"GLiREL Error: {e}")
185
+ return []
186
+
187
+ # Pomocná funkce na čištění textu (odstraní [], Unknown, prázdné stringy)
188
+ def clean_entity_text(raw_val):
189
+ if raw_val is None: return None
190
+ if isinstance(raw_val, list):
191
+ if not raw_val: return None
192
+ raw_val = " ".join([str(x) for x in raw_val])
193
+ text_val = str(raw_val).strip()
194
+ if text_val in ["", "[]", "['']", "Unknown", "None"]: return None
195
+ return text_val
196
+
197
+ best_relations = {}
198
+ for rel in relations:
199
+ head_idx = rel['head_pos'][0]
200
+ tail_idx = rel['tail_pos'][0]
201
+
202
+ raw_head = token_to_full_entity.get(head_idx, rel.get('head_text'))
203
+ raw_tail = token_to_full_entity.get(tail_idx, rel.get('tail_text'))
204
+
205
+ head = clean_entity_text(raw_head)
206
+ tail = clean_entity_text(raw_tail)
207
+
208
+ if head and tail and head != tail:
209
+ current_score = rel['score']
210
+ relation_label = rel['label']
211
+ pair = sorted([head, tail])
212
+ unique_key = (pair[0], pair[1], relation_label)
213
+
214
+ if unique_key not in best_relations:
215
+ best_relations[unique_key] = {
216
+ "source": head, "target": tail, "relation": relation_label, "confidence": current_score
217
+ }
218
+ else:
219
+ if current_score > best_relations[unique_key]['confidence']:
220
+ best_relations[unique_key] = {
221
+ "source": head, "target": tail, "relation": relation_label, "confidence": current_score
222
+ }
223
+
224
+ return list(best_relations.values())
225
+
226
+ # ==========================================
227
+ # 5. UI APLIKACE
228
+ # ==========================================
229
+
230
+ with st.sidebar:
231
+ st.title("🧭 Navigation")
232
+ page = st.radio("Go to:", ["Analyzer", "Visualizations"])
233
+ st.markdown("---")
234
+
235
+ if page == "Analyzer":
236
+ st.subheader("⚙️ Settings")
237
+ confidence_threshold = st.slider(
238
+ "Relation Confidence (%)", min_value=0, max_value=100, value=59,
239
+ help="Zobrazí jen vztahy, kde si je model jistý na více než X %."
240
+ )
241
+
242
+ if page == "Analyzer":
243
+ st.title("CTI Analyzer")
244
+
245
+ with st.spinner("Loading models..."):
246
+ ner_pipe = load_ner_model()
247
+
248
+ col1, col2 = st.columns([1, 2])
249
+
250
+ with col1:
251
+ st.subheader("📂 Input")
252
+ uploaded_file = st.file_uploader("Upload PDF Report", type=["pdf"])
253
+
254
+ with col2:
255
+ # ZMĚNA ZDE: NOVÝ DEFAULT TEXT
256
+ default_text = r"""Lazarus Group, often linked to the North Korean government, has been observed targeting the financial sector and cryptocurrency exchanges in Japan. The threat actor uses AppleJeus malware to infiltrate networks. The malware was found located at C:\Windows\Temp\update.exe. Security researchers attributed this campaign to Hidden Cobra. In a recent incident, Lazarus Group also targeted Sony Pictures."""
257
+ if uploaded_file:
258
+ with st.spinner("Reading PDF..."):
259
+ txt = extract_text_from_pdf(uploaded_file)
260
+ st.info(f"Loaded {len(txt)} characters from PDF.")
261
+ st.text_area("Preview", value=txt[:500] + "...", height=150, disabled=True)
262
+ else:
263
+ txt = st.text_area("Or Paste Text Here", value=default_text, height=150)
264
+
265
+ st.divider()
266
+ if st.button("Analyze", type="primary"):
267
+ if not txt.strip():
268
+ st.warning("Please enter some text or upload a PDF.")
269
+ else:
270
+ with st.status("Running analysis...") as status:
271
+
272
+ # 1. NER - SCAN CELÉHO DOKUMENTU
273
+ status.write("1. Scanning full document for Entities...")
274
+ full_raw_ents = analyze_ner_batched(ner_pipe, txt)
275
+
276
+ # 2. FILTRACE TEXTU
277
+ status.write("2. Selecting key sentences...")
278
+ optimized_text = filter_text_smartly(txt, full_raw_ents)
279
+ if not optimized_text: optimized_text = txt[:2000]
280
+
281
+ st.info(f"Text optimized from {len(txt)} to {len(optimized_text)} chars.")
282
+
283
+ # 3. RE-ALIGNMENT
284
+ status.write("3. Re-aligning entities...")
285
+ final_raw_ents = analyze_ner_batched(ner_pipe, optimized_text)
286
+ final_ents = merge_close_entities(final_raw_ents, optimized_text)
287
+
288
+ # 4. GLIREL
289
+ status.write("4. Extracting Relations...")
290
+ glirel = load_glirel_model()
291
+ threshold_float = confidence_threshold / 100.0
292
+ rels = align_and_predict_relations(glirel, optimized_text, final_ents, threshold=threshold_float)
293
+
294
+ status.update(label="Done!", state="complete")
295
+
296
+ # Uložení výsledků
297
+ df_ents = pd.DataFrame([{
298
+ "Entity": optimized_text[e['start']:e['end']],
299
+ "Type": e['entity_group'],
300
+ "Confidence": e['score']
301
+ } for e in final_ents])
302
+
303
+ # Konverze NER dat na JSON string pro download
304
+ ner_json = df_ents.to_json(orient="records", indent=4)
305
+
306
+ # Čistění duplicit ve vztazích
307
+ df_rels = pd.DataFrame(rels)
308
+ if not df_rels.empty:
309
+ df_rels = df_rels.drop_duplicates(subset=["source", "target", "relation"])
310
+
311
+ st.session_state['data'] = df_ents
312
+ st.session_state['rels'] = df_rels
313
+
314
+ c1, c2 = st.columns(2)
315
+ with c1:
316
+ st.subheader(f"Entities ({len(df_ents)})")
317
+ st.dataframe(df_ents, use_container_width=True)
318
+
319
+ # --- TLAČÍTKO PRO DOWNLOAD JSON ---
320
+ st.download_button(
321
+ label="📥 Download NER JSON",
322
+ data=ner_json,
323
+ file_name="ner_entities.json",
324
+ mime="application/json"
325
+ )
326
+ # ----------------------------------
327
+
328
+ with c2:
329
+ st.subheader(f"Relations ({len(df_rels)})")
330
+ st.dataframe(st.session_state['rels'], use_container_width=True)
331
+
332
+ elif page == "Visualizations":
333
+ st.title("Knowledge Graph")
334
+ if 'data' in st.session_state and not st.session_state['data'].empty:
335
+ nodes, edges = [], []
336
+ added = set()
337
+
338
+ type_colors = {"MALWARE": "#ff4b4b", "ACTOR": "#ffa421", "TOOL": "#1c83e1", "IP": "#21c354"}
339
+
340
+ for _, row in st.session_state['data'].iterrows():
341
+ ent = row['Entity']
342
+ if ent not in added:
343
+ color = type_colors.get(row['Type'], "#888")
344
+ nodes.append(Node(id=ent, label=ent, size=20, color=color))
345
+ added.add(ent)
346
+
347
+ if 'rels' in st.session_state and not st.session_state['rels'].empty:
348
+ for _, row in st.session_state['rels'].iterrows():
349
+ if row['source'] not in added:
350
+ nodes.append(Node(id=row['source'], label=row['source'], size=20, color="#888"))
351
+ added.add(row['source'])
352
+ if row['target'] not in added:
353
+ nodes.append(Node(id=row['target'], label=row['target'], size=20, color="#888"))
354
+ added.add(row['target'])
355
+
356
+ edges.append(Edge(
357
+ source=row['source'], target=row['target'], label=row['relation'],
358
+ color="red", arrows="to"
359
+ ))
360
 
361
+ config = Config(width="100%", height=600, directed=True, physics=True)
362
+ agraph(nodes=nodes, edges=edges, config=config)
363
+ else:
364
+ st.warning("No data found. Please run analysis first.")