Spaces:
Sleeping
Sleeping
Update routers/searchterm.py
Browse files- routers/searchterm.py +66 -107
routers/searchterm.py
CHANGED
@@ -117,60 +117,47 @@ def create_temp_file(data: Dict[str, Any]) -> Dict[str, str]:
|
|
117 |
}
|
118 |
|
119 |
|
120 |
-
async def
|
121 |
-
"""Gera
|
122 |
try:
|
123 |
client = genai.Client(api_key=GEMINI_API_KEY)
|
124 |
model = "gemini-2.5-flash-lite"
|
125 |
|
|
|
|
|
|
|
|
|
|
|
|
|
126 |
contents = [
|
127 |
types.Content(
|
128 |
role="user",
|
129 |
parts=[
|
130 |
-
types.Part.from_text(text="
|
131 |
],
|
132 |
),
|
133 |
types.Content(
|
134 |
role="model",
|
135 |
parts=[
|
136 |
-
types.Part.from_text(text="""
|
137 |
-
```json
|
138 |
-
{
|
139 |
-
\"nome\": \"Maria Silva\",
|
140 |
-
\"idade\": 30,
|
141 |
-
\"profissao\": \"Engenheira de Software\",
|
142 |
-
\"habilidades\": [
|
143 |
-
\"Python\",
|
144 |
-
\"JavaScript\",
|
145 |
-
\"SQL\",
|
146 |
-
\"Docker\"
|
147 |
-
],
|
148 |
-
\"contato\": {
|
149 |
-
\"email\": \"[email protected]\",
|
150 |
-
\"telefone\": \"+55 11 98765-4321\"
|
151 |
-
},
|
152 |
-
\"ativo\": true,
|
153 |
-
\"projetos\": null
|
154 |
-
}
|
155 |
-
```
|
156 |
-
**Explicação dos elementos:**
|
157 |
-
* **`{}`**: Representa um objeto JSON.
|
158 |
-
* **`\"chave\": valor`**: Um objeto é composto por pares de chave-valor.
|
159 |
-
* As **chaves** são sempre strings, delimitadas por aspas duplas.
|
160 |
-
* Os **valores** podem ser de diversos tipos:
|
161 |
-
* **String:** ` \"Maria Silva\" ` (delimitada por aspas duplas)
|
162 |
-
* **Número:** ` 30 ` (inteiro ou decimal)
|
163 |
-
* **Booleano:** ` true ` ou ` false `
|
164 |
-
* **Array (Lista):** ` [\"Python\", \"JavaScript\", \"SQL\", \"Docker\"] ` (uma lista de valores, delimitada por colchetes `[]`, onde os elementos são separados por vírgulas)
|
165 |
-
* **Objeto:** ` {\"email\": \"[email protected]\", \"telefone\": \"+55 11 98765-4321\"} ` (outro objeto JSON aninhado)
|
166 |
-
* **`null`**: Representa a ausência de valor.
|
167 |
-
Este é um exemplo bastante comum e demonstra a estrutura básica do JSON."""),
|
168 |
],
|
169 |
),
|
170 |
types.Content(
|
171 |
role="user",
|
172 |
parts=[
|
173 |
-
types.Part.from_text(text=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
174 |
],
|
175 |
),
|
176 |
]
|
@@ -191,10 +178,35 @@ Este é um exemplo bastante comum e demonstra a estrutura básica do JSON."""),
|
|
191 |
if chunk.text:
|
192 |
full_response += chunk.text
|
193 |
|
194 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
195 |
|
196 |
except Exception as e:
|
197 |
-
|
|
|
198 |
|
199 |
|
200 |
async def search_brave_term(client: httpx.AsyncClient, term: str) -> List[Dict[str, str]]:
|
@@ -261,10 +273,19 @@ async def extract_article_text(url: str, session: aiohttp.ClientSession) -> str:
|
|
261 |
|
262 |
|
263 |
@router.post("/search-terms")
|
264 |
-
async def search_terms(payload: Dict[str,
|
265 |
-
|
266 |
-
if not
|
267 |
-
raise HTTPException(status_code=400, detail="Campo '
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
268 |
|
269 |
used_urls = set()
|
270 |
search_semaphore = asyncio.Semaphore(20)
|
@@ -326,55 +347,12 @@ async def search_terms(payload: Dict[str, List[str]] = Body(...)) -> Dict[str, A
|
|
326 |
return {
|
327 |
"message": "Dados salvos em arquivo temporário",
|
328 |
"total_results": len(final_results),
|
|
|
|
|
329 |
"file_info": temp_file_info
|
330 |
}
|
331 |
|
332 |
|
333 |
-
@router.post("/inference/terms")
|
334 |
-
async def inference_terms(payload: Dict[str, str] = Body(...)) -> Dict[str, Any]:
|
335 |
-
"""
|
336 |
-
Endpoint para fazer inferência com o modelo Gemini
|
337 |
-
|
338 |
-
Body:
|
339 |
-
{
|
340 |
-
"input": "Sua pergunta ou texto aqui"
|
341 |
-
}
|
342 |
-
"""
|
343 |
-
input_text = payload.get("input")
|
344 |
-
|
345 |
-
if not input_text or not isinstance(input_text, str):
|
346 |
-
raise HTTPException(
|
347 |
-
status_code=400,
|
348 |
-
detail="Campo 'input' é obrigatório e deve ser uma string."
|
349 |
-
)
|
350 |
-
|
351 |
-
if len(input_text.strip()) == 0:
|
352 |
-
raise HTTPException(
|
353 |
-
status_code=400,
|
354 |
-
detail="Campo 'input' não pode estar vazio."
|
355 |
-
)
|
356 |
-
|
357 |
-
try:
|
358 |
-
# Gera resposta usando o Gemini
|
359 |
-
response = await generate_gemini_response(input_text)
|
360 |
-
|
361 |
-
return {
|
362 |
-
"input": input_text,
|
363 |
-
"response": response,
|
364 |
-
"model": "gemini-2.5-flash-lite",
|
365 |
-
"timestamp": time.time()
|
366 |
-
}
|
367 |
-
|
368 |
-
except HTTPException:
|
369 |
-
# Re-raise HTTPExceptions para manter o status code correto
|
370 |
-
raise
|
371 |
-
except Exception as e:
|
372 |
-
raise HTTPException(
|
373 |
-
status_code=500,
|
374 |
-
detail=f"Erro interno do servidor: {str(e)}"
|
375 |
-
)
|
376 |
-
|
377 |
-
|
378 |
@router.get("/download-temp/{file_id}")
|
379 |
async def download_temp_file(file_id: str):
|
380 |
"""Endpoint para download do arquivo temporário"""
|
@@ -393,23 +371,4 @@ async def download_temp_file(file_id: str):
|
|
393 |
filename="fontes.txt",
|
394 |
media_type="text/plain",
|
395 |
headers={"Content-Disposition": "attachment; filename=fontes.txt"}
|
396 |
-
)
|
397 |
-
|
398 |
-
|
399 |
-
@router.get("/temp-files/status")
|
400 |
-
async def get_temp_files_status():
|
401 |
-
"""Endpoint para verificar status dos arquivos temporários (debug)"""
|
402 |
-
status = {}
|
403 |
-
current_time = time.time()
|
404 |
-
|
405 |
-
for file_id, info in temp_files.items():
|
406 |
-
age_hours = (current_time - info["created_at"]) / 3600
|
407 |
-
remaining_hours = max(0, 24 - age_hours)
|
408 |
-
|
409 |
-
status[file_id] = {
|
410 |
-
"age_hours": round(age_hours, 2),
|
411 |
-
"remaining_hours": round(remaining_hours, 2),
|
412 |
-
"exists": info["path"].exists()
|
413 |
-
}
|
414 |
-
|
415 |
-
return {"temp_files": status}
|
|
|
117 |
}
|
118 |
|
119 |
|
120 |
+
async def generate_search_terms(context: str) -> List[str]:
|
121 |
+
"""Gera termos de pesquisa usando o modelo Gemini"""
|
122 |
try:
|
123 |
client = genai.Client(api_key=GEMINI_API_KEY)
|
124 |
model = "gemini-2.5-flash-lite"
|
125 |
|
126 |
+
system_prompt = """Com base num contexto inicial, gere termos de pesquisa (até 20 termos, no máximo), em um JSON. Esses textos devem ser interpretados como termos que podem ser usados por outras inteligências artificiais pra pesquisar no google e retornar resultados mais refinados e completos pra busca atual. Analise muito bem o contexto, por exemplo, se está falando de uma série coreana, gere os termos em coreano por que obviamente na mídia coreana terá mais cobertura que a americana, etc.
|
127 |
+
|
128 |
+
Deve seguir esse formato: "terms": []
|
129 |
+
|
130 |
+
Retorne apenas o JSON, sem mais nenhum texto."""
|
131 |
+
|
132 |
contents = [
|
133 |
types.Content(
|
134 |
role="user",
|
135 |
parts=[
|
136 |
+
types.Part.from_text(text="Contexto: Taylor Sheridan's 'Landman' Announces Season 2 Premiere Date"),
|
137 |
],
|
138 |
),
|
139 |
types.Content(
|
140 |
role="model",
|
141 |
parts=[
|
142 |
+
types.Part.from_text(text='{"terms": [ "imdb landman episodes season 2", "imdb landman series", "landman season 2 release date", "taylor sheridan landman series", "landman season 2 cast sam elliott", "billy bob thornton returns landman", "demi moore landman new season", "andy garcia ali larter landman season 2", "landman texas oil drama", "taylor sheridan tv series schedule", "landman 10 month turnaround new episodes", "landman season 2 november 16 premiere", "sam elliott joins taylor sheridan show", "landman streaming platform premiere", "landman season 2 filming details", "landman new cast and returning actors", "taylor sheridan quick tv show production" ]}'),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
143 |
],
|
144 |
),
|
145 |
types.Content(
|
146 |
role="user",
|
147 |
parts=[
|
148 |
+
types.Part.from_text(text="Contexto: Pixar's latest animated feature will arrive on digital (via platforms like Apple TV, Amazon Prime Video, and Fandango at Home) on Aug. 19 and on physical media (4K UHD, Blu-ray and DVD) on Sept. 9. The film has not yet set a Disney+ streaming release date, but that will likely come after the Blu-ray release."),
|
149 |
+
],
|
150 |
+
),
|
151 |
+
types.Content(
|
152 |
+
role="model",
|
153 |
+
parts=[
|
154 |
+
types.Part.from_text(text='{ "terms": [ "pixar elio 2024 movie details", "disney pixar new release elio", "elio animated film august 19 digital", "pixar sci-fi comedy elio home release", "elio movie blu-ray dvd release september", "where to watch elio online", "elio streaming disney plus release date", "elio digital release apple tv amazon prime", "elio physical media 4k uhd blu-ray dvd", "elio movie bonus features", "elio cast voice actors", "elio behind the scenes making of", "elio deleted scenes blu-ray", "elio soundtrack and score", "elio merchandise release date", "upcoming disney pixar movies 2024", "pixar elio critical reviews", "elio movie box office results" ] }'),
|
155 |
+
],
|
156 |
+
),
|
157 |
+
types.Content(
|
158 |
+
role="user",
|
159 |
+
parts=[
|
160 |
+
types.Part.from_text(text=f"Contexto: {context}"),
|
161 |
],
|
162 |
),
|
163 |
]
|
|
|
178 |
if chunk.text:
|
179 |
full_response += chunk.text
|
180 |
|
181 |
+
# Tenta extrair o JSON da resposta
|
182 |
+
try:
|
183 |
+
# Remove possíveis ```json e ``` da resposta
|
184 |
+
clean_response = full_response.strip()
|
185 |
+
if clean_response.startswith("```json"):
|
186 |
+
clean_response = clean_response[7:]
|
187 |
+
if clean_response.endswith("```"):
|
188 |
+
clean_response = clean_response[:-3]
|
189 |
+
clean_response = clean_response.strip()
|
190 |
+
|
191 |
+
# Parse do JSON
|
192 |
+
response_data = json.loads(clean_response)
|
193 |
+
terms = response_data.get("terms", [])
|
194 |
+
|
195 |
+
# Validação básica
|
196 |
+
if not isinstance(terms, list):
|
197 |
+
raise ValueError("Terms deve ser uma lista")
|
198 |
+
|
199 |
+
return terms[:20] # Garante máximo de 20 termos
|
200 |
+
|
201 |
+
except (json.JSONDecodeError, ValueError) as e:
|
202 |
+
print(f"Erro ao parsear resposta do Gemini: {e}")
|
203 |
+
print(f"Resposta recebida: {full_response}")
|
204 |
+
# Retorna uma lista vazia em caso de erro
|
205 |
+
return []
|
206 |
|
207 |
except Exception as e:
|
208 |
+
print(f"Erro ao gerar termos de pesquisa: {str(e)}")
|
209 |
+
return []
|
210 |
|
211 |
|
212 |
async def search_brave_term(client: httpx.AsyncClient, term: str) -> List[Dict[str, str]]:
|
|
|
273 |
|
274 |
|
275 |
@router.post("/search-terms")
|
276 |
+
async def search_terms(payload: Dict[str, str] = Body(...)) -> Dict[str, Any]:
|
277 |
+
context = payload.get("context")
|
278 |
+
if not context or not isinstance(context, str):
|
279 |
+
raise HTTPException(status_code=400, detail="Campo 'context' é obrigatório e deve ser uma string.")
|
280 |
+
|
281 |
+
if len(context.strip()) == 0:
|
282 |
+
raise HTTPException(status_code=400, detail="Campo 'context' não pode estar vazio.")
|
283 |
+
|
284 |
+
# Gera os termos de pesquisa usando o Gemini
|
285 |
+
terms = await generate_search_terms(context)
|
286 |
+
|
287 |
+
if not terms:
|
288 |
+
raise HTTPException(status_code=500, detail="Não foi possível gerar termos de pesquisa válidos.")
|
289 |
|
290 |
used_urls = set()
|
291 |
search_semaphore = asyncio.Semaphore(20)
|
|
|
347 |
return {
|
348 |
"message": "Dados salvos em arquivo temporário",
|
349 |
"total_results": len(final_results),
|
350 |
+
"context": context,
|
351 |
+
"generated_terms": terms,
|
352 |
"file_info": temp_file_info
|
353 |
}
|
354 |
|
355 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
356 |
@router.get("/download-temp/{file_id}")
|
357 |
async def download_temp_file(file_id: str):
|
358 |
"""Endpoint para download do arquivo temporário"""
|
|
|
371 |
filename="fontes.txt",
|
372 |
media_type="text/plain",
|
373 |
headers={"Content-Disposition": "attachment; filename=fontes.txt"}
|
374 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|