Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,11 +4,11 @@ import os
|
|
4 |
from PIL import Image
|
5 |
import tempfile
|
6 |
import PIL.Image
|
|
|
7 |
import time
|
8 |
import ssl
|
9 |
-
import requests
|
10 |
from urllib.parse import urlparse
|
11 |
-
|
12 |
|
13 |
app = Flask(__name__)
|
14 |
|
@@ -28,6 +28,26 @@ safety_settings = [
|
|
28 |
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
29 |
]
|
30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
@app.route('/')
|
32 |
def generale():
|
33 |
return render_template("generale.html")
|
@@ -36,19 +56,19 @@ def upload_and_process_file(file_path):
|
|
36 |
"""Upload et traite un fichier avec l'API Gemini avec gestion des erreurs améliorée"""
|
37 |
max_retries = 3
|
38 |
retry_delay = 2 # secondes
|
39 |
-
|
40 |
for attempt in range(max_retries):
|
41 |
try:
|
42 |
print(f"Tentative d'upload {attempt + 1}/{max_retries} pour {file_path}")
|
43 |
-
|
44 |
# Vérification du fichier
|
45 |
if not os.path.exists(file_path):
|
46 |
raise FileNotFoundError(f"Le fichier {file_path} n'existe pas")
|
47 |
-
|
48 |
file_size = os.path.getsize(file_path)
|
49 |
if file_size == 0:
|
50 |
raise ValueError(f"Le fichier {file_path} est vide")
|
51 |
-
|
52 |
# Upload du fichier
|
53 |
uploaded_file = genai.upload_file(path=file_path)
|
54 |
print(f"Upload réussi: {uploaded_file.uri}")
|
@@ -56,18 +76,18 @@ def upload_and_process_file(file_path):
|
|
56 |
# Attente du traitement
|
57 |
timeout = 300 # 5 minutes
|
58 |
start_time = time.time()
|
59 |
-
|
60 |
while uploaded_file.state.name == "PROCESSING":
|
61 |
if time.time() - start_time > timeout:
|
62 |
raise TimeoutError("Timeout pendant le traitement du fichier")
|
63 |
-
|
64 |
print(f"En attente du traitement... Temps écoulé: {int(time.time() - start_time)}s")
|
65 |
time.sleep(10)
|
66 |
uploaded_file = genai.get_file(uploaded_file.name)
|
67 |
|
68 |
if uploaded_file.state.name == "FAILED":
|
69 |
raise ValueError(f"Échec du traitement: {uploaded_file.state.name}")
|
70 |
-
|
71 |
print(f"Traitement terminé avec succès: {uploaded_file.uri}")
|
72 |
return uploaded_file
|
73 |
|
@@ -77,13 +97,15 @@ def upload_and_process_file(file_path):
|
|
77 |
time.sleep(retry_delay * (attempt + 1))
|
78 |
else:
|
79 |
raise
|
80 |
-
|
81 |
except Exception as e:
|
82 |
print(f"Erreur lors de l'upload (tentative {attempt + 1}): {e}")
|
83 |
if attempt < max_retries - 1:
|
84 |
time.sleep(retry_delay * (attempt + 1))
|
85 |
else:
|
86 |
raise
|
|
|
|
|
87 |
|
88 |
def is_youtube_url(url):
|
89 |
"""Vérifie si l'URL est une URL YouTube"""
|
@@ -101,23 +123,23 @@ def download_youtube_video(url):
|
|
101 |
'no_warnings': True,
|
102 |
'extract_flat': False
|
103 |
}
|
104 |
-
|
105 |
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
106 |
print(f"Téléchargement de la vidéo: {url}")
|
107 |
info = ydl.extract_info(url, download=True)
|
108 |
video_path = os.path.join(temp_dir, ydl.prepare_filename(info))
|
109 |
-
|
110 |
if not os.path.exists(video_path):
|
111 |
raise FileNotFoundError(f"La vidéo n'a pas été téléchargée correctement: {video_path}")
|
112 |
-
|
113 |
# Copie vers un fichier temporaire permanent
|
114 |
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(video_path)[1])
|
115 |
with open(video_path, 'rb') as f:
|
116 |
temp_file.write(f.read())
|
117 |
-
|
118 |
print(f"Vidéo téléchargée avec succès: {temp_file.name}")
|
119 |
return temp_file.name
|
120 |
-
|
121 |
except Exception as e:
|
122 |
print(f"Erreur lors du téléchargement de la vidéo: {e}")
|
123 |
return None
|
@@ -145,12 +167,12 @@ def submit_question():
|
|
145 |
question = request.form.get('question')
|
146 |
urls = request.form.getlist('urls')
|
147 |
files = request.files.getlist('files')
|
148 |
-
|
149 |
-
|
150 |
print("URLs reçues:", urls)
|
151 |
content = [question]
|
152 |
temp_files = []
|
153 |
-
|
154 |
try:
|
155 |
# Traitement des fichiers uploadés
|
156 |
for file in files:
|
@@ -180,22 +202,20 @@ def submit_question():
|
|
180 |
uploaded_file = upload_and_process_file(pdf_path)
|
181 |
content.append(uploaded_file)
|
182 |
|
|
|
|
|
|
|
183 |
# Génération de contenu avec Gemini
|
184 |
model = genai.GenerativeModel(
|
185 |
model_name="models/gemini-1.5-flash-002",
|
186 |
safety_settings=safety_settings,
|
187 |
-
system_instruction="Tu es un assistant intelligent. ton but est d'assister au mieux que tu peux. tu as été créé par Aenir et tu t'appelles Mariam."
|
|
|
188 |
)
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
contents=question,
|
194 |
-
tools=[{"function_declarations": [{"name": "google_search", "description": "Tool to retrieve search results from Google Search.", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "The query string to search for."}}, "required": ["query"]}}]}]
|
195 |
-
)
|
196 |
-
else:
|
197 |
-
response = model.generate_content(content, request_options={"timeout": 600})
|
198 |
-
|
199 |
return jsonify({"response": response.text})
|
200 |
|
201 |
except Exception as e:
|
|
|
4 |
from PIL import Image
|
5 |
import tempfile
|
6 |
import PIL.Image
|
7 |
+
import requests
|
8 |
import time
|
9 |
import ssl
|
|
|
10 |
from urllib.parse import urlparse
|
11 |
+
import yt_dlp
|
12 |
|
13 |
app = Flask(__name__)
|
14 |
|
|
|
28 |
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
29 |
]
|
30 |
|
31 |
+
# Configuration de la recherche Google
|
32 |
+
google_search = genai.Tool(
|
33 |
+
function_declarations=[
|
34 |
+
genai.FunctionDeclaration(
|
35 |
+
name="google_search",
|
36 |
+
description="A search engine. Useful for when you need to answer questions about current events. Input should be a search query.",
|
37 |
+
parameters={
|
38 |
+
"type": "object",
|
39 |
+
"properties": {
|
40 |
+
"query": {
|
41 |
+
"type": "string",
|
42 |
+
"description": "The search query.",
|
43 |
+
},
|
44 |
+
},
|
45 |
+
"required": ["query"],
|
46 |
+
},
|
47 |
+
),
|
48 |
+
]
|
49 |
+
)
|
50 |
+
|
51 |
@app.route('/')
|
52 |
def generale():
|
53 |
return render_template("generale.html")
|
|
|
56 |
"""Upload et traite un fichier avec l'API Gemini avec gestion des erreurs améliorée"""
|
57 |
max_retries = 3
|
58 |
retry_delay = 2 # secondes
|
59 |
+
|
60 |
for attempt in range(max_retries):
|
61 |
try:
|
62 |
print(f"Tentative d'upload {attempt + 1}/{max_retries} pour {file_path}")
|
63 |
+
|
64 |
# Vérification du fichier
|
65 |
if not os.path.exists(file_path):
|
66 |
raise FileNotFoundError(f"Le fichier {file_path} n'existe pas")
|
67 |
+
|
68 |
file_size = os.path.getsize(file_path)
|
69 |
if file_size == 0:
|
70 |
raise ValueError(f"Le fichier {file_path} est vide")
|
71 |
+
|
72 |
# Upload du fichier
|
73 |
uploaded_file = genai.upload_file(path=file_path)
|
74 |
print(f"Upload réussi: {uploaded_file.uri}")
|
|
|
76 |
# Attente du traitement
|
77 |
timeout = 300 # 5 minutes
|
78 |
start_time = time.time()
|
79 |
+
|
80 |
while uploaded_file.state.name == "PROCESSING":
|
81 |
if time.time() - start_time > timeout:
|
82 |
raise TimeoutError("Timeout pendant le traitement du fichier")
|
83 |
+
|
84 |
print(f"En attente du traitement... Temps écoulé: {int(time.time() - start_time)}s")
|
85 |
time.sleep(10)
|
86 |
uploaded_file = genai.get_file(uploaded_file.name)
|
87 |
|
88 |
if uploaded_file.state.name == "FAILED":
|
89 |
raise ValueError(f"Échec du traitement: {uploaded_file.state.name}")
|
90 |
+
|
91 |
print(f"Traitement terminé avec succès: {uploaded_file.uri}")
|
92 |
return uploaded_file
|
93 |
|
|
|
97 |
time.sleep(retry_delay * (attempt + 1))
|
98 |
else:
|
99 |
raise
|
100 |
+
|
101 |
except Exception as e:
|
102 |
print(f"Erreur lors de l'upload (tentative {attempt + 1}): {e}")
|
103 |
if attempt < max_retries - 1:
|
104 |
time.sleep(retry_delay * (attempt + 1))
|
105 |
else:
|
106 |
raise
|
107 |
+
|
108 |
+
|
109 |
|
110 |
def is_youtube_url(url):
|
111 |
"""Vérifie si l'URL est une URL YouTube"""
|
|
|
123 |
'no_warnings': True,
|
124 |
'extract_flat': False
|
125 |
}
|
126 |
+
|
127 |
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
|
128 |
print(f"Téléchargement de la vidéo: {url}")
|
129 |
info = ydl.extract_info(url, download=True)
|
130 |
video_path = os.path.join(temp_dir, ydl.prepare_filename(info))
|
131 |
+
|
132 |
if not os.path.exists(video_path):
|
133 |
raise FileNotFoundError(f"La vidéo n'a pas été téléchargée correctement: {video_path}")
|
134 |
+
|
135 |
# Copie vers un fichier temporaire permanent
|
136 |
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(video_path)[1])
|
137 |
with open(video_path, 'rb') as f:
|
138 |
temp_file.write(f.read())
|
139 |
+
|
140 |
print(f"Vidéo téléchargée avec succès: {temp_file.name}")
|
141 |
return temp_file.name
|
142 |
+
|
143 |
except Exception as e:
|
144 |
print(f"Erreur lors du téléchargement de la vidéo: {e}")
|
145 |
return None
|
|
|
167 |
question = request.form.get('question')
|
168 |
urls = request.form.getlist('urls')
|
169 |
files = request.files.getlist('files')
|
170 |
+
web_search_enabled = request.form.get('web_search') == 'true' # Récupère l'état de la recherche web
|
171 |
+
|
172 |
print("URLs reçues:", urls)
|
173 |
content = [question]
|
174 |
temp_files = []
|
175 |
+
|
176 |
try:
|
177 |
# Traitement des fichiers uploadés
|
178 |
for file in files:
|
|
|
202 |
uploaded_file = upload_and_process_file(pdf_path)
|
203 |
content.append(uploaded_file)
|
204 |
|
205 |
+
|
206 |
+
|
207 |
+
tools = [google_search] if web_search_enabled else None
|
208 |
# Génération de contenu avec Gemini
|
209 |
model = genai.GenerativeModel(
|
210 |
model_name="models/gemini-1.5-flash-002",
|
211 |
safety_settings=safety_settings,
|
212 |
+
system_instruction="Tu es un assistant intelligent. ton but est d'assister au mieux que tu peux. tu as été créé par Aenir et tu t'appelles Mariam.",
|
213 |
+
tools=tools
|
214 |
)
|
215 |
+
|
216 |
+
response = model.generate_content(content, request_options={"timeout": 600})
|
217 |
+
|
218 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
219 |
return jsonify({"response": response.text})
|
220 |
|
221 |
except Exception as e:
|