Docfile commited on
Commit
04084ef
·
verified ·
1 Parent(s): d3922dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -92
app.py CHANGED
@@ -1,117 +1,62 @@
1
- from flask import Flask, render_template, request, send_file
2
  import google.generativeai as genai
3
  import os
4
- import re
5
- import subprocess
6
- import uuid
7
- import tempfile
8
 
9
- # Configuration de l'API Gemini
 
 
10
  token = os.environ.get("TOKEN")
11
  genai.configure(api_key=token)
 
12
  generation_config = {
13
  "temperature": 1,
14
  "top_p": 0.95,
15
  "top_k": 64,
16
  "max_output_tokens": 8192,
17
  }
 
18
  safety_settings = [
19
  {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
20
  {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
21
  {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
22
  {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
23
  ]
 
 
 
24
  model = genai.GenerativeModel(
25
  model_name="gemini-1.5-pro",
26
  generation_config=generation_config,
27
- safety_settings=safety_settings,
28
  )
29
 
30
- app = Flask(__name__)
31
-
32
- # Dossiers pour les fichiers temporaires
33
- app.config['UPLOAD_FOLDER'] = 'static/temp_images'
34
- app.config['CHEM_RENDERS_FOLDER'] = 'static/chem_renders'
35
- if not os.path.exists(app.config['UPLOAD_FOLDER']):
36
- os.makedirs(app.config['UPLOAD_FOLDER'])
37
- if not os.path.exists(app.config['CHEM_RENDERS_FOLDER']):
38
- os.makedirs(app.config['CHEM_RENDERS_FOLDER'])
39
-
40
- # Fonction pour extraire et traiter les structures chimiques
41
- def process_chemfig(text):
42
- chemfig_pattern = r"\\chemfig{(.*?)}"
43
- matches = re.findall(chemfig_pattern, text)
44
- image_paths = []
45
-
46
- for match in matches:
47
- try:
48
- # Créer un fichier LaTeX temporaire
49
- tex_filename = str(uuid.uuid4()) + '.tex'
50
- tex_filepath = os.path.join(app.config['CHEM_RENDERS_FOLDER'], tex_filename)
51
- with open(tex_filepath, 'w') as tex_file:
52
- tex_file.write(r'\documentclass[margin=10pt]{standalone}\usepackage{chemfig}\begin{document}\chemfig{' + match + r'}\end{document}')
53
-
54
- # Compiler le fichier LaTeX en PDF
55
- pdf_filename = tex_filename[:-4] + '.pdf'
56
- pdf_filepath = os.path.join(app.config['CHEM_RENDERS_FOLDER'], pdf_filename)
57
- subprocess.run(['pdflatex', '-output-directory', app.config['CHEM_RENDERS_FOLDER'], tex_filepath], check=True)
58
-
59
- # Convertir le PDF en SVG
60
- svg_filename = tex_filename[:-4] + '.svg'
61
- svg_filepath = os.path.join(app.config['CHEM_RENDERS_FOLDER'], svg_filename)
62
- subprocess.run(['pdf2svg', pdf_filepath, svg_filepath], check=True)
63
-
64
- # Remplacer le motif chemfig par la balise img
65
- image_path = f'/chem_renders/{svg_filename}'
66
- image_paths.append(image_path)
67
- text = text.replace(f"\\chemfig{{{match}}}", f'<img src="{image_path}" style="max-width:100%; height:auto;" alt="Structure Chimique">')
68
-
69
- # Supprimer les fichiers temporaires
70
- os.remove(tex_filepath)
71
- os.remove(pdf_filepath)
72
-
73
- except Exception as e:
74
- text = text.replace(f"\\chemfig{{{match}}}", f'Erreur lors du rendu de la structure : {e}')
75
-
76
- return text, image_paths
77
-
78
- # Route principale
79
- @app.route('/', methods=['GET', 'POST'])
80
- def index():
81
- generated_content = ""
82
- image_paths = []
83
- if request.method == 'POST':
84
- image_file = request.files.get('image')
85
- mm = """ resous cet exercice. tu répondras en détaillant au maximum ton procédé de calcul. réponse attendue uniquement en Latex
86
-
87
- """
88
- if image_file :
89
- image_bytes = image_file.read()
90
- parts=[
91
- {
92
- "mime_type":"image/jpeg",
93
- "data": image_bytes
94
- },
95
- mm
96
- ]
97
- response = model.generate_content(parts)
98
- generated_content = response.text
99
- else:
100
- text_input= request.form.get('text_input')
101
- response = model.generate_content(mm+text_input)
102
- generated_content = response.text
103
-
104
- generated_content, image_paths = process_chemfig(generated_content)
105
- return render_template('index.html', generated_content=generated_content, image_paths=image_paths)
106
-
107
- # Routes pour servir les fichiers temporaires
108
- @app.route('/temp_images/<filename>')
109
- def temp_image(filename):
110
- return send_file(os.path.join(app.config['UPLOAD_FOLDER'], filename), mimetype='image/png')
111
-
112
- @app.route('/chem_renders/<filename>')
113
- def chem_render(filename):
114
- return send_file(os.path.join(app.config['CHEM_RENDERS_FOLDER'], filename), mimetype='image/svg+xml')
115
 
116
  if __name__ == '__main__':
117
  app.run(debug=True)
 
1
+ from flask import Flask, render_template, request, jsonify
2
  import google.generativeai as genai
3
  import os
4
+ from PIL import Image
5
+ import io
6
+ import base64
 
7
 
8
+ app = Flask(__name__)
9
+
10
+ # Configuration Gemini
11
  token = os.environ.get("TOKEN")
12
  genai.configure(api_key=token)
13
+
14
  generation_config = {
15
  "temperature": 1,
16
  "top_p": 0.95,
17
  "top_k": 64,
18
  "max_output_tokens": 8192,
19
  }
20
+
21
  safety_settings = [
22
  {"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
23
  {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
24
  {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
25
  {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
26
  ]
27
+
28
+ mm = """ resous cet exercice. tu répondras en détaillant au maximum ton procédé de calcul. réponse attendue uniquement en Latex"""
29
+
30
  model = genai.GenerativeModel(
31
  model_name="gemini-1.5-pro",
32
  generation_config=generation_config,
33
+ safety_settings=safety_settings
34
  )
35
 
36
+ @app.route('/')
37
+ def home():
38
+ return render_template('index.html')
39
+
40
+ @app.route('/generate', methods=['POST'])
41
+ def generate():
42
+ try:
43
+ # Récupérer l'image depuis la requête
44
+ image_data = request.json.get('image')
45
+ if not image_data:
46
+ return jsonify({"result": "djo"})
47
+
48
+ # Convertir l'image base64 en image PIL
49
+ image_data = image_data.split(',')[1]
50
+ image_bytes = base64.b64decode(image_data)
51
+ image = Image.open(io.BytesIO(image_bytes))
52
+
53
+ # Générer le contenu
54
+ response = model.generate_content([mm, image])
55
+ result = response.text
56
+
57
+ return jsonify({"result": result})
58
+ except Exception as e:
59
+ return jsonify({"error": str(e)}), 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  if __name__ == '__main__':
62
  app.run(debug=True)