Spaces:
Sleeping
Sleeping
Update utils.py
Browse files
utils.py
CHANGED
|
@@ -1,109 +1,23 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 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 |
-
for idx, row in df.head(max_rows).iterrows():
|
| 45 |
-
row_text = ""
|
| 46 |
-
for col in df.columns:
|
| 47 |
-
if pd.notna(row[col]):
|
| 48 |
-
row_text += f"{col}: {str(row[col]).strip()}\n"
|
| 49 |
-
context += f"Eintrag {idx + 1}:\n{row_text}\n---\n"
|
| 50 |
-
|
| 51 |
-
return context.strip()
|
| 52 |
-
|
| 53 |
-
except Exception as e:
|
| 54 |
-
raise Exception(f"Fehler bei der Kontextvorbereitung: {str(e)}")
|
| 55 |
-
|
| 56 |
-
def generate_response(self, context: str, query: str) -> str:
|
| 57 |
-
"""Generiert eine Antwort auf die Frage unter Verwendung des Kontexts."""
|
| 58 |
-
prompt = f"""<s>[INST] Du bist ein Assistent, der auf Datenanalyse spezialisiert ist in ein Facility Management Unternehmen.
|
| 59 |
-
Datenkontext:
|
| 60 |
-
{context}
|
| 61 |
-
Frage: {query}
|
| 62 |
-
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]"""
|
| 63 |
-
|
| 64 |
-
try:
|
| 65 |
-
# Tokenization with explicit padding handling
|
| 66 |
-
inputs = self.tokenizer(
|
| 67 |
-
prompt,
|
| 68 |
-
return_tensors="pt",
|
| 69 |
-
padding=True,
|
| 70 |
-
truncation=True,
|
| 71 |
-
max_length=2048,
|
| 72 |
-
pad_to_multiple_of=8,
|
| 73 |
-
return_attention_mask=True
|
| 74 |
-
).to(self.model.device)
|
| 75 |
-
|
| 76 |
-
# Response generation
|
| 77 |
-
with torch.no_grad():
|
| 78 |
-
outputs = self.model.generate(
|
| 79 |
-
input_ids=inputs["input_ids"],
|
| 80 |
-
attention_mask=inputs["attention_mask"],
|
| 81 |
-
max_new_tokens=512,
|
| 82 |
-
temperature=0.7,
|
| 83 |
-
top_p=0.95,
|
| 84 |
-
repetition_penalty=1.15,
|
| 85 |
-
do_sample=True,
|
| 86 |
-
num_beams=1,
|
| 87 |
-
pad_token_id=self.tokenizer.pad_token_id,
|
| 88 |
-
eos_token_id=self.tokenizer.eos_token_id
|
| 89 |
-
)
|
| 90 |
-
|
| 91 |
-
# Response decoding and cleaning
|
| 92 |
-
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 93 |
-
response = response.split("[/INST]")[-1].strip()
|
| 94 |
-
|
| 95 |
-
return response
|
| 96 |
-
|
| 97 |
-
except Exception as e:
|
| 98 |
-
return f"Generierungsfehler: {str(e)}"
|
| 99 |
-
|
| 100 |
-
def analyze_csv(df: pd.DataFrame, query: str) -> str:
|
| 101 |
-
"""Hauptfunktion zur CSV-Analyse und Fragenbeantwortung."""
|
| 102 |
try:
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
except Exception as e:
|
| 109 |
-
|
|
|
|
| 1 |
+
def prepare_context(self, df: pd.DataFrame) -> str:
|
| 2 |
+
"""Prépare le contexte avec les données du DataFrame en s'assurant que toutes les valeurs sont traitées comme du texte."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
try:
|
| 4 |
+
context = "Dateninhalt:\n\n"
|
| 5 |
+
|
| 6 |
+
# Limiter le nombre de lignes pour éviter un dépassement de contexte
|
| 7 |
+
max_rows = min(len(df), 50) # Maximum 50 lignes
|
| 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 |
+
raise Exception(f"Fehler bei der Kontextvorbereitung: {str(e)}")
|