from flask import Flask, render_template, request, send_file import google.generativeai as genai import os import re import subprocess import uuid import tempfile # Configuration de l'API Gemini token = os.environ.get("TOKEN") genai.configure(api_key=token) generation_config = { "temperature": 1, "top_p": 0.95, "top_k": 64, "max_output_tokens": 8192, } safety_settings = [ {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"}, {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}, {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"}, {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"}, ] model = genai.GenerativeModel( model_name="gemini-1.5-pro", generation_config=generation_config, safety_settings=safety_settings, ) app = Flask(__name__) # Dossiers pour les fichiers temporaires app.config['UPLOAD_FOLDER'] = 'static/temp_images' app.config['CHEM_RENDERS_FOLDER'] = 'static/chem_renders' if not os.path.exists(app.config['UPLOAD_FOLDER']): os.makedirs(app.config['UPLOAD_FOLDER']) if not os.path.exists(app.config['CHEM_RENDERS_FOLDER']): os.makedirs(app.config['CHEM_RENDERS_FOLDER']) # Fonction pour extraire et traiter les structures chimiques def process_chemfig(text): chemfig_pattern = r"\\chemfig{(.*?)}" matches = re.findall(chemfig_pattern, text) image_paths = [] for match in matches: try: # Créer un fichier LaTeX temporaire tex_filename = str(uuid.uuid4()) + '.tex' tex_filepath = os.path.join(app.config['CHEM_RENDERS_FOLDER'], tex_filename) with open(tex_filepath, 'w') as tex_file: tex_file.write(r'\documentclass[margin=10pt]{standalone}\usepackage{chemfig}\begin{document}\chemfig{' + match + r'}\end{document}') # Compiler le fichier LaTeX en PDF pdf_filename = tex_filename[:-4] + '.pdf' pdf_filepath = os.path.join(app.config['CHEM_RENDERS_FOLDER'], pdf_filename) subprocess.run(['pdflatex', '-output-directory', app.config['CHEM_RENDERS_FOLDER'], tex_filepath], check=True) # Convertir le PDF en SVG svg_filename = tex_filename[:-4] + '.svg' svg_filepath = os.path.join(app.config['CHEM_RENDERS_FOLDER'], svg_filename) subprocess.run(['pdf2svg', pdf_filepath, svg_filepath], check=True) # Remplacer le motif chemfig par la balise img image_path = f'/chem_renders/{svg_filename}' image_paths.append(image_path) text = text.replace(f"\\chemfig{{{match}}}", f'Structure Chimique') # Supprimer les fichiers temporaires os.remove(tex_filepath) os.remove(pdf_filepath) except Exception as e: text = text.replace(f"\\chemfig{{{match}}}", f'Erreur lors du rendu de la structure : {e}') return text, image_paths # Route principale @app.route('/', methods=['GET', 'POST']) def index(): generated_content = "" image_paths = [] if request.method == 'POST': image_file = request.files.get('image') mm = """ resous cet exercice. tu répondras en détaillant au maximum ton procédé de calcul. réponse attendue uniquement en Latex """ if image_file : image_bytes = image_file.read() parts=[ { "mime_type":"image/jpeg", "data": image_bytes }, mm ] response = model.generate_content(parts) generated_content = response.text else: text_input= request.form.get('text_input') response = model.generate_content(mm+text_input) generated_content = response.text generated_content, image_paths = process_chemfig(generated_content) return render_template('index.html', generated_content=generated_content, image_paths=image_paths) # Routes pour servir les fichiers temporaires @app.route('/temp_images/') def temp_image(filename): return send_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), mimetype='image/png') @app.route('/chem_renders/') def chem_render(filename): return send_file(os.path.join(app.config['CHEM_RENDERS_FOLDER'], filename), mimetype='image/svg+xml') if __name__ == '__main__': app.run(debug=True)