Spaces:
Sleeping
Sleeping
File size: 4,529 Bytes
b30ad3b a10ea6b 5f9325a ae30a13 b30ad3b ae30a13 5f9325a b30ad3b 5f9325a b30ad3b 3f35d09 ae30a13 b30ad3b ae30a13 b30ad3b ae30a13 b30ad3b ae30a13 b30ad3b 3f35d09 b30ad3b 3f35d09 b30ad3b ae30a13 b30ad3b ae30a13 b30ad3b a10ea6b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
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'<img src="{image_path}" style="max-width:100%; height:auto;" alt="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/<filename>')
def temp_image(filename):
return send_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), mimetype='image/png')
@app.route('/chem_renders/<filename>')
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) |