Spaces:
Sleeping
Sleeping
Update utils.py
Browse files
utils.py
CHANGED
|
@@ -1,23 +1,113 @@
|
|
| 1 |
-
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
try:
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
# Conversion sécurisée des données
|
| 10 |
-
for idx in range(max_rows):
|
| 11 |
-
row = df.iloc[idx]
|
| 12 |
-
row_text = ""
|
| 13 |
-
for col in df.columns:
|
| 14 |
-
if pd.notna(row[col]):
|
| 15 |
-
# Conversion explicite en chaîne de caractères
|
| 16 |
-
value = str(row[col]).strip()
|
| 17 |
-
row_text += f"{col}: {value}\n"
|
| 18 |
-
context += f"Eintrag {idx + 1}:\n{row_text}\n---\n"
|
| 19 |
-
|
| 20 |
-
return context.strip()
|
| 21 |
|
| 22 |
except Exception as e:
|
| 23 |
-
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 3 |
+
import torch
|
| 4 |
+
|
| 5 |
+
class CSVAnalyzer:
|
| 6 |
+
def __init__(self):
|
| 7 |
+
self.model_name = "mistralai/Mistral-7B-Instruct-v0.2"
|
| 8 |
+
try:
|
| 9 |
+
# Tokenizer initialization with specific configuration
|
| 10 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 11 |
+
self.model_name,
|
| 12 |
+
trust_remote_code=True,
|
| 13 |
+
use_fast=False
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Padding token configuration
|
| 17 |
+
if self.tokenizer.pad_token is None:
|
| 18 |
+
self.tokenizer.pad_token = self.tokenizer.eos_token
|
| 19 |
+
self.tokenizer.padding_side = "right"
|
| 20 |
+
|
| 21 |
+
# Model initialization
|
| 22 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 23 |
+
self.model_name,
|
| 24 |
+
torch_dtype=torch.float16,
|
| 25 |
+
device_map="auto",
|
| 26 |
+
trust_remote_code=True
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Ensure model knows the pad_token
|
| 30 |
+
self.model.config.pad_token_id = self.tokenizer.pad_token_id
|
| 31 |
+
|
| 32 |
+
except Exception as e:
|
| 33 |
+
print(f"Initialisierungsfehler: {str(e)}")
|
| 34 |
+
raise
|
| 35 |
+
|
| 36 |
+
def prepare_context(self, df: pd.DataFrame) -> str:
|
| 37 |
+
"""Bereitet den Kontext mit den DataFrame-Daten vor."""
|
| 38 |
+
try:
|
| 39 |
+
context = "Dateninhalt:\n\n"
|
| 40 |
+
|
| 41 |
+
# Limit rows to avoid context overflow
|
| 42 |
+
max_rows = min(len(df), 50) # Maximum 50 rows
|
| 43 |
+
|
| 44 |
+
# Conversion sécurisée des données
|
| 45 |
+
for idx in range(max_rows):
|
| 46 |
+
row = df.iloc[idx]
|
| 47 |
+
row_text = ""
|
| 48 |
+
for col in df.columns:
|
| 49 |
+
if pd.notna(row[col]):
|
| 50 |
+
# Conversion explicite en chaîne de caractères
|
| 51 |
+
value = str(row[col]).strip()
|
| 52 |
+
row_text += f"{col}: {value}\n"
|
| 53 |
+
context += f"Eintrag {idx + 1}:\n{row_text}\n---\n"
|
| 54 |
+
|
| 55 |
+
return context.strip()
|
| 56 |
+
|
| 57 |
+
except Exception as e:
|
| 58 |
+
raise Exception(f"Fehler bei der Kontextvorbereitung: {str(e)}")
|
| 59 |
+
|
| 60 |
+
def generate_response(self, context: str, query: str) -> str:
|
| 61 |
+
"""Generiert eine Antwort auf die Frage unter Verwendung des Kontexts."""
|
| 62 |
+
prompt = f"""<s>[INST] Du bist ein Assistent, der auf Datenanalyse spezialisiert ist in ein Facility Management Unternehmen.
|
| 63 |
+
Datenkontext:
|
| 64 |
+
{context}
|
| 65 |
+
Frage: {query}
|
| 66 |
+
Antworte präzise und knapp, basierend ausschließlich auf den bereitgestellten Informationen. Gib das betreffende E-Mail inklusive Datum und Absender an. Erstelle bei Bedarf Analyse-Tabellen, um die Informationen strukturiert darzustellen. [/INST]"""
|
| 67 |
+
|
| 68 |
+
try:
|
| 69 |
+
# Tokenization with explicit padding handling
|
| 70 |
+
inputs = self.tokenizer(
|
| 71 |
+
prompt,
|
| 72 |
+
return_tensors="pt",
|
| 73 |
+
padding=True,
|
| 74 |
+
truncation=True,
|
| 75 |
+
max_length=2048,
|
| 76 |
+
pad_to_multiple_of=8,
|
| 77 |
+
return_attention_mask=True
|
| 78 |
+
).to(self.model.device)
|
| 79 |
+
|
| 80 |
+
# Response generation
|
| 81 |
+
with torch.no_grad():
|
| 82 |
+
outputs = self.model.generate(
|
| 83 |
+
input_ids=inputs["input_ids"],
|
| 84 |
+
attention_mask=inputs["attention_mask"],
|
| 85 |
+
max_new_tokens=512,
|
| 86 |
+
temperature=0.7,
|
| 87 |
+
top_p=0.95,
|
| 88 |
+
repetition_penalty=1.15,
|
| 89 |
+
do_sample=True,
|
| 90 |
+
num_beams=1,
|
| 91 |
+
pad_token_id=self.tokenizer.pad_token_id,
|
| 92 |
+
eos_token_id=self.tokenizer.eos_token_id
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
# Response decoding and cleaning
|
| 96 |
+
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 97 |
+
response = response.split("[/INST]")[-1].strip()
|
| 98 |
+
|
| 99 |
+
return response
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
return f"Generierungsfehler: {str(e)}"
|
| 103 |
+
|
| 104 |
+
def analyze_csv(df: pd.DataFrame, query: str) -> str:
|
| 105 |
+
"""Hauptfunktion zur CSV-Analyse und Fragenbeantwortung."""
|
| 106 |
try:
|
| 107 |
+
analyzer = CSVAnalyzer()
|
| 108 |
+
context = analyzer.prepare_context(df)
|
| 109 |
+
response = analyzer.generate_response(context, query)
|
| 110 |
+
return response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
except Exception as e:
|
| 113 |
+
return f"Fehler bei der Analyse: {str(e)}"
|