Upload app.py
Browse files
app.py
CHANGED
|
@@ -979,24 +979,47 @@ async def analyze_graph_api(job_id: str = Form(...)):
|
|
| 979 |
cached_data = cache[job_id]
|
| 980 |
df = cached_data["df"]
|
| 981 |
textos = df["full_text"].tolist()
|
|
|
|
| 982 |
|
| 983 |
# Extrair entidades e construir grafo
|
| 984 |
entities_by_doc = extract_entities(textos)
|
| 985 |
entity_network = build_entity_to_entity_graph(entities_by_doc)
|
| 986 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 987 |
# Preparar resumo do grafo para o LLM
|
| 988 |
nodes = entity_network.get("nodes", [])[:15]
|
| 989 |
edges = entity_network.get("edges", [])[:20]
|
| 990 |
hubs = entity_network.get("hubs", [])[:5]
|
| 991 |
insights = entity_network.get("insights", {})
|
| 992 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 993 |
graph_summary = f"""
|
| 994 |
-
ANÁLISE DE KNOWLEDGE GRAPH
|
| 995 |
|
| 996 |
## Visão Geral
|
| 997 |
- {len(nodes)} entidades principais
|
| 998 |
- {insights.get('total_connections', 0)} conexões totais
|
| 999 |
- {insights.get('hub_count', 0)} hubs identificados
|
|
|
|
| 1000 |
|
| 1001 |
## Entidades Principais (por importância):
|
| 1002 |
{chr(10).join([f"- {n['entity']} ({n['type']}): {n['docs']} docs, centralidade {n.get('centrality', 0)}" for n in nodes])}
|
|
@@ -1006,6 +1029,9 @@ ANÁLISE DE KNOWLEDGE GRAPH
|
|
| 1006 |
|
| 1007 |
## Conexões Mais Fortes:
|
| 1008 |
{chr(10).join([f"- {e['source_entity']} ↔ {e['target_entity']}: {e['weight']} co-ocorrências" for e in edges[:10]])}
|
|
|
|
|
|
|
|
|
|
| 1009 |
"""
|
| 1010 |
|
| 1011 |
# Prompt para análise
|
|
@@ -1019,10 +1045,11 @@ Por favor forneça:
|
|
| 1019 |
1. **Narrativa Central**: Qual é a história principal que conecta estas entidades?
|
| 1020 |
2. **Atores Chave**: Quem são os principais players e qual seu papel?
|
| 1021 |
3. **Relações Ocultas**: Que conexões não-óbvias você identifica?
|
| 1022 |
-
4. **Padrões**:
|
| 1023 |
5. **Investigação**: O que valeria a pena investigar mais a fundo?
|
| 1024 |
|
| 1025 |
-
|
|
|
|
| 1026 |
|
| 1027 |
# Chamar LLM
|
| 1028 |
completion = groq_client.chat.completions.create(
|
|
|
|
| 979 |
cached_data = cache[job_id]
|
| 980 |
df = cached_data["df"]
|
| 981 |
textos = df["full_text"].tolist()
|
| 982 |
+
clusters = df["cluster"].tolist() if "cluster" in df.columns else ["0"] * len(textos)
|
| 983 |
|
| 984 |
# Extrair entidades e construir grafo
|
| 985 |
entities_by_doc = extract_entities(textos)
|
| 986 |
entity_network = build_entity_to_entity_graph(entities_by_doc)
|
| 987 |
|
| 988 |
+
# Mapear entidades por cluster
|
| 989 |
+
entity_clusters = defaultdict(lambda: defaultdict(int))
|
| 990 |
+
for doc_idx, (entities, cluster) in enumerate(zip(entities_by_doc, clusters)):
|
| 991 |
+
for ent_text, ent_type in entities:
|
| 992 |
+
entity_clusters[ent_text][str(cluster)] += 1
|
| 993 |
+
|
| 994 |
# Preparar resumo do grafo para o LLM
|
| 995 |
nodes = entity_network.get("nodes", [])[:15]
|
| 996 |
edges = entity_network.get("edges", [])[:20]
|
| 997 |
hubs = entity_network.get("hubs", [])[:5]
|
| 998 |
insights = entity_network.get("insights", {})
|
| 999 |
|
| 1000 |
+
# Criar contexto de clusters
|
| 1001 |
+
cluster_context = []
|
| 1002 |
+
unique_clusters = sorted(set(str(c) for c in clusters if str(c) != "-1"))
|
| 1003 |
+
for cluster_id in unique_clusters[:5]:
|
| 1004 |
+
cluster_docs = [textos[i][:200] for i, c in enumerate(clusters) if str(c) == cluster_id][:3]
|
| 1005 |
+
cluster_entities = [(ent, entity_clusters[ent].get(cluster_id, 0))
|
| 1006 |
+
for ent in entity_clusters if entity_clusters[ent].get(cluster_id, 0) > 0]
|
| 1007 |
+
cluster_entities.sort(key=lambda x: x[1], reverse=True)
|
| 1008 |
+
|
| 1009 |
+
cluster_context.append(f"""
|
| 1010 |
+
### Cluster {cluster_id} ({len([c for c in clusters if str(c) == cluster_id])} docs)
|
| 1011 |
+
Entidades principais: {', '.join([f"{e[0]}({e[1]})" for e in cluster_entities[:5]])}
|
| 1012 |
+
Exemplo de documento: "{cluster_docs[0][:150]}..."
|
| 1013 |
+
""")
|
| 1014 |
+
|
| 1015 |
graph_summary = f"""
|
| 1016 |
+
ANÁLISE DE KNOWLEDGE GRAPH COM CONTEXTO
|
| 1017 |
|
| 1018 |
## Visão Geral
|
| 1019 |
- {len(nodes)} entidades principais
|
| 1020 |
- {insights.get('total_connections', 0)} conexões totais
|
| 1021 |
- {insights.get('hub_count', 0)} hubs identificados
|
| 1022 |
+
- {len(unique_clusters)} clusters de documentos
|
| 1023 |
|
| 1024 |
## Entidades Principais (por importância):
|
| 1025 |
{chr(10).join([f"- {n['entity']} ({n['type']}): {n['docs']} docs, centralidade {n.get('centrality', 0)}" for n in nodes])}
|
|
|
|
| 1029 |
|
| 1030 |
## Conexões Mais Fortes:
|
| 1031 |
{chr(10).join([f"- {e['source_entity']} ↔ {e['target_entity']}: {e['weight']} co-ocorrências" for e in edges[:10]])}
|
| 1032 |
+
|
| 1033 |
+
## CONTEXTO POR CLUSTER (IMPORTANTE - USE ESTAS REFERÊNCIAS):
|
| 1034 |
+
{chr(10).join(cluster_context)}
|
| 1035 |
"""
|
| 1036 |
|
| 1037 |
# Prompt para análise
|
|
|
|
| 1045 |
1. **Narrativa Central**: Qual é a história principal que conecta estas entidades?
|
| 1046 |
2. **Atores Chave**: Quem são os principais players e qual seu papel?
|
| 1047 |
3. **Relações Ocultas**: Que conexões não-óbvias você identifica?
|
| 1048 |
+
4. **Padrões por Cluster**: Como as entidades se distribuem entre os clusters? Qual cluster tem foco diferente?
|
| 1049 |
5. **Investigação**: O que valeria a pena investigar mais a fundo?
|
| 1050 |
|
| 1051 |
+
IMPORTANTE: Sempre referencie os clusters específicos (ex: "No Cluster 0...", "Já no Cluster 1...").
|
| 1052 |
+
Use os dados concretos fornecidos, não generalize. Seja específico citando entidades e clusters."""
|
| 1053 |
|
| 1054 |
# Chamar LLM
|
| 1055 |
completion = groq_client.chat.completions.create(
|