Spaces:
Running
Running
add
Browse files
app.py
CHANGED
|
@@ -207,63 +207,64 @@ async def generate_viz(file: UploadFile = File(...), query: str = Form(...)):
|
|
| 207 |
x_col = numeric_cols[0]
|
| 208 |
y_col = numeric_cols[1] if query != "histplot" and len(numeric_cols) > 1 else None
|
| 209 |
|
| 210 |
-
#
|
| 211 |
prompt = f"""
|
| 212 |
-
Génère uniquement du code Python fonctionnel pour tracer un {query} avec Matplotlib et Seaborn
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
- {f"Axe Y : '{y_col}'" if y_col else ''}
|
| 217 |
-
- Enregistre le graphique sous 'plot.png'
|
| 218 |
-
- Ne génère que du code Python valide, sans texte explicatif
|
| 219 |
-
"""
|
| 220 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
print("🟣 Prompt envoyé au modèle :")
|
| 222 |
-
|
| 223 |
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
|
| 231 |
-
|
| 232 |
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
|
| 237 |
-
|
| 238 |
-
|
| 239 |
|
| 240 |
-
|
| 241 |
-
|
| 242 |
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
|
| 258 |
-
|
| 259 |
-
|
| 260 |
|
| 261 |
-
|
| 262 |
-
|
| 263 |
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
|
| 268 |
|
| 269 |
|
|
|
|
| 207 |
x_col = numeric_cols[0]
|
| 208 |
y_col = numeric_cols[1] if query != "histplot" and len(numeric_cols) > 1 else None
|
| 209 |
|
| 210 |
+
# ➔ CONSTRUCTION du prompt avec encadrement ```python
|
| 211 |
prompt = f"""
|
| 212 |
+
### Génère uniquement du code Python fonctionnel pour tracer un {query} avec Matplotlib et Seaborn
|
| 213 |
+
```python
|
| 214 |
+
import matplotlib.pyplot as plt
|
| 215 |
+
import seaborn as sns
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
|
| 217 |
+
plt.figure(figsize=(8,6))
|
| 218 |
+
sns.{query}(data=df, x="{x_col}"{f', y="{y_col}"' if y_col else ''})
|
| 219 |
+
plt.savefig("plot.png")
|
| 220 |
+
plt.close()
|
| 221 |
+
"""
|
| 222 |
print("🟣 Prompt envoyé au modèle :")
|
| 223 |
+
print(prompt)
|
| 224 |
|
| 225 |
+
inputs = codegen_tokenizer(prompt, return_tensors="pt").to(device)
|
| 226 |
+
outputs = codegen_model.generate(
|
| 227 |
+
**inputs,
|
| 228 |
+
max_new_tokens=150,
|
| 229 |
+
pad_token_id=codegen_tokenizer.eos_token_id
|
| 230 |
+
)
|
| 231 |
|
| 232 |
+
generated_code = codegen_tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
| 233 |
|
| 234 |
+
# Nettoyage : retirer tout ce qui n'est pas du vrai code
|
| 235 |
+
generated_code = re.sub(r"^.*?```python", "", generated_code, flags=re.DOTALL)
|
| 236 |
+
generated_code = re.sub(r"```.*?$", "", generated_code, flags=re.DOTALL).strip()
|
| 237 |
|
| 238 |
+
print("🔵 Code généré propre :")
|
| 239 |
+
print(generated_code)
|
| 240 |
|
| 241 |
+
if not generated_code.strip():
|
| 242 |
+
return JSONResponse(content={"error": "Erreur : Code généré vide."}, status_code=500)
|
| 243 |
|
| 244 |
+
try:
|
| 245 |
+
compile(generated_code, "<string>", "exec")
|
| 246 |
+
except SyntaxError as e:
|
| 247 |
+
return JSONResponse(content={"error": f"Erreur de syntaxe détectée : {e}\nCode généré :\n{generated_code}"}, status_code=422)
|
| 248 |
|
| 249 |
+
exec_env = {"df": df, "plt": plt, "sns": sns, "pd": pd}
|
| 250 |
+
print("🔹🔹🔹 Code réellement exécuté :")
|
| 251 |
+
exec(generated_code, exec_env)
|
| 252 |
|
| 253 |
+
img_path = "plot.png"
|
| 254 |
+
if not os.path.exists(img_path):
|
| 255 |
+
return JSONResponse(content={"error": "Le fichier plot.png n'a pas été généré."}, status_code=500)
|
| 256 |
+
if os.path.getsize(img_path) == 0:
|
| 257 |
+
return JSONResponse(content={"error": "Le fichier plot.png est vide."}, status_code=500)
|
| 258 |
|
| 259 |
+
with open(img_path, "rb") as image_file:
|
| 260 |
+
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
|
| 261 |
|
| 262 |
+
print("🟢 Génération réussie ✅")
|
| 263 |
+
return JSONResponse(content={"image_base64": encoded_string})
|
| 264 |
|
| 265 |
+
except Exception as e:
|
| 266 |
+
print(f"🔴 Erreur serveur : {e}")
|
| 267 |
+
return JSONResponse(content={"error": f"Erreur lors de la génération du graphique : {str(e)}"}, status_code=500)
|
| 268 |
|
| 269 |
|
| 270 |
|