Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,55 +1,30 @@
|
|
1 |
-
import
|
2 |
-
from google import genai
|
3 |
-
from google.genai import types
|
4 |
-
from PIL import Image
|
5 |
import os
|
6 |
import tempfile
|
|
|
|
|
|
|
|
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
|
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 |
-
|
147 |
-
|
148 |
-
"""Génère une réponse au format texte brut à partir du modèle Gemini."""
|
149 |
try:
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
|
|
|
|
|
|
|
|
|
|
158 |
)
|
|
|
|
|
|
|
|
|
|
|
159 |
|
160 |
-
|
161 |
-
|
162 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
163 |
except Exception as e:
|
164 |
-
|
165 |
-
return
|
166 |
-
|
167 |
-
|
168 |
-
def
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
178 |
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
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)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|