Spaces:
Running
Running
add
Browse files
app.py
CHANGED
@@ -176,36 +176,37 @@ async def translate_document(file: UploadFile = File(...), target_lang: str = Fo
|
|
176 |
|
177 |
|
178 |
|
179 |
-
|
|
|
|
|
|
|
180 |
codegen_model_name = "Salesforce/codegen-350M-mono"
|
181 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
182 |
|
183 |
codegen_tokenizer = AutoTokenizer.from_pretrained(codegen_model_name)
|
184 |
codegen_model = AutoModelForCausalLM.from_pretrained(codegen_model_name).to(device)
|
185 |
|
186 |
-
VALID_PLOTS = {"histplot", "scatterplot", "barplot", "lineplot", "boxplot"}
|
187 |
|
|
|
|
|
188 |
@app.post("/generate_viz/")
|
189 |
async def generate_viz(file: UploadFile = File(...), query: str = Form(...)):
|
|
|
190 |
try:
|
191 |
if query not in VALID_PLOTS:
|
192 |
-
return {"error": f"Type de graphique invalide. Choisissez parmi : {', '.join(VALID_PLOTS)}"}
|
193 |
|
194 |
df = pd.read_excel(file.file)
|
195 |
-
|
196 |
numeric_cols = df.select_dtypes(include=["number"]).columns
|
197 |
-
if len(numeric_cols) < 2:
|
198 |
-
return {"error": "Le fichier doit contenir au moins deux colonnes numériques."}
|
199 |
|
200 |
-
|
|
|
201 |
|
202 |
-
|
203 |
-
if query
|
204 |
-
|
205 |
-
else:
|
206 |
-
prompt_y = f', y="{y_col}"'
|
207 |
|
208 |
-
#
|
209 |
prompt = f"""
|
210 |
### Génère uniquement du code Python fonctionnel pour tracer un {query} avec Matplotlib et Seaborn ###
|
211 |
# Contraintes :
|
@@ -213,8 +214,6 @@ async def generate_viz(file: UploadFile = File(...), query: str = Form(...)):
|
|
213 |
# - Axe X : '{x_col}'
|
214 |
# - Enregistre le graphique sous 'plot.png'
|
215 |
# - Ne génère que du code Python valide, sans texte explicatif
|
216 |
-
# Contraintes spécifiques pour sns.histplot :
|
217 |
-
# - N'inclut pas "y=" car histplot ne supporte qu'un axe
|
218 |
import matplotlib.pyplot as plt
|
219 |
import seaborn as sns
|
220 |
plt.figure(figsize=(8,6))
|
@@ -223,49 +222,38 @@ plt.savefig("plot.png")
|
|
223 |
plt.close()
|
224 |
"""
|
225 |
|
226 |
-
# Génération du code
|
227 |
inputs = codegen_tokenizer(prompt, return_tensors="pt").to(device)
|
228 |
outputs = codegen_model.generate(**inputs, max_new_tokens=120, pad_token_id=codegen_tokenizer.eos_token_id)
|
229 |
generated_code = codegen_tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
230 |
-
|
|
|
231 |
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)
|
232 |
if generated_code.strip().endswith("sns."):
|
233 |
-
generated_code = generated_code.rsplit("\n", 1)[0]
|
234 |
|
235 |
print("🔹 Code généré par l'IA :\n", generated_code)
|
236 |
|
237 |
-
# Vérification syntaxique avant exécution
|
238 |
try:
|
239 |
compile(generated_code, "<string>", "exec")
|
240 |
except SyntaxError as e:
|
241 |
-
return {"error": f"Erreur de syntaxe détectée : {e}\nCode généré :\n{generated_code}"}
|
242 |
-
|
243 |
-
# Vérification des données
|
244 |
-
print(df.head()) # Affiche les premières lignes du dataframe
|
245 |
-
print(df.dtypes) # Vérifie les types de colonnes
|
246 |
-
print(f"Colonne '{x_col}' - Valeurs uniques:", df[x_col].unique())
|
247 |
|
248 |
-
if df.empty or x_col not in df.columns or df[x_col].isnull().all():
|
249 |
-
return {"error": f"La colonne '{x_col}' est absente ou ne contient pas de données valides."}
|
250 |
-
|
251 |
-
# Exécution du code généré
|
252 |
exec_env = {"df": df, "plt": plt, "sns": sns, "pd": pd}
|
253 |
exec(generated_code, exec_env)
|
254 |
|
255 |
-
# Vérification de l'image générée
|
256 |
img_path = "plot.png"
|
257 |
if not os.path.exists(img_path):
|
258 |
-
return {"error": "Le fichier plot.png n'a pas été généré."}
|
259 |
if os.path.getsize(img_path) == 0:
|
260 |
-
return {"error": "Le fichier plot.png est vide."}
|
261 |
|
262 |
-
|
263 |
-
|
|
|
|
|
264 |
|
265 |
except Exception as e:
|
266 |
-
|
267 |
-
return {"error": f"Erreur lors de la génération du graphique : {str(e)}"}
|
268 |
-
|
269 |
|
270 |
|
271 |
|
|
|
176 |
|
177 |
|
178 |
|
179 |
+
|
180 |
+
|
181 |
+
|
182 |
+
# Charger le modèle pour la génération de code
|
183 |
codegen_model_name = "Salesforce/codegen-350M-mono"
|
184 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
185 |
|
186 |
codegen_tokenizer = AutoTokenizer.from_pretrained(codegen_model_name)
|
187 |
codegen_model = AutoModelForCausalLM.from_pretrained(codegen_model_name).to(device)
|
188 |
|
|
|
189 |
|
190 |
+
VALID_PLOTS = {"histplot", "scatterplot", "barplot", "lineplot", "boxplot"}
|
191 |
+
print("hello")
|
192 |
@app.post("/generate_viz/")
|
193 |
async def generate_viz(file: UploadFile = File(...), query: str = Form(...)):
|
194 |
+
print("hello")
|
195 |
try:
|
196 |
if query not in VALID_PLOTS:
|
197 |
+
return JSONResponse(content={"error": f"Type de graphique invalide. Choisissez parmi : {', '.join(VALID_PLOTS)}"}, status_code=400)
|
198 |
|
199 |
df = pd.read_excel(file.file)
|
|
|
200 |
numeric_cols = df.select_dtypes(include=["number"]).columns
|
|
|
|
|
201 |
|
202 |
+
if len(numeric_cols) < 1:
|
203 |
+
return JSONResponse(content={"error": "Le fichier doit contenir au moins une colonne numérique."}, status_code=400)
|
204 |
|
205 |
+
x_col = numeric_cols[0]
|
206 |
+
y_col = numeric_cols[1] if query != "histplot" and len(numeric_cols) > 1 else None
|
207 |
+
prompt_y = f', y="{y_col}"' if y_col else ""
|
|
|
|
|
208 |
|
209 |
+
# Prompt d'entrée pour le modèle
|
210 |
prompt = f"""
|
211 |
### Génère uniquement du code Python fonctionnel pour tracer un {query} avec Matplotlib et Seaborn ###
|
212 |
# Contraintes :
|
|
|
214 |
# - Axe X : '{x_col}'
|
215 |
# - Enregistre le graphique sous 'plot.png'
|
216 |
# - Ne génère que du code Python valide, sans texte explicatif
|
|
|
|
|
217 |
import matplotlib.pyplot as plt
|
218 |
import seaborn as sns
|
219 |
plt.figure(figsize=(8,6))
|
|
|
222 |
plt.close()
|
223 |
"""
|
224 |
|
|
|
225 |
inputs = codegen_tokenizer(prompt, return_tensors="pt").to(device)
|
226 |
outputs = codegen_model.generate(**inputs, max_new_tokens=120, pad_token_id=codegen_tokenizer.eos_token_id)
|
227 |
generated_code = codegen_tokenizer.decode(outputs[0], skip_special_tokens=True).strip()
|
228 |
+
|
229 |
+
# Nettoyage
|
230 |
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)
|
231 |
if generated_code.strip().endswith("sns."):
|
232 |
+
generated_code = generated_code.rsplit("\n", 1)[0]
|
233 |
|
234 |
print("🔹 Code généré par l'IA :\n", generated_code)
|
235 |
|
|
|
236 |
try:
|
237 |
compile(generated_code, "<string>", "exec")
|
238 |
except SyntaxError as e:
|
239 |
+
return JSONResponse(content={"error": f"Erreur de syntaxe détectée : {e}\nCode généré :\n{generated_code}"}, status_code=422)
|
|
|
|
|
|
|
|
|
|
|
240 |
|
|
|
|
|
|
|
|
|
241 |
exec_env = {"df": df, "plt": plt, "sns": sns, "pd": pd}
|
242 |
exec(generated_code, exec_env)
|
243 |
|
|
|
244 |
img_path = "plot.png"
|
245 |
if not os.path.exists(img_path):
|
246 |
+
return JSONResponse(content={"error": "Le fichier plot.png n'a pas été généré."}, status_code=500)
|
247 |
if os.path.getsize(img_path) == 0:
|
248 |
+
return JSONResponse(content={"error": "Le fichier plot.png est vide."}, status_code=500)
|
249 |
|
250 |
+
# Encoder l'image en base64
|
251 |
+
with open(img_path, "rb") as image_file:
|
252 |
+
encoded_string = base64.b64encode(image_file.read()).decode('utf-8')
|
253 |
+
return JSONResponse(content={"image_base64": encoded_string})
|
254 |
|
255 |
except Exception as e:
|
256 |
+
return JSONResponse(content={"error": f"Erreur lors de la génération du graphique : {str(e)}"}, status_code=500)
|
|
|
|
|
257 |
|
258 |
|
259 |
|