-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquery_tools.py
More file actions
1314 lines (1142 loc) · 48.2 KB
/
query_tools.py
File metadata and controls
1314 lines (1142 loc) · 48.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Ferramentas de consulta especializadas para análise de posts do Instagram.
Estas ferramentas fornecem queries estruturadas que complementam o RAG semântico.
"""
from typing import List, Dict, Any, Optional
from datetime import datetime, timedelta
from dateutil import parser as date_parser
import json
import llm_chat
from config import DEFAULT_PROVIDER, DEEPSEEK_MODEL, OLLAMA_GENERATION_MODEL
try:
from ddgs import DDGS
DDGS_AVAILABLE = True
except ImportError:
DDGS_AVAILABLE = False
class QueryTools:
"""Ferramentas de consulta para análise estruturada de posts."""
def __init__(self, embedding_manager, llm_model: str = "qwen3:30b"):
"""
Inicializa as ferramentas com acesso ao banco de dados.
Args:
embedding_manager: Instância do EmbeddingManager com a coleção
llm_model: Modelo LLM para análise de sentimento
"""
self.collection = embedding_manager.collection
self.llm_model = llm_model
def get_top_posts_by_likes(
self,
limit: int = 10,
profile: Optional[str] = None,
min_date: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Retorna os posts com mais curtidas.
Args:
limit: Número de posts a retornar
profile: Filtrar por perfil específico (opcional)
min_date: Data mínima no formato ISO (opcional)
Returns:
Lista de posts ordenados por curtidas (decrescente)
"""
# Busca todos os posts (ou filtrados)
where = {}
if profile:
where['profile'] = profile
# ChromaDB não suporta ordenação nativa, então pegamos todos e ordenamos
results = self.collection.get(
where=where if where else None,
limit=10000 # Pega muitos para ordenar
)
# Converte para lista de dicts
posts = []
for i in range(len(results['ids'])):
metadata = results['metadatas'][i]
# Aplica filtro de data se especificado
if min_date:
try:
post_date = date_parser.parse(metadata['timestamp'])
min_date_obj = date_parser.parse(min_date)
if post_date < min_date_obj:
continue
except:
pass
posts.append({
'id': results['ids'][i],
'metadata': metadata,
'document': results['documents'][i]
})
# Ordena por curtidas (decrescente)
posts.sort(key=lambda x: x['metadata']['likesCount'], reverse=True)
return posts[:limit]
def get_top_posts_by_comments(
self,
limit: int = 10,
profile: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Retorna os posts com mais comentários.
Args:
limit: Número de posts a retornar
profile: Filtrar por perfil específico (opcional)
Returns:
Lista de posts ordenados por comentários (decrescente)
"""
where = {}
if profile:
where['profile'] = profile
results = self.collection.get(
where=where if where else None,
limit=10000
)
posts = []
for i in range(len(results['ids'])):
posts.append({
'id': results['ids'][i],
'metadata': results['metadatas'][i],
'document': results['documents'][i]
})
posts.sort(key=lambda x: x['metadata']['commentsCount'], reverse=True)
return posts[:limit]
def get_posts_by_engagement(
self,
limit: int = 10,
profile: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Retorna os posts com maior engajamento (curtidas + comentários).
Args:
limit: Número de posts a retornar
profile: Filtrar por perfil específico (opcional)
Returns:
Lista de posts ordenados por engajamento total
"""
where = {}
if profile:
where['profile'] = profile
results = self.collection.get(
where=where if where else None,
limit=10000
)
posts = []
for i in range(len(results['ids'])):
metadata = results['metadatas'][i]
engagement = metadata['likesCount'] + metadata['commentsCount']
posts.append({
'id': results['ids'][i],
'metadata': metadata,
'document': results['documents'][i],
'engagement': engagement
})
posts.sort(key=lambda x: x['engagement'], reverse=True)
return posts[:limit]
def get_bottom_posts_by_likes(
self,
limit: int = 10,
profile: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Retorna os posts com MENOS curtidas.
Args:
limit: Número de posts a retornar
profile: Filtrar por perfil específico (opcional)
Returns:
Lista de posts ordenados por curtidas (crescente)
"""
where = {}
if profile:
where['profile'] = profile
results = self.collection.get(
where=where if where else None,
limit=10000
)
posts = []
for i in range(len(results['ids'])):
posts.append({
'id': results['ids'][i],
'metadata': results['metadatas'][i],
'document': results['documents'][i]
})
# Ordena por curtidas (CRESCENTE - menos curtidas primeiro)
posts.sort(key=lambda x: x['metadata']['likesCount'], reverse=False)
return posts[:limit]
def get_bottom_posts_by_comments(
self,
limit: int = 10,
profile: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Retorna os posts com MENOS comentários.
Args:
limit: Número de posts a retornar
profile: Filtrar por perfil específico (opcional)
Returns:
Lista de posts ordenados por comentários (crescente)
"""
where = {}
if profile:
where['profile'] = profile
results = self.collection.get(
where=where if where else None,
limit=10000
)
posts = []
for i in range(len(results['ids'])):
posts.append({
'id': results['ids'][i],
'metadata': results['metadatas'][i],
'document': results['documents'][i]
})
# Ordena por comentários (CRESCENTE - menos comentários primeiro)
posts.sort(key=lambda x: x['metadata']['commentsCount'], reverse=False)
return posts[:limit]
def get_recent_posts(
self,
days: int = 30,
limit: int = 10,
profile: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Retorna os posts mais recentes.
Args:
days: Número de dias para considerar
limit: Número de posts a retornar
profile: Filtrar por perfil específico (opcional)
Returns:
Lista de posts recentes ordenados por data
"""
where = {}
if profile:
where['profile'] = profile
results = self.collection.get(
where=where if where else None,
limit=10000
)
# Cria cutoff_date com timezone UTC para comparação correta
from datetime import timezone
cutoff_date = datetime.now(timezone.utc) - timedelta(days=days)
posts = []
for i in range(len(results['ids'])):
metadata = results['metadatas'][i]
try:
post_date = date_parser.parse(metadata['timestamp'])
# Garante que post_date tem timezone para comparação
if post_date.tzinfo is None:
post_date = post_date.replace(tzinfo=timezone.utc)
if post_date >= cutoff_date:
posts.append({
'id': results['ids'][i],
'metadata': metadata,
'document': results['documents'][i],
'date': post_date
})
except:
continue
posts.sort(key=lambda x: x['date'], reverse=True)
return posts[:limit]
def get_posts_with_keyword(
self,
keyword: str,
limit: int = 10,
profile: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Busca posts que contenham uma palavra-chave específica.
Args:
keyword: Palavra-chave a buscar
limit: Número de posts a retornar
profile: Filtrar por perfil específico (opcional)
Returns:
Lista de posts que contém a palavra-chave
"""
where = {}
if profile:
where['profile'] = profile
results = self.collection.get(
where=where if where else None,
limit=10000
)
keyword_lower = keyword.lower()
posts = []
for i in range(len(results['ids'])):
doc = results['documents'][i].lower()
caption = results['metadatas'][i].get('caption', '').lower()
if keyword_lower in doc or keyword_lower in caption:
posts.append({
'id': results['ids'][i],
'metadata': results['metadatas'][i],
'document': results['documents'][i]
})
return posts[:limit]
def get_profile_statistics(
self,
profile: Optional[str] = None
) -> Dict[str, Any]:
"""
Retorna estatísticas agregadas de um perfil.
Args:
profile: Nome do perfil (se None, retorna de todos)
Returns:
Dicionário com estatísticas
"""
where = {}
if profile:
where['profile'] = profile
results = self.collection.get(
where=where if where else None,
limit=10000
)
if not results['ids']:
return {'error': 'Nenhum post encontrado'}
total_posts = len(results['ids'])
total_likes = sum(m['likesCount'] for m in results['metadatas'])
total_comments = sum(m['commentsCount'] for m in results['metadatas'])
# Calcula médias
avg_likes = total_likes / total_posts if total_posts > 0 else 0
avg_comments = total_comments / total_posts if total_posts > 0 else 0
# Encontra post com mais engajamento
posts_with_engagement = []
for i in range(len(results['ids'])):
metadata = results['metadatas'][i]
engagement = metadata['likesCount'] + metadata['commentsCount']
posts_with_engagement.append({
'url': metadata['url'],
'engagement': engagement,
'likes': metadata['likesCount'],
'comments': metadata['commentsCount']
})
posts_with_engagement.sort(key=lambda x: x['engagement'], reverse=True)
top_post = posts_with_engagement[0] if posts_with_engagement else None
return {
'profile': profile or 'todos',
'total_posts': total_posts,
'total_likes': total_likes,
'total_comments': total_comments,
'avg_likes_per_post': round(avg_likes, 2),
'avg_comments_per_post': round(avg_comments, 2),
'total_engagement': total_likes + total_comments,
'top_post': top_post
}
def compare_profiles(self) -> Dict[str, Any]:
"""
Compara estatísticas entre todos os perfis disponíveis.
Returns:
Dicionário com comparação entre perfis
"""
results = self.collection.get(limit=10000)
profiles = {}
for i in range(len(results['ids'])):
metadata = results['metadatas'][i]
profile = metadata['profile']
if profile not in profiles:
profiles[profile] = {
'posts': 0,
'likes': 0,
'comments': 0
}
profiles[profile]['posts'] += 1
profiles[profile]['likes'] += metadata['likesCount']
profiles[profile]['comments'] += metadata['commentsCount']
# Calcula médias
comparison = {}
for profile, stats in profiles.items():
comparison[profile] = {
'total_posts': stats['posts'],
'total_likes': stats['likes'],
'total_comments': stats['comments'],
'avg_likes': round(stats['likes'] / stats['posts'], 2),
'avg_comments': round(stats['comments'] / stats['posts'], 2),
'total_engagement': stats['likes'] + stats['comments']
}
return comparison
def count_term_occurrences(
self,
term: str,
profile: Optional[str] = None,
case_sensitive: bool = False
) -> Dict[str, Any]:
"""
Quantifica quantos posts mencionam um termo específico.
Diferente da busca semântica que retorna os posts MAIS relevantes,
esta ferramenta conta TODOS os posts que mencionam o termo.
Args:
term: Termo a buscar (pode ser palavra ou frase)
profile: Perfil específico ou None para todos
case_sensitive: Se True, considera maiúsculas/minúsculas
Returns:
Dict com:
- count: Número de posts que mencionam o termo
- percentage: Porcentagem do total de posts
- total_posts: Total de posts analisados
- matching_posts: Lista de posts que mencionam o termo
"""
try:
# Prepara filtro de perfil
where_filter = {"profile": profile} if profile else None
# Busca TODOS os posts (limite alto)
results = self.collection.get(
where=where_filter,
limit=10000, # Consulta toda a base
include=["documents", "metadatas"]
)
total_posts = len(results['documents'])
# Normaliza o termo de busca
search_term = term if case_sensitive else term.lower()
# Filtra posts que contêm o termo
matching_posts = []
for i, doc in enumerate(results['documents']):
# Texto completo do post
text = doc if case_sensitive else doc.lower()
# Verifica se o termo aparece no texto
if search_term in text:
metadata = results['metadatas'][i]
matching_posts.append({
'document': results['documents'][i],
'metadata': metadata
})
count = len(matching_posts)
percentage = (count / total_posts * 100) if total_posts > 0 else 0
return {
'count': count,
'percentage': round(percentage, 2),
'total_posts': total_posts,
'term': term,
'profile': profile or 'todos os perfis',
'matching_posts': matching_posts
}
except Exception as e:
print(f"❌ Erro ao contar ocorrências: {str(e)}")
return {
'count': 0,
'percentage': 0.0,
'total_posts': 0,
'term': term,
'profile': profile or 'todos os perfis',
'matching_posts': [],
'error': str(e)
}
def analyze_sentiment(
self,
topic: str,
profile: Optional[str] = None,
n_posts: int = 20
) -> Dict[str, Any]:
"""
Analisa o sentimento de posts sobre um tópico específico usando LLM.
Args:
topic: Tópico ou entidade a analisar (ex: "reitor", "greve", "HUAP")
profile: Perfil específico ou None para todos
n_posts: Número de posts a analisar (padrão: 20)
Returns:
Dict com:
- topic: Tópico analisado
- profile: Perfil(s) analisado(s)
- total_posts: Total de posts analisados
- sentiment_summary: Resumo geral do sentimento
- positive_count: Número de posts positivos
- negative_count: Número de posts negativos
- neutral_count: Número de posts neutros
- key_points: Pontos-chave identificados
- examples: Exemplos de posts por sentimento
"""
try:
# Busca posts relacionados ao tópico
where_filter = {"profile": profile} if profile else None
results = self.collection.get(
where=where_filter,
limit=10000,
include=["documents", "metadatas"]
)
# Filtra posts que mencionam o tópico (case-insensitive)
topic_lower = topic.lower()
relevant_posts = []
for i, doc in enumerate(results['documents']):
if topic_lower in doc.lower():
relevant_posts.append({
'document': doc,
'metadata': results['metadatas'][i]
})
if not relevant_posts:
return {
'topic': topic,
'profile': profile or 'todos os perfis',
'total_posts': 0,
'sentiment_summary': f"Nenhum post encontrado sobre '{topic}'",
'positive_count': 0,
'negative_count': 0,
'neutral_count': 0,
'key_points': [],
'examples': {'positive': [], 'negative': [], 'neutral': []}
}
# Limita ao número solicitado
posts_to_analyze = relevant_posts[:n_posts]
# Prepara contexto para o LLM
posts_text = "\n\n".join([
f"Post {i+1} (@{p['metadata']['profile']}):\n{p['document'][:500]}"
for i, p in enumerate(posts_to_analyze)
])
# Prompt para análise de sentimento
prompt = f"""Analise o sentimento dos posts abaixo sobre o tópico "{topic}".
POSTS:
{posts_text}
Forneça uma análise estruturada em formato JSON com:
1. sentiment_summary: Resumo geral do sentimento (2-3 frases)
2. positive_count: Número de posts com tom positivo/favorável
3. negative_count: Número de posts com tom negativo/crítico
4. neutral_count: Número de posts com tom neutro/informativo
5. key_points: Lista de 3-5 pontos-chave sobre como o tópico é abordado
6. positive_aspects: Lista de aspectos positivos mencionados
7. negative_aspects: Lista de aspectos negativos/críticas mencionadas
Retorne APENAS o JSON, sem texto adicional."""
# Chama o LLM com suporte a provider (DeepSeek ou Ollama)
if DEFAULT_PROVIDER == 'deepseek':
model_to_use = DEEPSEEK_MODEL
else:
model_to_use = self.llm_model
response = llm_chat.chat(
model=model_to_use,
messages=[{
'role': 'user',
'content': prompt
}]
)
# Parse da resposta
try:
# Extrai JSON da resposta
response_text = response['message']['content']
# Remove markdown se presente
if '```json' in response_text:
response_text = response_text.split('```json')[1].split('```')[0]
elif '```' in response_text:
response_text = response_text.split('```')[1].split('```')[0]
analysis = json.loads(response_text.strip())
# Categoriza posts em exemplos
examples = {
'positive': [],
'negative': [],
'neutral': []
}
# Seleciona exemplos (simplificado - usa os primeiros de cada categoria)
positive_needed = min(analysis.get('positive_count', 0), 2)
negative_needed = min(analysis.get('negative_count', 0), 2)
neutral_needed = min(analysis.get('neutral_count', 0), 2)
for post in posts_to_analyze[:6]: # Analisa até 6 posts como exemplos
if len(examples['positive']) < positive_needed:
examples['positive'].append(post)
elif len(examples['negative']) < negative_needed:
examples['negative'].append(post)
elif len(examples['neutral']) < neutral_needed:
examples['neutral'].append(post)
return {
'topic': topic,
'profile': profile or 'todos os perfis',
'total_posts': len(posts_to_analyze),
'total_relevant': len(relevant_posts),
'sentiment_summary': analysis.get('sentiment_summary', ''),
'positive_count': analysis.get('positive_count', 0),
'negative_count': analysis.get('negative_count', 0),
'neutral_count': analysis.get('neutral_count', 0),
'key_points': analysis.get('key_points', []),
'positive_aspects': analysis.get('positive_aspects', []),
'negative_aspects': analysis.get('negative_aspects', []),
'examples': examples
}
except json.JSONDecodeError as e:
print(f"⚠️ Erro ao parsear JSON do LLM: {e}")
print(f"Resposta: {response_text[:500]}")
# Fallback: retorna análise básica
return {
'topic': topic,
'profile': profile or 'todos os perfis',
'total_posts': len(posts_to_analyze),
'total_relevant': len(relevant_posts),
'sentiment_summary': f"Analisados {len(posts_to_analyze)} posts sobre '{topic}'. Análise detalhada não disponível.",
'positive_count': 0,
'negative_count': 0,
'neutral_count': len(posts_to_analyze),
'key_points': [f"{len(relevant_posts)} posts mencionam '{topic}'"],
'positive_aspects': [],
'negative_aspects': [],
'examples': {'positive': posts_to_analyze[:2], 'negative': [], 'neutral': []},
'error': 'LLM response parsing failed'
}
except Exception as e:
print(f"❌ Erro na análise de sentimento: {str(e)}")
return {
'topic': topic,
'profile': profile or 'todos os perfis',
'total_posts': 0,
'sentiment_summary': f"Erro ao analisar sentimento: {str(e)}",
'positive_count': 0,
'negative_count': 0,
'neutral_count': 0,
'key_points': [],
'positive_aspects': [],
'negative_aspects': [],
'examples': {'positive': [], 'negative': [], 'neutral': []},
'error': str(e)
}
def get_news_articles(
self,
limit: int = 10,
min_date: Optional[str] = None,
max_date: Optional[str] = None,
publisher: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Retorna notícias filtradas por data e/ou publisher.
Args:
limit: Número de notícias a retornar
min_date: Data mínima no formato ISO (opcional)
max_date: Data máxima no formato ISO (opcional)
publisher: Nome do publisher para filtrar (opcional)
Returns:
Lista de notícias ordenadas por data (mais recentes primeiro)
"""
# Busca apenas notícias
where = {'content_type': 'news'}
results = self.collection.get(
where=where,
limit=10000
)
news_articles = []
for i in range(len(results['ids'])):
metadata = results['metadatas'][i]
# Aplica filtros de data
try:
news_date = date_parser.parse(metadata['timestamp'])
if min_date:
min_date_obj = date_parser.parse(min_date)
if news_date < min_date_obj:
continue
if max_date:
max_date_obj = date_parser.parse(max_date)
if news_date > max_date_obj:
continue
except:
pass
# Aplica filtro de publisher
if publisher and publisher.lower() not in metadata.get('publisher_name', '').lower():
continue
news_articles.append({
'id': results['ids'][i],
'metadata': metadata,
'document': results['documents'][i]
})
# Ordena por data (mais recentes primeiro)
news_articles.sort(
key=lambda x: date_parser.parse(x['metadata']['timestamp']),
reverse=True
)
return news_articles[:limit]
def search_news_by_person(
self,
person_name: str,
limit: int = 10
) -> List[Dict[str, Any]]:
"""
Busca notícias que mencionam uma pessoa específica (ex: Roberto Salles).
Args:
person_name: Nome da pessoa a buscar
limit: Número de notícias a retornar
Returns:
Lista de notícias que mencionam a pessoa
"""
# Busca apenas notícias
where = {'content_type': 'news'}
results = self.collection.get(
where=where,
limit=10000
)
# Filtra notícias que mencionam a pessoa
relevant_news = []
person_name_lower = person_name.lower()
# Variações comuns de nomes (ex: Salles vs Sales)
name_variations = [person_name_lower]
if 'salles' in person_name_lower:
name_variations.append(person_name_lower.replace('salles', 'sales'))
elif 'sales' in person_name_lower:
name_variations.append(person_name_lower.replace('sales', 'salles'))
for i in range(len(results['ids'])):
document = results['documents'][i].lower()
metadata = results['metadatas'][i]
# Verifica se QUALQUER variação do nome completo aparece no documento
# Procura o nome completo, não apenas partes separadas
if any(variation in document for variation in name_variations):
relevant_news.append({
'id': results['ids'][i],
'metadata': metadata,
'document': results['documents'][i]
})
# Ordena por data (mais antigas primeiro para contexto histórico)
relevant_news.sort(
key=lambda x: date_parser.parse(x['metadata']['timestamp']),
reverse=False # Histórico: mais antigas primeiro
)
return relevant_news[:limit]
def get_news_statistics(self) -> Dict[str, Any]:
"""
Retorna estatísticas sobre as notícias indexadas.
Returns:
Dicionário com estatísticas
"""
# Busca todas as notícias
where = {'content_type': 'news'}
results = self.collection.get(
where=where,
limit=10000
)
if not results['ids']:
return {
'total_news': 0,
'publishers': [],
'date_range': {'oldest': None, 'newest': None},
'error': 'Nenhuma notícia encontrada'
}
# Coleta estatísticas
publishers = {}
dates = []
for metadata in results['metadatas']:
# Contagem por publisher
pub = metadata.get('publisher_name', 'Desconhecido')
publishers[pub] = publishers.get(pub, 0) + 1
# Coleta datas
try:
dates.append(date_parser.parse(metadata['timestamp']))
except:
pass
return {
'total_news': len(results['ids']),
'publishers': [{'name': k, 'count': v} for k, v in sorted(publishers.items(), key=lambda x: x[1], reverse=True)],
'date_range': {
'oldest': min(dates).isoformat() if dates else None,
'newest': max(dates).isoformat() if dates else None
}
}
def web_search(
self,
query: str,
limit: int = 5,
timeout: int = 10
) -> List[Dict[str, Any]]:
"""
Busca na internet usando DuckDuckGo para contexto externo.
Útil quando o agente precisa de informações atuais ou contexto
que não está nos registros locais da UFF.
Args:
query: Termo de busca
limit: Número de resultados (padrão: 5)
timeout: Timeout em segundos
Returns:
Lista com resultados da busca contendo:
- title: Título do resultado
- body: Texto resumido do resultado
- source: URL da fonte
- date: Data (se disponível)
- profile: 'web_search' (para compatibilidade com outras ferramentas)
"""
if not DDGS_AVAILABLE:
return [{
'title': 'Web search indisponível',
'body': 'Módulo duckduckgo-search não está instalado',
'source': 'local',
'date': None,
'profile': 'web_search'
}]
try:
results = []
filtered_count = 0
# Busca com DuckDuckGo
try:
with DDGS(timeout=timeout) as ddgs:
search_results = ddgs.text(
query, # Novo ddgs: query como posicional
max_results=limit * 2, # Busca mais para compensar filtros
region='br-pt' # Região Brasil
)
for result in search_results:
if len(results) >= limit:
break
# Filtra resultados muito genéricos/inúteis
title = result.get('title', '').lower()
body = result.get('body', '').lower()
href = result.get('href', '')
# Rejeita apenas os muito óbviamente inúteis
reject_patterns = [
'wikipedia.org', # Wikipedia (muito genérico)
'dicionario', 'significado', 'sinônimo', # Dicionários
'pinterest', 'instagram.com', 'facebook.com', # Redes sociais
]
# Verifica se deve rejeitar
should_reject = False
for pattern in reject_patterns:
if pattern in href.lower() or pattern in title:
should_reject = True
filtered_count += 1
break
if should_reject:
continue
# Também rejeita se o body é muito curto
if len(body.strip()) < 50:
filtered_count += 1
continue
results.append({
'title': result.get('title', 'Sem título'),
'body': result.get('body', ''),
'source': result.get('href', ''),
'date': result.get('date', None),
'profile': 'web_search' # Compatibilidade com outras ferramentas
})
except Exception as search_error:
print(f"⚠️ Erro na busca DuckDuckGo: {search_error}")
# Retorna mensagem de erro sem quebrar
return [{
'title': 'Erro ao buscar na internet',
'body': f'Não foi possível conectar ao DuckDuckGo. Tente novamente mais tarde.',
'source': 'web',
'date': None,
'profile': 'web_search'
}]
# Se conseguiu resultados após filtros, retorna
if results:
print(f"✅ Web search: {len(results)} resultado(s) encontrado(s) (filtrados: {filtered_count})")
return results
else:
# Se nenhum resultado passou pelo filtro, retorna sem filtro rigoroso
print(f"⚠️ Web search: Todos os {filtered_count} resultado(s) foram filtrados, tentando novamente sem filtro...")
try:
with DDGS(timeout=timeout) as ddgs:
search_results = ddgs.text(
query, # Novo ddgs: query como posicional
max_results=3,
region='br-pt'
)
# Retorna sem filtro rigoroso
for result in search_results:
results.append({
'title': result.get('title', 'Sem título'),
'body': result.get('body', ''),
'source': result.get('href', ''),
'date': result.get('date', None),
'profile': 'web_search'
})
if results:
return results
except:
pass
# Se ainda assim não retornar nada, retorna mensagem
return [{
'title': 'Nenhum resultado encontrado',
'body': f'Infelizmente, a busca por "{query}" não retornou resultados na internet. Tente com termos diferentes.',
'source': 'web',
'date': None,
'profile': 'web_search'
}]
except Exception as e:
return [{
'title': 'Erro ao buscar na web',
'body': f'Erro: {str(e)}. Tente novamente mais tarde.',
'source': 'error',