Update utils.py
Browse files
utils.py
CHANGED
@@ -21,46 +21,48 @@ class CSVAnalyzer:
|
|
21 |
)
|
22 |
|
23 |
except Exception as e:
|
24 |
-
print(f"
|
25 |
raise
|
26 |
|
27 |
def prepare_context(self, df: pd.DataFrame) -> str:
|
28 |
-
"""
|
29 |
try:
|
30 |
-
context = "
|
31 |
|
32 |
-
#
|
33 |
max_rows = min(len(df), 50)
|
34 |
|
35 |
-
|
|
|
|
|
36 |
row_text = ""
|
37 |
for col in df.columns:
|
38 |
if pd.notna(row[col]):
|
39 |
row_text += f"{col}: {str(row[col]).strip()}\n"
|
40 |
-
context += f"
|
41 |
|
42 |
return context.strip()
|
43 |
|
44 |
except Exception as e:
|
45 |
-
raise Exception(f"
|
46 |
|
47 |
def generate_response(self, context: str, query: str) -> str:
|
48 |
-
"""
|
49 |
-
# Format
|
50 |
-
prompt = f"""<|system|>
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
|
55 |
-
<|user|>
|
56 |
{context}
|
57 |
|
58 |
-
|
59 |
|
60 |
<|assistant|>"""
|
61 |
|
62 |
try:
|
63 |
-
#
|
64 |
inputs = self.tokenizer(
|
65 |
prompt,
|
66 |
return_tensors="pt",
|
@@ -70,7 +72,7 @@ Question: {query}
|
|
70 |
return_attention_mask=True
|
71 |
).to(self.model.device)
|
72 |
|
73 |
-
#
|
74 |
with torch.no_grad():
|
75 |
outputs = self.model.generate(
|
76 |
input_ids=inputs["input_ids"],
|
@@ -84,17 +86,17 @@ Question: {query}
|
|
84 |
eos_token_id=self.tokenizer.eos_token_id
|
85 |
)
|
86 |
|
87 |
-
#
|
88 |
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
89 |
response = response.split("<|assistant|>")[-1].strip()
|
90 |
|
91 |
return response
|
92 |
|
93 |
except Exception as e:
|
94 |
-
return f"
|
95 |
|
96 |
def analyze_csv(df: pd.DataFrame, query: str) -> str:
|
97 |
-
"""
|
98 |
try:
|
99 |
analyzer = CSVAnalyzer()
|
100 |
context = analyzer.prepare_context(df)
|
@@ -102,4 +104,4 @@ def analyze_csv(df: pd.DataFrame, query: str) -> str:
|
|
102 |
return response
|
103 |
|
104 |
except Exception as e:
|
105 |
-
return f"
|
|
|
21 |
)
|
22 |
|
23 |
except Exception as e:
|
24 |
+
print(f"Initialisierungsfehler: {str(e)}")
|
25 |
raise
|
26 |
|
27 |
def prepare_context(self, df: pd.DataFrame) -> str:
|
28 |
+
"""Bereitet den Kontext mit DataFrame-Daten vor."""
|
29 |
try:
|
30 |
+
context = "Dateninhalt:\n\n"
|
31 |
|
32 |
+
# Zeilen begrenzen, um Kontextüberlauf zu vermeiden
|
33 |
max_rows = min(len(df), 50)
|
34 |
|
35 |
+
# Sichere Konvertierung der Indexwerte zu Strings
|
36 |
+
for i in range(max_rows):
|
37 |
+
row = df.iloc[i]
|
38 |
row_text = ""
|
39 |
for col in df.columns:
|
40 |
if pd.notna(row[col]):
|
41 |
row_text += f"{col}: {str(row[col]).strip()}\n"
|
42 |
+
context += f"Eintrag {str(i + 1)}:\n{row_text}\n---\n"
|
43 |
|
44 |
return context.strip()
|
45 |
|
46 |
except Exception as e:
|
47 |
+
raise Exception(f"Fehler bei der Kontextvorbereitung: {str(e)}")
|
48 |
|
49 |
def generate_response(self, context: str, query: str) -> str:
|
50 |
+
"""Generiert eine Antwort auf die Frage unter Verwendung des Kontexts."""
|
51 |
+
# Spezifisches Format für TinyLlama Chat
|
52 |
+
prompt = f"""<|system|>Du bist ein Assistent, der auf Datenanalyse in einem Facility Management Unternehmen spezialisiert ist.
|
53 |
+
Antworte präzise und knapp, basierend ausschließlich auf den bereitgestellten Informationen.
|
54 |
+
Gib das betreffende E-Mail inklusive Datum und Absender an.
|
55 |
+
Erstelle bei Bedarf Analyse-Tabellen, um die Informationen strukturiert darzustellen.
|
56 |
|
57 |
+
<|user|>Kontext:
|
58 |
{context}
|
59 |
|
60 |
+
Frage: {query}
|
61 |
|
62 |
<|assistant|>"""
|
63 |
|
64 |
try:
|
65 |
+
# Tokenisierung
|
66 |
inputs = self.tokenizer(
|
67 |
prompt,
|
68 |
return_tensors="pt",
|
|
|
72 |
return_attention_mask=True
|
73 |
).to(self.model.device)
|
74 |
|
75 |
+
# Antwortgenerierung
|
76 |
with torch.no_grad():
|
77 |
outputs = self.model.generate(
|
78 |
input_ids=inputs["input_ids"],
|
|
|
86 |
eos_token_id=self.tokenizer.eos_token_id
|
87 |
)
|
88 |
|
89 |
+
# Antwort dekodieren und bereinigen
|
90 |
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
91 |
response = response.split("<|assistant|>")[-1].strip()
|
92 |
|
93 |
return response
|
94 |
|
95 |
except Exception as e:
|
96 |
+
return f"Generierungsfehler: {str(e)}"
|
97 |
|
98 |
def analyze_csv(df: pd.DataFrame, query: str) -> str:
|
99 |
+
"""Hauptfunktion für CSV-Analyse und Fragenbeantwortung."""
|
100 |
try:
|
101 |
analyzer = CSVAnalyzer()
|
102 |
context = analyzer.prepare_context(df)
|
|
|
104 |
return response
|
105 |
|
106 |
except Exception as e:
|
107 |
+
return f"Analysefehler: {str(e)}"
|