Repository navigation
Expand file tree
/
Copy pathutils.py
More file actions
97 lines (82 loc) · 3.27 KB
/
Copy pathutils.py
File metadata and controls
97 lines (82 loc) · 3.27 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
import subprocess
import os
import json
import re
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint, HuggingFacePipeline
def execute_command(command):
''' Execute a shell command and return the output '''
# print(command)
# result = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# if result.returncode != 0:
# raise Exception(f"Command failed with error: {result.stderr}")
# return result.stdout.decode("utf-8", errors="replace")
try:
result = subprocess.run(command, shell=True, capture_output=True, text=True, encoding="utf-8", errors="replace")
return result.stdout.strip()
except Exception as e:
return None, str(e), -1 # Return -1 as exit code for exceptions
def extract_json_from_string(input_str: str):
try:
response = json.loads(input_str.strip().replace("\n", ""))
return response
except json.JSONDecodeError:
json_match = re.search(r'{[\s\S]*}', input_str)
try:
response = json.loads(json_match.group()) if json_match else ""
except json.JSONDecodeError:
print(f"Fail to extract json from string {input_str}")
return None
return response
def pretty_print_message(message, indent=False):
pretty_message = message.pretty_repr(html=True)
if not indent:
print(pretty_message)
return
indented = "\n".join("\t" + c for c in pretty_message.split("\n"))
print(indented)
def pretty_print_messages(update, last_message=False):
is_subgraph = False
if isinstance(update, tuple):
ns, update = update
# skip parent graph updates in the printouts
if len(ns) == 0:
return
graph_id = ns[-1].split(":")[0]
print(f"Update from subgraph {graph_id}:")
print("\n")
is_subgraph = True
for node_name, node_update in update.items():
update_label = f"Update from node {node_name}:"
if is_subgraph:
update_label = "\t" + update_label
print(update_label)
print("\n")
messages = convert_to_messages(node_update["messages"])
if last_message:
messages = messages[-1:]
for m in messages:
pretty_print_message(m, indent=is_subgraph)
print("\n")
def strip_html(s: str) -> str:
return re.sub(r"<[^>]+>", "", s or "")
def compact_mitre(mitre_json_str: str, k_mitigations=2) -> str:
"""Return a short, plain-text digest of techniques + top mitigations."""
try:
data = json.loads(mitre_json_str)
except Exception:
return strip_html(mitre_json_str)
lines = []
for tid, obj in list(data.items()):
name = obj.get("Name", "")
desc = obj.get("Description", "")
# take top-2 mitigation *names*
mits = obj.get("Mitigations", []) or []
mit_names = []
for m in mits[:k_mitigations]:
if isinstance(m, dict):
mit_names.append(m.get("name") or m.get("id") or "")
elif isinstance(m, str):
mit_names.append(m)
lines.append(f"{tid} - {name}: {desc[:180]}... | Mitigations: {', '.join(mit_names)}")
return "\n".join(lines[:3])