FatimaGr commited on
Commit
9ce7f8d
·
verified ·
1 Parent(s): 9b9ff7e
Files changed (1) hide show
  1. app.py +27 -20
app.py CHANGED
@@ -192,15 +192,12 @@ VALID_PLOTS = {"histplot", "scatterplot", "barplot", "lineplot", "boxplot"}
192
  print("hello")
193
  @app.post("/generate_viz/")
194
  async def generate_viz(file: UploadFile = File(...), query: str = Form(...)):
195
- print("hello")
196
  try:
197
- contents = await file.read()
198
- excel_file = io.BytesIO(contents)
199
- df = pd.read_excel(excel_file)
200
-
201
  if query not in VALID_PLOTS:
202
  return JSONResponse(content={"error": f"Type de graphique invalide. Choisissez parmi : {', '.join(VALID_PLOTS)}"}, status_code=400)
203
 
 
204
  numeric_cols = df.select_dtypes(include=["number"]).columns
205
 
206
  if len(numeric_cols) < 1:
@@ -210,7 +207,7 @@ async def generate_viz(file: UploadFile = File(...), query: str = Form(...)):
210
  y_col = numeric_cols[1] if query != "histplot" and len(numeric_cols) > 1 else None
211
  prompt_y = f', y="{y_col}"' if y_col else ""
212
 
213
- # Prompt d'entrée pour le modèle
214
  prompt = f"""
215
  ### Génère uniquement du code Python fonctionnel pour tracer un {query} avec Matplotlib et Seaborn ###
216
  # Contraintes :
@@ -226,32 +223,39 @@ plt.savefig("plot.png")
226
  plt.close()
227
  """
228
 
 
 
 
229
  inputs = codegen_tokenizer(prompt, return_tensors="pt").to(device)
230
- outputs = codegen_model.generate(**inputs, max_new_tokens=120, pad_token_id=codegen_tokenizer.eos_token_id)
231
- generated_code = codegen_tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
 
 
 
232
 
233
- # 🔥 Nettoyage : couper si répétition du prompt
234
- if "### Génère uniquement du code Python fonctionnel" in generated_code[1:]:
235
- generated_code = generated_code.split("### Génère uniquement du code Python fonctionnel")[0]
236
 
237
- # 🔥 Nettoyage : éviter doublon imports
238
- generated_code = re.sub(r"(import matplotlib.pyplot as plt\nimport seaborn as sns\n)+", "import matplotlib.pyplot as plt\nimport seaborn as sns\n", generated_code)
239
 
 
 
240
  if generated_code.strip().endswith("sns."):
241
  generated_code = generated_code.rsplit("\n", 1)[0]
242
 
243
- print("🔹 Code généré propre :\n", generated_code)
 
 
 
 
244
 
245
  try:
246
  compile(generated_code, "<string>", "exec")
247
  except SyntaxError as e:
248
  return JSONResponse(content={"error": f"Erreur de syntaxe détectée : {e}\nCode généré :\n{generated_code}"}, status_code=422)
249
 
250
- exec_env = {
251
- "__builtins__": __builtins__,
252
- "df": df,
253
- }
254
- print("🔹🔹🔹 Code réellement exécuté :\n", generated_code)
255
  exec(generated_code, exec_env)
256
 
257
  img_path = "plot.png"
@@ -262,9 +266,12 @@ plt.close()
262
 
263
  with open(img_path, "rb") as image_file:
264
  encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
265
- return JSONResponse(content={"image_base64": encoded_string})
 
 
266
 
267
  except Exception as e:
 
268
  return JSONResponse(content={"error": f"Erreur lors de la génération du graphique : {str(e)}"}, status_code=500)
269
 
270
 
 
192
  print("hello")
193
  @app.post("/generate_viz/")
194
  async def generate_viz(file: UploadFile = File(...), query: str = Form(...)):
195
+ print("🔵 Début /generate_viz")
196
  try:
 
 
 
 
197
  if query not in VALID_PLOTS:
198
  return JSONResponse(content={"error": f"Type de graphique invalide. Choisissez parmi : {', '.join(VALID_PLOTS)}"}, status_code=400)
199
 
200
+ df = pd.read_excel(file.file)
201
  numeric_cols = df.select_dtypes(include=["number"]).columns
202
 
203
  if len(numeric_cols) < 1:
 
207
  y_col = numeric_cols[1] if query != "histplot" and len(numeric_cols) > 1 else None
208
  prompt_y = f', y="{y_col}"' if y_col else ""
209
 
210
+ # Prompt pour l'IA
211
  prompt = f"""
212
  ### Génère uniquement du code Python fonctionnel pour tracer un {query} avec Matplotlib et Seaborn ###
213
  # Contraintes :
 
223
  plt.close()
224
  """
225
 
226
+ print("🟣 Prompt envoyé au modèle :")
227
+ print(prompt)
228
+
229
  inputs = codegen_tokenizer(prompt, return_tensors="pt").to(device)
230
+ outputs = codegen_model.generate(
231
+ **inputs,
232
+ max_new_tokens=120,
233
+ pad_token_id=codegen_tokenizer.eos_token_id
234
+ )
235
 
236
+ print("🟠 Raw output du modèle :")
237
+ print(outputs)
 
238
 
239
+ generated_code = codegen_tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
 
240
 
241
+ # Nettoyage
242
+ generated_code = re.sub(r"(import matplotlib.pyplot as plt\nimport seaborn as sns\n)+", "import matplotlib.pyplot as plt\nimport seaborn as sns\n", generated_code)
243
  if generated_code.strip().endswith("sns."):
244
  generated_code = generated_code.rsplit("\n", 1)[0]
245
 
246
+ print("🔵 Code généré propre :")
247
+ print(generated_code)
248
+
249
+ if not generated_code.strip():
250
+ return JSONResponse(content={"error": "Erreur : Code généré vide."}, status_code=500)
251
 
252
  try:
253
  compile(generated_code, "<string>", "exec")
254
  except SyntaxError as e:
255
  return JSONResponse(content={"error": f"Erreur de syntaxe détectée : {e}\nCode généré :\n{generated_code}"}, status_code=422)
256
 
257
+ exec_env = {"df": df, "plt": plt, "sns": sns, "pd": pd}
258
+ print("🔹🔹🔹 Code réellement exécuté :")
 
 
 
259
  exec(generated_code, exec_env)
260
 
261
  img_path = "plot.png"
 
266
 
267
  with open(img_path, "rb") as image_file:
268
  encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
269
+
270
+ print("🟢 Génération réussie ✅")
271
+ return JSONResponse(content={"image_base64": encoded_string})
272
 
273
  except Exception as e:
274
+ print(f"🔴 Erreur serveur : {e}")
275
  return JSONResponse(content={"error": f"Erreur lors de la génération du graphique : {str(e)}"}, status_code=500)
276
 
277