Docfile commited on
Commit
bd7cf3a
·
verified ·
1 Parent(s): 37b5c18

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +114 -105
app.py CHANGED
@@ -1,55 +1,30 @@
1
- import streamlit as st
2
- from google import genai
3
- from google.genai import types
4
- from PIL import Image
5
  import os
6
  import tempfile
 
 
 
 
7
 
8
- # Authentification et initialisation du client Gemini
9
- gen = os.environ['GOOGLE_API_KEY']
10
- client = genai.Client(api_key=gen)
11
-
12
- # --- MISE EN PAGE ET STYLE ---
13
- st.set_page_config(page_title="Mariam Espagnol", page_icon="🇪🇸", layout="wide")
14
-
15
- # Style CSS personnalisé
16
- st.markdown("""
17
- <style>
18
- body {
19
- background-color: #f0f2f6;
20
- }
21
- .title {
22
- color: #0077cc;
23
- font-size: 3em;
24
- font-weight: bold;
25
- text-align: center;
26
- margin-bottom: 20px;
27
- }
28
- .subtitle {
29
- color: #28a745;
30
- font-size: 1.5em;
31
- font-weight: bold;
32
- margin-top: 30px;
33
- }
34
- .sidebar {
35
- background-color: #e9ecef;
36
- padding: 20px;
37
- border-radius: 10px;
38
- }
39
- .important-info {
40
- background-color: #d4edda;
41
- border: 1px solid #c3e6cb;
42
- color: #155724;
43
- padding: 15px;
44
- border-radius: 5px;
45
- margin-bottom: 10px;
46
- }
47
- </style>
48
- """, unsafe_allow_html=True)
49
-
50
- # --- PROMPT ---
51
- prompt = """
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  je souhaite faire mon travail d'espagnol qui consiste à de l'analyse de documents iconographique. j'aimerais que tu le phase en respectant scrupuleusement la méthodologie suivante. j'aimerais que tu fasses ce travail en espagnol en donnant également la traduction française
54
 
55
  Metodología del comentario de un documento iconográfico
@@ -139,69 +114,103 @@ Dar la impresión personal: esta foto (no) me parece interesante/escandaloso/per
139
  Justificamos nuestra impresión: porque revela una realidad social/política/cultural...
140
 
141
  Un modelo: a través de este cuadro, el pintor quiere denunciar las injusticias sociales en África. El cuadro me parece interesante porque releva un fenómeno social recurrente que incita las autoridades a la responsabilidad. La propia imagen ilustra muy bien el tema de las injusticias entre ricos y ricos...
 
 
 
 
142
 
 
143
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  """
145
 
146
- # --- FONCTIONS ---
147
- def generate_response(image_path, question):
148
- """Génère une réponse au format texte brut à partir du modèle Gemini."""
149
  try:
150
- image_data = Image.open(image_path)
151
- response = client.models.generate_content(
152
- model="gemini-2.5-flash-preview-04-17",
153
- contents=[image_data, prompt],
154
- config=types.GenerateContentConfig(
155
- thinking_config=types.ThinkingConfig(
156
- thinking_budget=8000
157
- )
 
 
 
 
 
158
  )
 
 
 
 
 
159
 
160
- )
161
- answer = response.candidates[0].content.parts[0].text
162
- return answer.strip()
 
 
 
 
 
 
 
 
163
  except Exception as e:
164
- st.error("Erreur lors de la génération de la réponse.")
165
- return None
166
-
167
- # --- APPLICATION PRINCIPALE ---
168
- def main():
169
- st.markdown("<h1 class='title'>Mariam Espagnol( document iconographique seulement) 🇪🇸</h1>", unsafe_allow_html=True)
170
-
171
- # --- BARRE LATÉRALE ---
172
- with st.sidebar:
173
- st.markdown("<h2 class='subtitle'>Instructions</h2>", unsafe_allow_html=True)
174
- st.markdown("""
175
- 1. **Téléchargez une image** que vous souhaitez analyser (PNG, JPG, JPEG).
176
- 2. L'application **générera une analyse** de l'image en espagnol et en français, en suivant la méthodologie fournie.
177
- """)
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
- # --- SECTION PRINCIPALE ---
180
- col1, col2 = st.columns([1, 2])
181
-
182
- with col1:
183
- st.markdown("<h2 class='subtitle'>Télécharger une image</h2>", unsafe_allow_html=True)
184
- uploaded_file = st.file_uploader("", type=["png", "jpg", "jpeg"], label_visibility="collapsed")
185
-
186
- if uploaded_file is not None:
187
- with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as tmp_file:
188
- tmp_file.write(uploaded_file.getvalue())
189
- temp_image_path = tmp_file.name
190
-
191
- # Affichage de l'image
192
- image = Image.open(temp_image_path)
193
- st.image(image, use_container_width=True)
194
-
195
- with col2:
196
- if uploaded_file is not None:
197
- st.markdown("<h2 class='subtitle'>Analyse de l'image</h2>", unsafe_allow_html=True)
198
- question = "yusuf" # Question fixe pour l'instant
199
-
200
- if st.button("✨ Générer l'analyse ✨", type="primary"):
201
- with st.spinner("Analyse en cours..."):
202
- response = generate_response(temp_image_path, question)
203
- st.markdown(response)
204
-
205
- # --- EXÉCUTION ---
206
- if __name__ == "__main__":
207
- main()
 
1
+ from flask import Flask, render_template, request, jsonify
 
 
 
2
  import os
3
  import tempfile
4
+ from PIL import Image
5
+ from google import genai
6
+ from google.genai import types
7
+ import uuid
8
 
9
+ app = Flask(__name__)
10
+ app.config['UPLOAD_FOLDER'] = 'static/uploads'
11
+ app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 MB max upload
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ # Ensure upload directory exists
14
+ os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
15
+
16
+ # Google Gemini API setup
17
+ def init_gemini():
18
+ api_key = os.environ.get('GOOGLE_API_KEY')
19
+ if not api_key:
20
+ print("WARNING: GOOGLE_API_KEY environment variable not set")
21
+ return None
22
+ return genai.Client(api_key=api_key)
23
+
24
+ client = init_gemini()
25
+
26
+ # Prompts for analysis
27
+ ICONOGRAPHIC_PROMPT = """
28
  je souhaite faire mon travail d'espagnol qui consiste à de l'analyse de documents iconographique. j'aimerais que tu le phase en respectant scrupuleusement la méthodologie suivante. j'aimerais que tu fasses ce travail en espagnol en donnant également la traduction française
29
 
30
  Metodología del comentario de un documento iconográfico
 
114
  Justificamos nuestra impresión: porque revela una realidad social/política/cultural...
115
 
116
  Un modelo: a través de este cuadro, el pintor quiere denunciar las injusticias sociales en África. El cuadro me parece interesante porque releva un fenómeno social recurrente que incita las autoridades a la responsabilidad. La propia imagen ilustra muy bien el tema de las injusticias entre ricos y ricos...
117
+ """
118
+
119
+ TEXT_PROMPT = """
120
+ Je souhaite faire une analyse de texte en espagnol en respectant scrupuleusement la méthodologie suivante. J'aimerais que tu fasses ce travail en espagnol en donnant également la traduction française.
121
 
122
+ Metodología del comentario de texto en español:
123
 
124
+ 1. Presentación del documento
125
+ - Autor y contexto histórico
126
+ - Naturaleza del texto (literario, periodístico, discurso, etc.)
127
+ - Tema principal
128
+
129
+ 2. Análisis de la estructura
130
+ - División en partes lógicas
131
+ - Identificación de la organización de las ideas
132
+
133
+ 3. Análisis del contenido
134
+ - Ideas principales y secundarias
135
+ - Intención del autor
136
+ - Recursos lingüísticos utilizados
137
+ - Vocabulario y campo semántico
138
+
139
+ 4. Conclusión
140
+ - Síntesis del análisis
141
+ - Aportación personal
142
+ - Relevancia del texto en su contexto
143
+
144
+ Por favor, analiza este texto según la metodología indicada, proporcionando el análisis completo en español y su traducción al francés.
145
  """
146
 
147
+ def generate_response(file_path, file_type):
148
+ """Generate response using Gemini API based on file type"""
 
149
  try:
150
+ if not client:
151
+ return "Error: Google API key not configured properly."
152
+
153
+ if file_type == 'image':
154
+ image_data = Image.open(file_path)
155
+ response = client.models.generate_content(
156
+ model="gemini-2.5-flash-preview-04-17",
157
+ contents=[image_data, ICONOGRAPHIC_PROMPT],
158
+ config=types.GenerateContentConfig(
159
+ thinking_config=types.ThinkingConfig(
160
+ thinking_budget=8000
161
+ )
162
+ ),
163
  )
164
+ return response.candidates[0].content.parts[0].text.strip()
165
+
166
+ elif file_type == 'text':
167
+ with open(file_path, 'r', encoding='utf-8') as f:
168
+ text_content = f.read()
169
 
170
+ response = client.models.generate_content(
171
+ model="gemini-2.5-flash-preview-04-17",
172
+ contents=[text_content, TEXT_PROMPT],
173
+ config=types.GenerateContentConfig(
174
+ thinking_config=types.ThinkingConfig(
175
+ thinking_budget=8000
176
+ )
177
+ ),
178
+ )
179
+ return response.candidates[0].content.parts[0].text.strip()
180
+
181
  except Exception as e:
182
+ print(f"Error generating response: {e}")
183
+ return f"Error durante el análisis: {str(e)}"
184
+
185
+ @app.route('/')
186
+ def index():
187
+ return render_template('index.html')
188
+
189
+ @app.route('/upload', methods=['POST'])
190
+ def upload_file():
191
+ if 'file' not in request.files:
192
+ return jsonify({'error': 'No file part'}), 400
193
+
194
+ file = request.files['file']
195
+ file_type = request.form.get('fileType', 'image')
196
+
197
+ if file.filename == '':
198
+ return jsonify({'error': 'No selected file'}), 400
199
+
200
+ if file:
201
+ # Generate a unique filename
202
+ filename = f"{uuid.uuid4()}_{file.filename}"
203
+ file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
204
+ file.save(file_path)
205
+
206
+ # Generate analysis
207
+ analysis = generate_response(file_path, file_type)
208
 
209
+ return jsonify({
210
+ 'success': True,
211
+ 'file_url': f"/static/uploads/{filename}",
212
+ 'analysis': analysis
213
+ })
214
+
215
+ if __name__ == '__main__':
216
+ app.run(debug=True)