-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathREADME.typ
More file actions
1208 lines (1027 loc) · 35.4 KB
/
README.typ
File metadata and controls
1208 lines (1027 loc) · 35.4 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
// Some definitions presupposed by pandoc's typst output.
#let blockquote(body) = [
#set text( size: 0.92em )
#block(inset: (left: 1.5em, top: 0.2em, bottom: 0.2em))[#body]
]
#let horizontalrule = line(start: (25%,0%), end: (75%,0%))
#let endnote(num, contents) = [
#stack(dir: ltr, spacing: 3pt, super[#num], contents)
]
#show terms: it => {
it.children
.map(child => [
#strong[#child.term]
#block(inset: (left: 1.5em, top: -0.4em))[#child.description]
])
.join()
}
// Some quarto-specific definitions.
#show raw.where(block: true): set block(
fill: luma(230),
width: 100%,
inset: 8pt,
radius: 2pt
)
#let block_with_new_content(old_block, new_content) = {
let d = (:)
let fields = old_block.fields()
fields.remove("body")
if fields.at("below", default: none) != none {
// TODO: this is a hack because below is a "synthesized element"
// according to the experts in the typst discord...
fields.below = fields.below.abs
}
return block.with(..fields)(new_content)
}
#let empty(v) = {
if type(v) == str {
// two dollar signs here because we're technically inside
// a Pandoc template :grimace:
v.matches(regex("^\\s*$")).at(0, default: none) != none
} else if type(v) == content {
if v.at("text", default: none) != none {
return empty(v.text)
}
for child in v.at("children", default: ()) {
if not empty(child) {
return false
}
}
return true
}
}
// Subfloats
// This is a technique that we adapted from https://github.com/tingerrr/subpar/
#let quartosubfloatcounter = counter("quartosubfloatcounter")
#let quarto_super(
kind: str,
caption: none,
label: none,
supplement: str,
position: none,
subrefnumbering: "1a",
subcapnumbering: "(a)",
body,
) = {
context {
let figcounter = counter(figure.where(kind: kind))
let n-super = figcounter.get().first() + 1
set figure.caption(position: position)
[#figure(
kind: kind,
supplement: supplement,
caption: caption,
{
show figure.where(kind: kind): set figure(numbering: _ => numbering(subrefnumbering, n-super, quartosubfloatcounter.get().first() + 1))
show figure.where(kind: kind): set figure.caption(position: position)
show figure: it => {
let num = numbering(subcapnumbering, n-super, quartosubfloatcounter.get().first() + 1)
show figure.caption: it => {
num.slice(2) // I don't understand why the numbering contains output that it really shouldn't, but this fixes it shrug?
[ ]
it.body
}
quartosubfloatcounter.step()
it
counter(figure.where(kind: it.kind)).update(n => n - 1)
}
quartosubfloatcounter.update(0)
body
}
)#label]
}
}
// callout rendering
// this is a figure show rule because callouts are crossreferenceable
#show figure: it => {
if type(it.kind) != str {
return it
}
let kind_match = it.kind.matches(regex("^quarto-callout-(.*)")).at(0, default: none)
if kind_match == none {
return it
}
let kind = kind_match.captures.at(0, default: "other")
kind = upper(kind.first()) + kind.slice(1)
// now we pull apart the callout and reassemble it with the crossref name and counter
// when we cleanup pandoc's emitted code to avoid spaces this will have to change
let old_callout = it.body.children.at(1).body.children.at(1)
let old_title_block = old_callout.body.children.at(0)
let old_title = old_title_block.body.body.children.at(2)
// TODO use custom separator if available
let new_title = if empty(old_title) {
[#kind #it.counter.display()]
} else {
[#kind #it.counter.display(): #old_title]
}
let new_title_block = block_with_new_content(
old_title_block,
block_with_new_content(
old_title_block.body,
old_title_block.body.body.children.at(0) +
old_title_block.body.body.children.at(1) +
new_title))
block_with_new_content(old_callout,
block(below: 0pt, new_title_block) +
old_callout.body.children.at(1))
}
// 2023-10-09: #fa-icon("fa-info") is not working, so we'll eval "#fa-info()" instead
#let callout(body: [], title: "Callout", background_color: rgb("#dddddd"), icon: none, icon_color: black, body_background_color: white) = {
block(
breakable: false,
fill: background_color,
stroke: (paint: icon_color, thickness: 0.5pt, cap: "round"),
width: 100%,
radius: 2pt,
block(
inset: 1pt,
width: 100%,
below: 0pt,
block(
fill: background_color,
width: 100%,
inset: 8pt)[#text(icon_color, weight: 900)[#icon] #title]) +
if(body != []){
block(
inset: 1pt,
width: 100%,
block(fill: body_background_color, width: 100%, inset: 8pt, body))
}
)
}
#let article(
title: none,
subtitle: none,
authors: none,
date: none,
abstract: none,
abstract-title: none,
cols: 1,
lang: "en",
region: "US",
font: "libertinus serif",
fontsize: 11pt,
title-size: 1.5em,
subtitle-size: 1.25em,
heading-family: "libertinus serif",
heading-weight: "bold",
heading-style: "normal",
heading-color: black,
heading-line-height: 0.65em,
sectionnumbering: none,
toc: false,
toc_title: none,
toc_depth: none,
toc_indent: 1.5em,
doc,
) = {
set par(justify: true)
set text(lang: lang,
region: region,
font: font,
size: fontsize)
set heading(numbering: sectionnumbering)
if title != none {
align(center)[#block(inset: 2em)[
#set par(leading: heading-line-height)
#if (heading-family != none or heading-weight != "bold" or heading-style != "normal"
or heading-color != black) {
set text(font: heading-family, weight: heading-weight, style: heading-style, fill: heading-color)
text(size: title-size)[#title]
if subtitle != none {
parbreak()
text(size: subtitle-size)[#subtitle]
}
} else {
text(weight: "bold", size: title-size)[#title]
if subtitle != none {
parbreak()
text(weight: "bold", size: subtitle-size)[#subtitle]
}
}
]]
}
if authors != none {
let count = authors.len()
let ncols = calc.min(count, 3)
grid(
columns: (1fr,) * ncols,
row-gutter: 1.5em,
..authors.map(author =>
align(center)[
#author.name \
#author.affiliation \
#author.email
]
)
)
}
if date != none {
align(center)[#block(inset: 1em)[
#date
]]
}
if abstract != none {
block(inset: 2em)[
#text(weight: "semibold")[#abstract-title] #h(1em) #abstract
]
}
if toc {
let title = if toc_title == none {
auto
} else {
toc_title
}
block(above: 0em, below: 2em)[
#outline(
title: toc_title,
depth: toc_depth,
indent: toc_indent
);
]
}
if cols == 1 {
doc
} else {
columns(cols, doc)
}
}
#set table(
inset: 6pt,
stroke: none
)
#set page(
paper: "us-letter",
margin: (x: 1.25in, y: 1.25in),
numbering: "1",
)
#show: doc => article(
toc_title: [Table of contents],
toc_depth: 3,
cols: 1,
doc,
)
= 📱 UFF Instagram Analytics - Sistema RAG Inteligente
<uff-instagram-analytics---sistema-rag-inteligente>
#quote(block: true)[
Sistema de análise semântica e análise de sentimento para posts do Instagram dos perfis institucionais da UFF (Universidade Federal Fluminense) usando IA local.
]
#block[
#box(image("README_files/mediabag/Python-3.12--blue.svg")) #box(image("README_files/mediabag/Ollama-Local-AI-gree.svg")) #box(image("README_files/mediabag/ChromaDB-Vector-DB-o.svg")) #box(image("README_files/mediabag/Gradio-4.0--red.svg"))
#strong[#link(<-início-rápido>)[Início Rápido];] • #strong[#link(<-funcionalidades>)[Funcionalidades];] • #strong[#link(<-arquitetura>)[Arquitetura];] • #strong[#link(<-documentação-completa>)[Documentação];]
]
#horizontalrule
== 📋 Índice
<índice>
- #link(<-visão-geral>)[Visão Geral]
- #link(<-funcionalidades>)[Funcionalidades]
- #link(<-arquitetura-do-sistema>)[Arquitetura do Sistema]
- #link(<-início-rápido>)[Início Rápido]
- #link(<-configuração>)[Configuração]
- #link(<-uso-da-interface>)[Uso da Interface]
- #link(<-ferramentas-disponíveis>)[Ferramentas Disponíveis]
- #link(<-api-rest>)[API REST]
- #link(<-documentação-completa>)[Documentação Completa]
- #link(<-solução-de-problemas>)[Solução de Problemas]
#horizontalrule
== 🎯 Visão Geral
<visão-geral>
O #strong[UFF Instagram Analytics] é um sistema completo de análise de posts do Instagram que combina:
- 🤖 #strong[Agente Inteligente] - LLM decide automaticamente quais ferramentas usar
- 🔍 #strong[Busca Semântica] - Encontre posts por significado, não apenas palavras-chave
- 📊 #strong[Análise Quantitativa] - Estatísticas de engajamento, ranking, comparações
- 🎭 #strong[Análise de Sentimento] - Compreenda percepções e opiniões automaticamente
- 💬 #strong[Interface de Chat] - Pergunte em linguagem natural
- 🌐 #strong[100% Local] - Privacidade total, sem enviar dados para APIs externas
=== Base de Dados Atual
<base-de-dados-atual>
- #strong[2.413 posts] indexados
- #strong[3 perfis] oficiais da UFF:
- `@dceuff` (Diretório Central dos Estudantes) - 1.503 posts
- `@reitor` (Reitoria da UFF) - 575 posts
- `@vicereitor` (Vice-Reitoria da UFF) - 335 posts
#horizontalrule
== ✨ Funcionalidades
<funcionalidades>
=== 🎯 Sistema de Agente Inteligente
<sistema-de-agente-inteligente>
O sistema usa um #strong[agente autônomo] que: 1. 📋 #strong[Analisa] sua pergunta em linguagem natural 2. 🧠 #strong[Decide] automaticamente quais ferramentas usar 3. ⚙️ #strong[Executa] as ferramentas necessárias (uma ou múltiplas) 4. 🎨 #strong[Sintetiza] uma resposta clara e completa
#strong[Exemplo:]
```
Você: "Como o reitor é visto pelos estudantes?"
Agente:
1. Detecta: pergunta de sentimento
2. Usa: analyze_sentiment(topic="reitor", profile="dceuff")
3. Retorna: Análise completa com positivo/negativo, críticas, elogios
```
=== 🛠️ 9 Ferramentas Especializadas
<ferramentas-especializadas>
#table(
columns: (10.71%, 39.29%, 17.86%, 32.14%),
align: (auto,auto,auto,auto,),
table.header([\#], [Ferramenta], [Uso], [Exemplo],),
table.hline(),
[1], [`get_top_posts_by_likes`], [Posts mais curtidos], ["Post mais curtido do reitor"],
[2], [`get_top_posts_by_comments`], [Posts mais comentados], ["Top 5 com mais comentários"],
[3], [`get_posts_by_engagement`], [Maior engajamento total], ["Posts com maior interação"],
[4], [`get_recent_posts`], [Publicações recentes], ["Posts dos últimos 7 dias"],
[5], [`get_profile_statistics`], [Estatísticas agregadas], ["Estatísticas do DCE"],
[6], [`compare_profiles`], [Comparação entre perfis], ["Compare os 3 perfis"],
[7], [`count_term_occurrences`], [Contagem de menções], ["Quantos posts falam de greve?"],
[8], [`analyze_sentiment`], [Análise de sentimento (IA)], ["Como o HUAP é visto?"],
[9], [`semantic_search`], [Busca por conteúdo], ["Posts sobre saúde"],
)
=== 🎭 Análise de Sentimento com IA
<análise-de-sentimento-com-ia>
Ferramenta única que usa LLM para analisar percepção e opiniões:
```
Entrada: "Como o reitor é visto pelos estudantes?"
Saída:
✅ 5 posts positivos (25%)
❌ 12 posts negativos (60%)
⚪ 3 posts neutros (15%)
Aspectos Positivos:
- Gestão transparente
- Diálogo com comunidade
Aspectos Negativos:
- Demora em decisões
- Falta de comunicação clara
+ Resumo narrativo completo
+ Exemplos de posts de cada categoria
```
#horizontalrule
== 🏗️ Arquitetura do Sistema
<arquitetura-do-sistema>
=== Visão Geral
<visão-geral-1>
```
┌─────────────────────────────────────────────────────────────┐
│ INTERFACE GRADIO │
│ (Chat + Filtros + Visualizações) │
└────────────────────────┬────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ AGENTE RAG (LLM) │
│ ┌─────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ Planejamento│→ │ Execução │→ │ Síntese │ │
│ │ (qwen3:30b)│ │ (Ferramentas)│ │ (qwen3:30b) │ │
│ └─────────────┘ └──────────────┘ └──────────────┘ │
└────────────────────────┬────────────────────────────────────┘
│
┌───────────────┼───────────────┐
│ │ │
▼ ▼ ▼
┌────────────────┐ ┌──────────┐ ┌──────────────┐
│ ChromaDB │ │ Análise │ │ Estatísticas │
│ (Embeddings) │ │Sentimento│ │ Agregadas │
│ 2.413 posts │ │ (LLM) │ │ (Python) │
└────────────────┘ └──────────┘ └──────────────┘
│
▼
┌─────────────────────────────────────────────┐
│ DADOS BRUTOS (JSON) │
│ dceuff.json | reitor.json | vicereitor.json│
└─────────────────────────────────────────────┘
```
=== Componentes Principais
<componentes-principais>
==== 1. #strong[Interface (app.py)]
<interface-app.py>
- Interface web com Gradio 4.0+
- Chat interativo com histórico
- Filtros por perfil
- Exibição de resultados (cards, gráficos, estatísticas)
- Avatar customizado do agente
==== 2. #strong[Agente RAG (agent\_system.py)]
<agente-rag-agent_system.py>
- #strong[Planejamento];: LLM analisa a pergunta e decide quais ferramentas usar
- #strong[Execução];: Roda as ferramentas escolhidas (pode ser múltiplas)
- #strong[Síntese];: LLM combina resultados em resposta coerente
==== 3. #strong[Ferramentas (query\_tools.py)]
<ferramentas-query_tools.py>
- 9 ferramentas especializadas
- Queries estruturadas no ChromaDB
- Análise de sentimento com LLM
- Estatísticas calculadas em Python
==== 4. #strong[Embeddings (embedding\_manager.py)]
<embeddings-embedding_manager.py>
- Gerencia ChromaDB
- Modelo: `mxbai-embed-large` (669MB)
- Busca vetorial semântica
- Persistência em disco
==== 5. #strong[Dados (data\_loader.py)]
<dados-data_loader.py>
- Carrega posts de arquivos JSON
- Processa e limpa dados
- Extrai metadados (curtidas, comentários, data, etc.)
=== Fluxo de Uma Consulta
<fluxo-de-uma-consulta>
```mermaid
graph TD
A[Usuário faz pergunta] --> B[Agente: Planejamento]
B --> C{Qual ferramenta?}
C -->|Sentimento| D[analyze_sentiment]
C -->|Contagem| E[count_term_occurrences]
C -->|Ranking| F[get_top_posts]
C -->|Busca| G[semantic_search]
D --> H[Agente: Síntese]
E --> H
F --> H
G --> H
H --> I[Resposta formatada]
I --> J[Interface: Exibição]
```
#horizontalrule
== 🚀 Início Rápido
<início-rápido>
=== Pré-requisitos
<pré-requisitos>
- #strong[Python 3.12+]
- #strong[uv] (gerenciador de pacotes)
- #strong[Ollama] (para rodar LLMs localmente)
- #strong[8GB RAM] mínimo (16GB recomendado)
- #strong[20GB] de espaço em disco para modelos
=== Instalação em 3 Passos
<instalação-em-3-passos>
==== 1. Instalar Ollama
<instalar-ollama>
```bash
# Linux
curl -fsSL https://ollama.com/install.sh | sh
# macOS
brew install ollama
# Windows
# Baixe de https://ollama.com/download
```
==== 2. Configurar Projeto
<configurar-projeto>
```bash
# Navegue até o diretório
cd /home/marcus/projects/ping
# Sincronize dependências
uv sync
```
==== 3. Instalar Modelos
<instalar-modelos>
```bash
# Modelo de embeddings (OBRIGATÓRIO) - 669MB
ollama pull mxbai-embed-large
# Modelo de geração (escolha um):
# Opção 1: Leve - 2GB RAM
ollama pull qwen2.5:3b
# Opção 2: Balanceado - 7GB RAM (recomendado)
ollama pull qwen2.5:7b
# Opção 3: Melhor qualidade - 18GB RAM
ollama pull qwen3:30b # ← Modelo atual do sistema
```
=== Iniciar a Aplicação
<iniciar-a-aplicação>
```bash
# Modo padrão (porta 7860)
uv run python app.py
# Com modelo específico
uv run python app.py --generation-model qwen2.5:7b
# Criar link público
uv run python app.py --share
# Porta customizada
uv run python app.py --port 8080
```
Acesse: #strong[http:\/\/localhost:7860]
#horizontalrule
== ⚙️ Configuração
<configuração>
=== Argumentos de Linha de Comando
<argumentos-de-linha-de-comando>
```bash
--embedding-model TEXT # Modelo para embeddings
# Padrão: mxbai-embed-large
--generation-model TEXT # Modelo para geração de respostas
# Padrão: qwen3:30b
--port INTEGER # Porta da aplicação web
# Padrão: 7860
--share # Criar link público Gradio
# Padrão: False
```
=== Modelos Recomendados por Recurso
<modelos-recomendados-por-recurso>
#table(
columns: 5,
align: (auto,auto,auto,auto,auto,),
table.header([RAM Disponível], [Embedding], [Generation], [Qualidade], [Velocidade],),
table.hline(),
[8GB], [mxbai-embed-large], [qwen2.5:3b], [⭐⭐], [⚡⚡⚡],
[16GB], [mxbai-embed-large], [qwen2.5:7b], [⭐⭐⭐], [⚡⚡],
[32GB+], [mxbai-embed-large], [qwen3:30b], [⭐⭐⭐⭐⭐], [⚡],
)
=== Estrutura de Dados (JSON)
<estrutura-de-dados-json>
Os posts devem estar em `data/` no formato:
```json
[
{
"id": "3737403160894992541",
"type": "Video",
"caption": "Texto da legenda do post...",
"hashtags": ["uff", "universidade"],
"mentions": ["@perfil"],
"url": "https://www.instagram.com/p/ABC123/",
"commentsCount": 7,
"likesCount": 124,
"timestamp": "2025-10-06T14:58:54.000Z",
"latestComments": [
{
"text": "Ótima iniciativa!",
"ownerUsername": "usuario123"
}
]
}
]
```
#horizontalrule
== 💬 Uso da Interface
<uso-da-interface>
=== Painel Principal
<painel-principal>
```
┌─────────────────────────────────────────────────────────┐
│ 📱 UFF Instagram Analytics │
│ Faça perguntas sobre os 2.413 posts │
├─────────────────────────────────────────────────────────┤
│ │
│ 💬 CHAT │ ⚙️ CONFIGURAÇÕES │
│ ┌──────────────────┐ │ Filtrar por Perfil: │
│ │ Bot: Olá! │ │ [🌐 Todos os Perfis ▼] │
│ │ User: Quantos... │ │ │
│ └──────────────────┘ │ 📊 Estatísticas │
│ │ 💡 Exemplos │
│ [Digite sua pergunta...] │ 🏆 Post mais curtido │
│ [Enviar 🚀] │ 📊 Compare perfis │
│ │ 🔍 Posts sobre HUAP │
└──────────────────────────────┴──────────────────────────┘
```
=== Exemplos de Perguntas
<exemplos-de-perguntas>
==== 📊 Análise Quantitativa
<análise-quantitativa>
```
✅ "Quantos posts falam sobre greve?"
→ Usa: count_term_occurrences
→ Retorna: 42 posts (1.74%)
✅ "Qual foi o post mais curtido do reitor?"
→ Usa: get_top_posts_by_likes(profile="reitor", limit=1)
→ Retorna: Post com 1.234 curtidas + link
✅ "Compare o engajamento dos 3 perfis"
→ Usa: compare_profiles()
→ Retorna: Tabela comparativa completa
```
==== 🔍 Busca Semântica
<busca-semântica>
```
✅ "Posts sobre saúde e hospital"
→ Usa: semantic_search(query="saúde hospital HUAP atendimento")
→ Retorna: 10 posts mais relevantes
✅ "O que foi dito sobre a greve em 2024?"
→ Usa: semantic_search + filtro temporal
→ Retorna: Posts relevantes ordenados
✅ "Última aparição pública do reitor"
→ Usa: semantic_search(profile="reitor") + get_recent_posts
→ Retorna: Post mais recente relevante
```
==== 🎭 Análise de Sentimento
<análise-de-sentimento>
```
✅ "Como o reitor é visto pelos estudantes?"
→ Usa: analyze_sentiment(topic="reitor", profile="dceuff")
→ Retorna:
• 60% negativos, 25% positivos, 15% neutros
• Aspectos positivos: transparência, diálogo
• Críticas: demora, falta de comunicação
• Resumo narrativo + exemplos
✅ "Qual a percepção sobre o HUAP?"
→ Usa: analyze_sentiment(topic="HUAP")
→ Retorna: Análise completa de sentimento
✅ "O que pensam sobre a gestão?"
→ Usa: analyze_sentiment(topic="gestão")
→ Retorna: Opiniões e tendências identificadas
```
==== 📈 Estatísticas
<estatísticas>
```
✅ "Estatísticas do DCE"
→ Usa: get_profile_statistics(profile="dceuff")
→ Retorna:
• 1.503 posts
• 45.678 curtidas totais
• Média: 30.4 curtidas/post
• Post mais engajado
✅ "Posts da última semana"
→ Usa: get_recent_posts(days=7)
→ Retorna: Todos os posts recentes
✅ "Top 5 posts com mais comentários"
→ Usa: get_top_posts_by_comments(limit=5)
→ Retorna: Ranking com links
```
#horizontalrule
== 🛠️ Ferramentas Disponíveis
<ferramentas-disponíveis>
=== 1. get\_top\_posts\_by\_likes
<get_top_posts_by_likes>
#strong[Uso:] Encontrar posts mais curtidos \
#strong[Parâmetros:] - `limit` (int): Quantidade de posts - `profile` (str, opcional): Filtrar por perfil
#strong[Exemplo:]
```python
tools.get_top_posts_by_likes(limit=10, profile="reitor")
```
=== 2. get\_top\_posts\_by\_comments
<get_top_posts_by_comments>
#strong[Uso:] Posts com mais comentários \
#strong[Parâmetros:] - `limit` (int): Quantidade - `profile` (str, opcional): Perfil
=== 3. get\_posts\_by\_engagement
<get_posts_by_engagement>
#strong[Uso:] Maior engajamento (curtidas + comentários) \
#strong[Parâmetros:] - `limit` (int): Quantidade - `profile` (str, opcional): Perfil
=== 4. get\_recent\_posts
<get_recent_posts>
#strong[Uso:] Publicações recentes \
#strong[Parâmetros:] - `days` (int): Últimos N dias - `limit` (int): Quantidade - `profile` (str, opcional): Perfil
=== 5. get\_profile\_statistics
<get_profile_statistics>
#strong[Uso:] Estatísticas agregadas de um perfil \
#strong[Parâmetros:] - `profile` (str, opcional): Se vazio, retorna todos
#strong[Retorna:]
```json
{
"total_posts": 1503,
"total_likes": 45678,
"total_comments": 2341,
"avg_likes_per_post": 30.4,
"avg_comments_per_post": 1.6,
"total_engagement": 48019,
"top_post": {...}
}
```
=== 6. compare\_profiles
<compare_profiles>
#strong[Uso:] Comparar todos os perfis \
#strong[Sem parâmetros]
#strong[Retorna:]
```json
{
"dceuff": {
"total_posts": 1503,
"total_likes": 45678,
"avg_likes": 30.4,
...
},
"reitor": {...},
"vicereitor": {...}
}
```
=== 7. count\_term\_occurrences ⭐ NOVO
<count_term_occurrences-novo>
#strong[Uso:] Quantificar menções de um termo \
#strong[Parâmetros:] - `term` (str): Termo a buscar - `profile` (str, opcional): Perfil - `case_sensitive` (bool): Maiúsculas/minúsculas
#strong[Retorna:]
```json
{
"count": 42,
"percentage": 1.74,
"total_posts": 2413,
"term": "greve",
"matching_posts": [...]
}
```
#strong[Diferença de semantic\_search:] - `count_term_occurrences`: #strong[QUANTIFICA] (todos os posts) - `semantic_search`: #strong[QUALIFICA] (posts mais relevantes)
=== 8. analyze\_sentiment ⭐ NOVO - IA
<analyze_sentiment-novo---ia>
#strong[Uso:] Análise de sentimento com LLM \
#strong[Parâmetros:] - `topic` (str): Tópico/entidade - `profile` (str, opcional): Perfil - `n_posts` (int): Posts a analisar (padrão: 20)
#strong[Retorna:]
```json
{
"topic": "reitor",
"sentiment_summary": "Análise narrativa...",
"positive_count": 5,
"negative_count": 12,
"neutral_count": 3,
"positive_aspects": ["transparência", "diálogo"],
"negative_aspects": ["demora", "comunicação"],
"key_points": [...],
"examples": {
"positive": [...],
"negative": [...],
"neutral": [...]
}
}
```
#strong[Como funciona:] 1. Busca posts que mencionam o tópico 2. Seleciona até N posts para análise 3. LLM analisa e classifica cada post 4. Extrai aspectos positivos e negativos 5. Gera resumo qualitativo 6. Retorna estatísticas + exemplos
=== 9. semantic\_search
<semantic_search>
#strong[Uso:] Busca vetorial por conteúdo \
#strong[Parâmetros:] - `query` (str): Consulta semântica - `n_results` (int): Quantidade - `profile` (str, opcional): Perfil
#strong[Como funciona:] - Converte query em embedding - Busca posts similares no espaço vetorial - Retorna os N mais relevantes
#horizontalrule
== 🌐 API REST
<api-rest>
A aplicação Gradio expõe uma API REST automática.
=== Endpoint Principal
<endpoint-principal>
```
POST http://localhost:7860/api/predict
```
=== Fazer uma Pergunta
<fazer-uma-pergunta>
```bash
curl -X POST http://localhost:7860/api/predict \
-H "Content-Type: application/json" \
-d '{
"data": [
"Quantos posts falam de greve?",
[],
5,
"🌐 Todos os Perfis"
]
}'
```
#strong[Parâmetros (array `data`):] 1. Pergunta (string) 2. Histórico do chat (array, pode ser `[]`) 3. Número de resultados (int, ignorado no modo agente) 4. Filtro de perfil (string: "🌐 Todos os Perfis", "#cite(<dceuff>, form: "prose");", "#cite(<reitor>, form: "prose");", "#cite(<vicereitor>, form: "prose");")
=== Resposta
<resposta>
```json
{
"data": [
"", // Input vazio (limpo após envio)
[ // Histórico atualizado
[
"Quantos posts falam de greve?",
"Encontrados 42 posts (1.74%) que mencionam 'greve'..."
]
],
"<div>...</div>" // HTML dos posts recuperados
],
"duration": 2.34
}
```
=== Exemplo com Python
<exemplo-com-python>
```python
import requests
response = requests.post(
"http://localhost:7860/api/predict",
json={
"data": [
"Como o reitor é visto?",
[],
5,
"@dceuff"
]
}
)
result = response.json()
answer = result['data'][1][0][1] # Resposta do bot
print(answer)
```
#horizontalrule
== 📚 Documentação Completa
<documentação-completa>
=== Arquivos de Documentação
<arquivos-de-documentação>
Toda a documentação está consolidada aqui, mas arquivos individuais ainda existem:
#table(
columns: 2,
align: (auto,auto,),
table.header([Arquivo], [Conteúdo],),
table.hline(),
[`README.md`], [#strong[Este arquivo] - Documentação completa],
[`QUICKSTART.md`], [Guia rápido de início],
[`API_QUICKSTART.md`], [Exemplos de uso da API],
[`TOOLS.md`], [Detalhes de todas as ferramentas],
[`SENTIMENT_ANALYSIS_TOOL.md`], [Análise de sentimento (ferramenta \#8)],
[`TERM_COUNT_TOOL.md`], [Contagem de termos (ferramenta \#7)],
[`ARCHITECTURE.md`], [Arquitetura detalhada],
[`AGENT_VS_CLASSIC.md`], [Comparação agente vs sistema clássico],
[`BALANCED_AGENT.md`], [Como o agente equilibra ferramentas],
)
=== Estrutura de Arquivos
<estrutura-de-arquivos>
```
ping/
├── 📁 data/ # Dados dos posts (JSON)
│ ├── dceuff.json # 1.503 posts
│ ├── reitor.json # 575 posts
│ └── vicereitor.json # 335 posts
│
├── 📁 chroma_db/ # Banco vetorial (auto-gerado)
│ └── ... # Embeddings persistidos
│
├── 📁 assets/ # Assets da interface
│ └── agent_avatar.png # Avatar do agente
│
├── 🐍 CÓDIGO PRINCIPAL
│ ├── app.py # Interface Gradio
│ ├── agent_system.py # Sistema de agente RAG
│ ├── query_tools.py # 9 ferramentas especializadas
│ ├── embedding_manager.py # Gerenciador ChromaDB
│ ├── data_loader.py # Carregador de dados
│ └── rag_system.py # Sistema RAG clássico (legado)
│
├── 📄 CONFIGURAÇÃO
│ ├── pyproject.toml # Dependências (uv)
│ └── .python-version # Python 3.12+
│
├── 🧪 TESTES
│ ├── test_term_count.py # Teste de contagem
│ └── check_profiles.py # Debug de perfis
│
└── 📚 DOCUMENTAÇÃO
├── README.md # ← VOCÊ ESTÁ AQUI
├── QUICKSTART.md
├── API_QUICKSTART.md
├── TOOLS.md
├── SENTIMENT_ANALYSIS_TOOL.md
├── TERM_COUNT_TOOL.md
├── ARCHITECTURE.md
├── AGENT_VS_CLASSIC.md
└── BALANCED_AGENT.md
```
=== Tecnologias Utilizadas
<tecnologias-utilizadas>
#table(
columns: 3,
align: (auto,auto,auto,),
table.header([Tecnologia], [Versão], [Uso],),
table.hline(),
[#strong[Python];], [3.12+], [Linguagem principal],
[#strong[uv];], [Latest], [Gerenciador de pacotes],
[#strong[Ollama];], [Latest], [Runtime para LLMs locais],
[#strong[ChromaDB];], [Latest], [Banco de dados vetorial],
[#strong[Gradio];], [4.0+], [Interface web],
[#strong[mxbai-embed-large];], [669MB], [Modelo de embeddings],
[#strong[qwen3:30b];], [18GB], [Modelo de geração (padrão)],
)
#horizontalrule
== 🐛 Solução de Problemas
<solução-de-problemas>
=== Erro: "Model not found"