Spaces:
Running
Running
luanpoppe
commited on
Commit
·
f9a1a18
1
Parent(s):
d514965
refactor: melhorando a função gerar_documento e a classe GerarDocumento
Browse files- _utils/Utils_Class.py +0 -3
- _utils/axiom_logs.py +27 -0
- _utils/custom_exception_handler.py +1 -1
- _utils/gerar_documento.py +20 -97
- _utils/gerar_documento_utils/GerarDocumento.py +150 -8
- _utils/gerar_documento_utils/prompts.py +4 -0
- _utils/gerar_documento_utils/utils.py +2 -1
- _utils/ragas.py +1 -1
- gerar_documento/views.py +6 -4
_utils/Utils_Class.py
CHANGED
|
@@ -8,6 +8,3 @@ from _utils.Handle_Files_Class import HandleFilesClass
|
|
| 8 |
class UtilsClass:
|
| 9 |
lista_pdfs: List[str] | None = None
|
| 10 |
handle_files = HandleFilesClass()
|
| 11 |
-
|
| 12 |
-
def configure_lista_pdfs(self, lista_pdfs):
|
| 13 |
-
self.lista_pdfs = lista_pdfs
|
|
|
|
| 8 |
class UtilsClass:
|
| 9 |
lista_pdfs: List[str] | None = None
|
| 10 |
handle_files = HandleFilesClass()
|
|
|
|
|
|
|
|
|
_utils/axiom_logs.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
|
| 3 |
+
from setup.logging import Axiom
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
@dataclass
|
| 7 |
+
class AxiomLogs:
|
| 8 |
+
axiom: Axiom
|
| 9 |
+
|
| 10 |
+
def texto_completo_pdf(self, full_text_as_array):
|
| 11 |
+
self.axiom.send_axiom(
|
| 12 |
+
f"INÍCIO DO TEXTO COMPLETO DOS PDFS: {full_text_as_array[0:5]}"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
def resumo_inicial_processo(self, response_auxiliar_summary):
|
| 16 |
+
self.axiom.send_axiom(
|
| 17 |
+
f"RESUMO INICIAL DO PROCESSO: {response_auxiliar_summary}"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
def inicio_requisicao_contextual(self):
|
| 21 |
+
self.axiom.send_axiom("COMEÇANDO A FAZER AS REQUISIÇÕES DO CONTEXTUAL")
|
| 22 |
+
|
| 23 |
+
def fim_requisicao_contextual(self):
|
| 24 |
+
self.axiom.send_axiom("TERMINOU DE FAZER TODAS AS REQUISIÇÕES DO CONTEXTUAL")
|
| 25 |
+
|
| 26 |
+
def chunks_inicialmente(self, chunks_processados):
|
| 27 |
+
self.axiom.send_axiom(f"CHUNKS PROCESSADOS INICIALMENTE: {chunks_processados}")
|
_utils/custom_exception_handler.py
CHANGED
|
@@ -44,7 +44,7 @@ def custom_exception_handler(exc, context):
|
|
| 44 |
return response
|
| 45 |
|
| 46 |
|
| 47 |
-
def
|
| 48 |
error, serializer: Union[GerarDocumentoSerializerData, Any], axiom_instace: Axiom
|
| 49 |
):
|
| 50 |
bahia_tz = pytz.timezone("America/Bahia")
|
|
|
|
| 44 |
return response
|
| 45 |
|
| 46 |
|
| 47 |
+
def custom_exception_handler_without_api_handler(
|
| 48 |
error, serializer: Union[GerarDocumentoSerializerData, Any], axiom_instace: Axiom
|
| 49 |
):
|
| 50 |
bahia_tz = pytz.timezone("America/Bahia")
|
_utils/gerar_documento.py
CHANGED
|
@@ -2,12 +2,11 @@ import os
|
|
| 2 |
from langchain_core.messages import HumanMessage
|
| 3 |
from typing import Any, Union, cast
|
| 4 |
from _utils.Utils_Class import UtilsClass
|
|
|
|
| 5 |
from _utils.langchain_utils.LLM_class import LLM
|
| 6 |
from _utils.bubble_integrations.enviar_resposta_final import enviar_resposta_final
|
| 7 |
-
from _utils.custom_exception_handler import
|
| 8 |
-
from
|
| 9 |
-
prompt_gerar_query_dinamicamente,
|
| 10 |
-
)
|
| 11 |
from _utils.gerar_documento_utils.GerarDocumento import (
|
| 12 |
GerarDocumento,
|
| 13 |
)
|
|
@@ -50,120 +49,44 @@ async def gerar_documento(
|
|
| 50 |
):
|
| 51 |
try:
|
| 52 |
axiom = axiom_instance.send_axiom
|
|
|
|
| 53 |
utils = UtilsClass()
|
| 54 |
-
|
| 55 |
-
contextual_retriever = ContextualRetriever(serializer)
|
| 56 |
-
summarizer = GerarDocumento(serializer, axiom_instance)
|
| 57 |
-
|
| 58 |
-
params = {
|
| 59 |
-
"listaPDFs": listaPDFs,
|
| 60 |
-
"splitterObject": summarizer.splitter,
|
| 61 |
-
"should_use_llama_parse": serializer.should_use_llama_parse,
|
| 62 |
-
"isBubble": isBubble,
|
| 63 |
-
}
|
| 64 |
|
| 65 |
-
all_PDFs_chunks, full_text_as_array = (
|
| 66 |
-
await handle_files.get_full_text_and_all_PDFs_chunks(**params)
|
| 67 |
-
)
|
| 68 |
-
axiom(f"INÍCIO DO TEXTO COMPLETO DOS PDFS: {full_text_as_array[0:5]}")
|
| 69 |
|
| 70 |
is_contextualized_chunk = serializer.should_have_contextual_chunks
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
await get_response_from_auxiliar_contextual_prompt(full_text_as_array)
|
| 75 |
-
)
|
| 76 |
-
axiom(f"RESUMO INICIAL DO PROCESSO: {response_auxiliar_summary}")
|
| 77 |
-
|
| 78 |
-
axiom("COMEÇANDO A FAZER AS REQUISIÇÕES DO CONTEXTUAL")
|
| 79 |
-
contextualized_chunks = await contextual_retriever.contextualize_all_chunks(
|
| 80 |
-
all_PDFs_chunks, response_auxiliar_summary, axiom_instance
|
| 81 |
-
)
|
| 82 |
-
axiom("TERMINOU DE FAZER TODAS AS REQUISIÇÕES DO CONTEXTUAL")
|
| 83 |
-
chunks_processados = contextualized_chunks
|
| 84 |
-
axiom(f"CHUNKS PROCESSADOS INICIALMENTE: {chunks_processados}")
|
| 85 |
-
else:
|
| 86 |
-
chunks_processados = all_PDFs_chunks
|
| 87 |
-
|
| 88 |
-
llm = LLM()
|
| 89 |
-
prompt_para_gerar_query_dinamico = prompt_gerar_query_dinamicamente(
|
| 90 |
-
cast(str, response_auxiliar_summary)
|
| 91 |
)
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
|
| 94 |
-
query_gerado_dinamicamente_para_o_vector_store = (
|
| 95 |
-
await llm.google_gemini_ainvoke(
|
| 96 |
-
prompt_para_gerar_query_dinamico, "gemini-2.0-flash"
|
| 97 |
-
)
|
| 98 |
-
)
|
| 99 |
|
| 100 |
-
|
| 101 |
-
f"query_gerado_dinamicamente_para_o_vector_store: {query_gerado_dinamicamente_para_o_vector_store.content}",
|
| 102 |
-
)
|
| 103 |
|
| 104 |
-
|
| 105 |
-
vector_store, bm25, chunk_ids = (
|
| 106 |
-
summarizer.vector_store.create_enhanced_vector_store(
|
| 107 |
-
chunks_processados, is_contextualized_chunk, axiom_instance
|
| 108 |
-
)
|
| 109 |
-
)
|
| 110 |
|
| 111 |
-
|
| 112 |
-
axiom("COMEÇANDO A FAZER ÚLTIMA REQUISIÇÃO")
|
| 113 |
-
structured_summaries = await summarizer.gerar_documento_final(
|
| 114 |
-
vector_store,
|
| 115 |
-
bm25,
|
| 116 |
-
chunk_ids,
|
| 117 |
-
llm_ultimas_requests,
|
| 118 |
-
cast(
|
| 119 |
-
str, query_gerado_dinamicamente_para_o_vector_store.content
|
| 120 |
-
), # prompt_auxiliar_SEM_CONTEXT,
|
| 121 |
-
)
|
| 122 |
-
axiom("TERMINOU DE FAZER A ÚLTIMA REQUISIÇÃO")
|
| 123 |
|
| 124 |
if not isinstance(structured_summaries, list):
|
| 125 |
-
from rest_framework.response import Response
|
| 126 |
-
|
| 127 |
return Response({"erro": structured_summaries})
|
| 128 |
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
for x in structured_summaries:
|
| 132 |
-
texto_completo = texto_completo + x["content"] + "\n"
|
| 133 |
-
x["source"]["text"] = x["source"]["text"][0:200]
|
| 134 |
-
x["source"]["context"] = x["source"]["context"][0:200]
|
| 135 |
|
| 136 |
-
|
| 137 |
-
"resposta_segunda_etapa:", "<br><br>"
|
| 138 |
-
)
|
| 139 |
-
axiom(f"texto_completo_como_html: {texto_completo_como_html}")
|
| 140 |
-
|
| 141 |
-
if is_contextualized_chunk:
|
| 142 |
-
prompt_titulo_do_documento = response_auxiliar_summary
|
| 143 |
-
else:
|
| 144 |
-
prompt_titulo_do_documento = texto_completo_como_html
|
| 145 |
-
titulo_do_documento = await generate_document_title(
|
| 146 |
-
cast(str, prompt_titulo_do_documento)
|
| 147 |
-
)
|
| 148 |
|
| 149 |
if isBubble:
|
| 150 |
-
|
| 151 |
-
enviar_resposta_final(
|
| 152 |
-
serializer.doc_id, # type: ignore
|
| 153 |
-
serializer.form_response_id, # type: ignore
|
| 154 |
-
serializer.version, # type: ignore
|
| 155 |
-
texto_completo_como_html,
|
| 156 |
-
False,
|
| 157 |
-
cast(str, titulo_do_documento),
|
| 158 |
-
)
|
| 159 |
-
axiom("TERMINOU A REQUISIÇÃO FINAL PARA O BUBBLE")
|
| 160 |
|
| 161 |
return {
|
| 162 |
-
"texto_completo": texto_completo_como_html,
|
| 163 |
-
"titulo_do_documento": titulo_do_documento,
|
| 164 |
"resultado": structured_summaries,
|
| 165 |
"parametros-utilizados": gerar_resposta_compilada(serializer),
|
| 166 |
}
|
| 167 |
except Exception as e:
|
| 168 |
-
|
| 169 |
raise
|
|
|
|
| 2 |
from langchain_core.messages import HumanMessage
|
| 3 |
from typing import Any, Union, cast
|
| 4 |
from _utils.Utils_Class import UtilsClass
|
| 5 |
+
from _utils.axiom_logs import AxiomLogs
|
| 6 |
from _utils.langchain_utils.LLM_class import LLM
|
| 7 |
from _utils.bubble_integrations.enviar_resposta_final import enviar_resposta_final
|
| 8 |
+
from _utils.custom_exception_handler import custom_exception_handler_without_api_handler
|
| 9 |
+
from rest_framework.response import Response
|
|
|
|
|
|
|
| 10 |
from _utils.gerar_documento_utils.GerarDocumento import (
|
| 11 |
GerarDocumento,
|
| 12 |
)
|
|
|
|
| 49 |
):
|
| 50 |
try:
|
| 51 |
axiom = axiom_instance.send_axiom
|
| 52 |
+
ax = AxiomLogs(axiom_instance)
|
| 53 |
utils = UtilsClass()
|
| 54 |
+
summarizer = GerarDocumento(serializer, isBubble, axiom_instance)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
+
all_PDFs_chunks, full_text_as_array = await summarizer.get_text_and_pdf_chunks()
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
is_contextualized_chunk = serializer.should_have_contextual_chunks
|
| 59 |
|
| 60 |
+
response_auxiliar_summary = await get_response_from_auxiliar_contextual_prompt(
|
| 61 |
+
full_text_as_array
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
)
|
| 63 |
+
summarizer.resumo_auxiliar = response_auxiliar_summary
|
| 64 |
+
ax.resumo_inicial_processo(response_auxiliar_summary)
|
| 65 |
|
| 66 |
+
await summarizer.generate_chunks_processados()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
await summarizer.generate_query_for_vector_store()
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
await summarizer.create_enhanced_vector_store()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
structured_summaries = await summarizer.do_last_requests()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
if not isinstance(structured_summaries, list):
|
|
|
|
|
|
|
| 75 |
return Response({"erro": structured_summaries})
|
| 76 |
|
| 77 |
+
await summarizer.generate_complete_text()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
+
await summarizer.get_document_title()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
|
| 81 |
if isBubble:
|
| 82 |
+
await summarizer.send_to_bubble()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
|
| 84 |
return {
|
| 85 |
+
"texto_completo": summarizer.texto_completo_como_html,
|
| 86 |
+
"titulo_do_documento": summarizer.titulo_do_documento,
|
| 87 |
"resultado": structured_summaries,
|
| 88 |
"parametros-utilizados": gerar_resposta_compilada(serializer),
|
| 89 |
}
|
| 90 |
except Exception as e:
|
| 91 |
+
custom_exception_handler_without_api_handler(e, serializer, axiom_instance)
|
| 92 |
raise
|
_utils/gerar_documento_utils/GerarDocumento.py
CHANGED
|
@@ -3,10 +3,20 @@ import os
|
|
| 3 |
from typing import Any, List, Dict, Literal, Tuple, Optional, Union, cast
|
| 4 |
|
| 5 |
from pydantic import SecretStr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from _utils.langchain_utils.Chain_class import Chain
|
| 7 |
from _utils.langchain_utils.LLM_class import LLM
|
| 8 |
from _utils.langchain_utils.Prompt_class import Prompt
|
| 9 |
from _utils.langchain_utils.Vector_store_class import VectorStore
|
|
|
|
| 10 |
from gerar_documento.serializer import (
|
| 11 |
GerarDocumentoComPDFProprioSerializerData,
|
| 12 |
GerarDocumentoSerializerData,
|
|
@@ -21,6 +31,8 @@ from setup.easy_imports import (
|
|
| 21 |
)
|
| 22 |
import logging
|
| 23 |
from _utils.models.gerar_documento import (
|
|
|
|
|
|
|
| 24 |
RetrievalConfig,
|
| 25 |
)
|
| 26 |
from cohere import Client
|
|
@@ -97,14 +109,28 @@ class GerarDocumentoUtils:
|
|
| 97 |
|
| 98 |
|
| 99 |
class GerarDocumento:
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
gerar_documento_utils = GerarDocumentoUtils()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
def __init__(
|
| 104 |
self,
|
| 105 |
serializer: Union[
|
| 106 |
GerarDocumentoSerializerData, GerarDocumentoComPDFProprioSerializerData, Any
|
| 107 |
],
|
|
|
|
| 108 |
axiom_instance: Axiom,
|
| 109 |
):
|
| 110 |
self.config = self.gerar_documento_utils.create_retrieval_config(serializer)
|
|
@@ -113,6 +139,11 @@ class GerarDocumento:
|
|
| 113 |
self.gpt_model = serializer.model
|
| 114 |
self.gpt_temperature = serializer.gpt_temperature
|
| 115 |
self.prompt_gerar_documento = serializer.prompt_gerar_documento
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
self.cohere_client = Client(cohere_api_key)
|
| 118 |
self.embeddings = HuggingFaceEmbeddings(model_name=serializer.hf_embedding)
|
|
@@ -124,6 +155,71 @@ class GerarDocumento:
|
|
| 124 |
|
| 125 |
self.vector_store = VectorStore(serializer.hf_embedding)
|
| 126 |
self.axiom_instance: Axiom = axiom_instance
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 127 |
|
| 128 |
def retrieve_with_rank_fusion(
|
| 129 |
self, vector_store: Chroma, bm25: BM25Okapi, chunk_ids: List[str], query: str
|
|
@@ -236,17 +332,18 @@ class GerarDocumento:
|
|
| 236 |
llm = llm_instance.google_gemini("gemini-2.5-flash-preview-04-17")
|
| 237 |
return llm
|
| 238 |
|
| 239 |
-
async def
|
| 240 |
self,
|
| 241 |
-
vector_store: Chroma,
|
| 242 |
-
bm25: BM25Okapi,
|
| 243 |
-
chunk_ids: List[str],
|
| 244 |
-
llm_ultimas_requests: str,
|
| 245 |
-
query: str = "Summarize the main points of this document",
|
| 246 |
) -> List[Dict]:
|
| 247 |
try:
|
|
|
|
|
|
|
|
|
|
| 248 |
sources, contexts = self.rank_fusion_get_top_results(
|
| 249 |
-
vector_store,
|
|
|
|
|
|
|
|
|
|
| 250 |
)
|
| 251 |
|
| 252 |
prompt_gerar_documento = PromptTemplate(
|
|
@@ -254,6 +351,7 @@ class GerarDocumento:
|
|
| 254 |
input_variables=["context"],
|
| 255 |
)
|
| 256 |
|
|
|
|
| 257 |
llm = self.select_model_for_last_requests(llm_ultimas_requests) # type: ignore
|
| 258 |
prompt_instance = Prompt()
|
| 259 |
context_do_prompt_primeira_etapa = "\n\n".join(contexts)
|
|
@@ -311,12 +409,56 @@ class GerarDocumento:
|
|
| 311 |
structured_output = self.gerar_documento_utils.criar_output_estruturado(
|
| 312 |
summaries, sources
|
| 313 |
)
|
|
|
|
|
|
|
|
|
|
| 314 |
return structured_output
|
| 315 |
|
| 316 |
except Exception as e:
|
| 317 |
self.logger.error(f"Error generating enhanced summary: {str(e)}")
|
| 318 |
raise
|
| 319 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
async def checar_se_resposta_vazia_do_documento_final(
|
| 321 |
self, llm_ultimas_requests: str, prompt: str
|
| 322 |
):
|
|
|
|
| 3 |
from typing import Any, List, Dict, Literal, Tuple, Optional, Union, cast
|
| 4 |
|
| 5 |
from pydantic import SecretStr
|
| 6 |
+
from _utils.Utils_Class import UtilsClass
|
| 7 |
+
from _utils.axiom_logs import AxiomLogs
|
| 8 |
+
from _utils.bubble_integrations.enviar_resposta_final import enviar_resposta_final
|
| 9 |
+
from _utils.gerar_documento_utils.contextual_retriever import ContextualRetriever
|
| 10 |
+
from _utils.gerar_documento_utils.llm_calls import agemini_answer
|
| 11 |
+
from _utils.gerar_documento_utils.prompts import (
|
| 12 |
+
prompt_gerar_query_dinamicamente,
|
| 13 |
+
prompt_para_gerar_titulo,
|
| 14 |
+
)
|
| 15 |
from _utils.langchain_utils.Chain_class import Chain
|
| 16 |
from _utils.langchain_utils.LLM_class import LLM
|
| 17 |
from _utils.langchain_utils.Prompt_class import Prompt
|
| 18 |
from _utils.langchain_utils.Vector_store_class import VectorStore
|
| 19 |
+
from _utils.utils import convert_markdown_to_HTML
|
| 20 |
from gerar_documento.serializer import (
|
| 21 |
GerarDocumentoComPDFProprioSerializerData,
|
| 22 |
GerarDocumentoSerializerData,
|
|
|
|
| 31 |
)
|
| 32 |
import logging
|
| 33 |
from _utils.models.gerar_documento import (
|
| 34 |
+
ContextualizedChunk,
|
| 35 |
+
DocumentChunk,
|
| 36 |
RetrievalConfig,
|
| 37 |
)
|
| 38 |
from cohere import Client
|
|
|
|
| 109 |
|
| 110 |
|
| 111 |
class GerarDocumento:
|
| 112 |
+
lista_pdfs: List[str]
|
| 113 |
+
should_use_llama_parse: bool
|
| 114 |
+
all_PDFs_chunks: List[DocumentChunk]
|
| 115 |
+
full_text_as_array: List[str]
|
| 116 |
+
isBubble: bool
|
| 117 |
+
chunks_processados: List[ContextualizedChunk] | List[DocumentChunk]
|
| 118 |
+
resumo_auxiliar: str
|
| 119 |
gerar_documento_utils = GerarDocumentoUtils()
|
| 120 |
+
utils = UtilsClass()
|
| 121 |
+
llm = LLM()
|
| 122 |
+
enhanced_vector_store: tuple[Chroma, BM25Okapi, List[str]]
|
| 123 |
+
query_gerado_dinamicamente_para_o_vector_store: str
|
| 124 |
+
structured_output: List[Any]
|
| 125 |
+
texto_completo_como_html: str
|
| 126 |
+
titulo_do_documento: str
|
| 127 |
|
| 128 |
def __init__(
|
| 129 |
self,
|
| 130 |
serializer: Union[
|
| 131 |
GerarDocumentoSerializerData, GerarDocumentoComPDFProprioSerializerData, Any
|
| 132 |
],
|
| 133 |
+
isBubble: bool,
|
| 134 |
axiom_instance: Axiom,
|
| 135 |
):
|
| 136 |
self.config = self.gerar_documento_utils.create_retrieval_config(serializer)
|
|
|
|
| 139 |
self.gpt_model = serializer.model
|
| 140 |
self.gpt_temperature = serializer.gpt_temperature
|
| 141 |
self.prompt_gerar_documento = serializer.prompt_gerar_documento
|
| 142 |
+
self.should_use_llama_parse = serializer.should_use_llama_parse
|
| 143 |
+
self.isBubble = isBubble
|
| 144 |
+
self.is_contextualized_chunk = serializer.should_have_contextual_chunks
|
| 145 |
+
self.contextual_retriever = ContextualRetriever(serializer)
|
| 146 |
+
self.llm_ultimas_requests = serializer.llm_ultimas_requests
|
| 147 |
|
| 148 |
self.cohere_client = Client(cohere_api_key)
|
| 149 |
self.embeddings = HuggingFaceEmbeddings(model_name=serializer.hf_embedding)
|
|
|
|
| 155 |
|
| 156 |
self.vector_store = VectorStore(serializer.hf_embedding)
|
| 157 |
self.axiom_instance: Axiom = axiom_instance
|
| 158 |
+
self.ax = AxiomLogs(axiom_instance)
|
| 159 |
+
|
| 160 |
+
async def get_text_and_pdf_chunks(self):
|
| 161 |
+
all_PDFs_chunks, full_text_as_array = (
|
| 162 |
+
await self.utils.handle_files.get_full_text_and_all_PDFs_chunks(
|
| 163 |
+
self.lista_pdfs,
|
| 164 |
+
self.splitter,
|
| 165 |
+
self.should_use_llama_parse,
|
| 166 |
+
self.isBubble,
|
| 167 |
+
)
|
| 168 |
+
)
|
| 169 |
+
self.ax.texto_completo_pdf(full_text_as_array)
|
| 170 |
+
|
| 171 |
+
self.all_PDFs_chunks = all_PDFs_chunks
|
| 172 |
+
self.full_text_as_array = full_text_as_array
|
| 173 |
+
return all_PDFs_chunks, full_text_as_array
|
| 174 |
+
|
| 175 |
+
async def generate_chunks_processados(self):
|
| 176 |
+
if self.is_contextualized_chunk:
|
| 177 |
+
self.ax.inicio_requisicao_contextual()
|
| 178 |
+
contextualized_chunks = (
|
| 179 |
+
await self.contextual_retriever.contextualize_all_chunks(
|
| 180 |
+
self.all_PDFs_chunks, self.resumo_auxiliar, self.axiom_instance
|
| 181 |
+
)
|
| 182 |
+
)
|
| 183 |
+
self.ax.fim_requisicao_contextual()
|
| 184 |
+
|
| 185 |
+
chunks_processados = (
|
| 186 |
+
contextualized_chunks
|
| 187 |
+
if self.is_contextualized_chunk
|
| 188 |
+
else self.all_PDFs_chunks
|
| 189 |
+
)
|
| 190 |
+
self.chunks_processados = chunks_processados
|
| 191 |
+
self.ax.chunks_inicialmente(chunks_processados)
|
| 192 |
+
return chunks_processados
|
| 193 |
+
|
| 194 |
+
async def generate_query_for_vector_store(self):
|
| 195 |
+
prompt_para_gerar_query_dinamico = prompt_gerar_query_dinamicamente(
|
| 196 |
+
cast(str, self.resumo_auxiliar)
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
self.axiom_instance.send_axiom(
|
| 200 |
+
"COMEÇANDO REQUISIÇÃO PARA GERAR O QUERY DINAMICAMENTE DO VECTOR STORE"
|
| 201 |
+
)
|
| 202 |
+
response = await self.llm.google_gemini_ainvoke(
|
| 203 |
+
prompt_para_gerar_query_dinamico, "gemini-2.0-flash"
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
self.query_gerado_dinamicamente_para_o_vector_store = cast(
|
| 207 |
+
str, response.content
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
self.axiom_instance.send_axiom(
|
| 211 |
+
f"query_gerado_dinamicamente_para_o_vector_store: {self.query_gerado_dinamicamente_para_o_vector_store}",
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
return self.query_gerado_dinamicamente_para_o_vector_store
|
| 215 |
+
|
| 216 |
+
async def create_enhanced_vector_store(self):
|
| 217 |
+
vector_store, bm25, chunk_ids = self.vector_store.create_enhanced_vector_store(
|
| 218 |
+
self.chunks_processados, self.is_contextualized_chunk, self.axiom_instance # type: ignore
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
self.enhanced_vector_store = vector_store, bm25, chunk_ids
|
| 222 |
+
return vector_store, bm25, chunk_ids
|
| 223 |
|
| 224 |
def retrieve_with_rank_fusion(
|
| 225 |
self, vector_store: Chroma, bm25: BM25Okapi, chunk_ids: List[str], query: str
|
|
|
|
| 332 |
llm = llm_instance.google_gemini("gemini-2.5-flash-preview-04-17")
|
| 333 |
return llm
|
| 334 |
|
| 335 |
+
async def do_last_requests(
|
| 336 |
self,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
) -> List[Dict]:
|
| 338 |
try:
|
| 339 |
+
self.axiom_instance.send_axiom("COMEÇANDO A FAZER ÚLTIMA REQUISIÇÃO")
|
| 340 |
+
vector_store, bm25, chunk_ids = self.enhanced_vector_store
|
| 341 |
+
|
| 342 |
sources, contexts = self.rank_fusion_get_top_results(
|
| 343 |
+
vector_store,
|
| 344 |
+
bm25,
|
| 345 |
+
chunk_ids,
|
| 346 |
+
self.query_gerado_dinamicamente_para_o_vector_store,
|
| 347 |
)
|
| 348 |
|
| 349 |
prompt_gerar_documento = PromptTemplate(
|
|
|
|
| 351 |
input_variables=["context"],
|
| 352 |
)
|
| 353 |
|
| 354 |
+
llm_ultimas_requests = self.llm_ultimas_requests
|
| 355 |
llm = self.select_model_for_last_requests(llm_ultimas_requests) # type: ignore
|
| 356 |
prompt_instance = Prompt()
|
| 357 |
context_do_prompt_primeira_etapa = "\n\n".join(contexts)
|
|
|
|
| 409 |
structured_output = self.gerar_documento_utils.criar_output_estruturado(
|
| 410 |
summaries, sources
|
| 411 |
)
|
| 412 |
+
|
| 413 |
+
self.axiom_instance.send_axiom("TERMINOU DE FAZER A ÚLTIMA REQUISIÇÃO")
|
| 414 |
+
self.structured_output = structured_output
|
| 415 |
return structured_output
|
| 416 |
|
| 417 |
except Exception as e:
|
| 418 |
self.logger.error(f"Error generating enhanced summary: {str(e)}")
|
| 419 |
raise
|
| 420 |
|
| 421 |
+
async def generate_complete_text(self):
|
| 422 |
+
texto_completo = "\n\n"
|
| 423 |
+
|
| 424 |
+
for x in self.structured_output:
|
| 425 |
+
texto_completo = texto_completo + x["content"] + "\n"
|
| 426 |
+
x["source"]["text"] = x["source"]["text"][0:200]
|
| 427 |
+
x["source"]["context"] = x["source"]["context"][0:200]
|
| 428 |
+
|
| 429 |
+
self.texto_completo_como_html = convert_markdown_to_HTML(
|
| 430 |
+
texto_completo
|
| 431 |
+
).replace("resposta_segunda_etapa:", "<br><br>")
|
| 432 |
+
|
| 433 |
+
self.axiom_instance.send_axiom(
|
| 434 |
+
f"texto_completo_como_html: {self.texto_completo_como_html}"
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
async def get_document_title(self):
|
| 438 |
+
if self.is_contextualized_chunk:
|
| 439 |
+
resumo_para_gerar_titulo = self.resumo_auxiliar
|
| 440 |
+
else:
|
| 441 |
+
resumo_para_gerar_titulo = self.texto_completo_como_html
|
| 442 |
+
|
| 443 |
+
prompt = prompt_para_gerar_titulo(resumo_para_gerar_titulo)
|
| 444 |
+
response = await agemini_answer(prompt, "gemini-2.0-flash-lite")
|
| 445 |
+
self.titulo_do_documento = response
|
| 446 |
+
return self.titulo_do_documento
|
| 447 |
+
|
| 448 |
+
async def send_to_bubble(self):
|
| 449 |
+
self.axiom_instance.send_axiom("COMEÇANDO A REQUISIÇÃO FINAL PARA O BUBBLE")
|
| 450 |
+
|
| 451 |
+
enviar_resposta_final(
|
| 452 |
+
serializer.doc_id, # type: ignore
|
| 453 |
+
serializer.form_response_id, # type: ignore
|
| 454 |
+
serializer.version, # type: ignore
|
| 455 |
+
self.texto_completo_como_html,
|
| 456 |
+
False,
|
| 457 |
+
cast(str, self.titulo_do_documento),
|
| 458 |
+
)
|
| 459 |
+
|
| 460 |
+
self.axiom_instance.send_axiom("TERMINOU A REQUISIÇÃO FINAL PARA O BUBBLE")
|
| 461 |
+
|
| 462 |
async def checar_se_resposta_vazia_do_documento_final(
|
| 463 |
self, llm_ultimas_requests: str, prompt: str
|
| 464 |
):
|
_utils/gerar_documento_utils/prompts.py
CHANGED
|
@@ -239,3 +239,7 @@ def prompt_gerar_query_dinamicamente(resumo_do_processo: str):
|
|
| 239 |
|
| 240 |
- *Importante:** Sua resposta final deve ser *somente* a string da query.
|
| 241 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
|
| 240 |
- *Importante:** Sua resposta final deve ser *somente* a string da query.
|
| 241 |
"""
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def prompt_para_gerar_titulo(resumo_para_gerar_titulo: str):
|
| 245 |
+
return f"Você é um assistente jurídico e irá receber abaixo o resumo de um documento jurídico. Quero que você gere um título para este documento. Mande como resposta apenas o título gerado, nada mais. Aqui está um título de exemplo pra você se basear ao criar um novo: <titulo_de_exemplo>Ação Penal por Furto Qualificado nº 0002269-86.2009.805.0032<titulo_de_exemplo>\n\nSegue abaixo o resumo do documento jurídico:\n{resumo_para_gerar_titulo}"
|
_utils/gerar_documento_utils/utils.py
CHANGED
|
@@ -7,6 +7,7 @@ from _utils.langchain_utils.Splitter_class import Splitter
|
|
| 7 |
from _utils.langchain_utils.LLM_class import LLM
|
| 8 |
from _utils.gerar_documento_utils.prompts import (
|
| 9 |
create_prompt_auxiliar_do_contextual_prompt,
|
|
|
|
| 10 |
)
|
| 11 |
|
| 12 |
from _utils.models.gerar_documento import DocumentChunk
|
|
@@ -102,6 +103,6 @@ def split_text_by_tokens(full_text: str):
|
|
| 102 |
|
| 103 |
|
| 104 |
async def generate_document_title(resumo_para_gerar_titulo: str):
|
| 105 |
-
prompt =
|
| 106 |
response = await agemini_answer(prompt, "gemini-2.0-flash-lite")
|
| 107 |
return response
|
|
|
|
| 7 |
from _utils.langchain_utils.LLM_class import LLM
|
| 8 |
from _utils.gerar_documento_utils.prompts import (
|
| 9 |
create_prompt_auxiliar_do_contextual_prompt,
|
| 10 |
+
prompt_para_gerar_titulo,
|
| 11 |
)
|
| 12 |
|
| 13 |
from _utils.models.gerar_documento import DocumentChunk
|
|
|
|
| 103 |
|
| 104 |
|
| 105 |
async def generate_document_title(resumo_para_gerar_titulo: str):
|
| 106 |
+
prompt = prompt_para_gerar_titulo(resumo_para_gerar_titulo)
|
| 107 |
response = await agemini_answer(prompt, "gemini-2.0-flash-lite")
|
| 108 |
return response
|
_utils/ragas.py
CHANGED
|
@@ -76,7 +76,7 @@ def test_ragas(serializer, listaPDFs):
|
|
| 76 |
|
| 77 |
def generate_summary(vector_store, bm25, chunk_ids, query, summarizer):
|
| 78 |
"""Generates an enhanced summary using the vector store and BM25 index."""
|
| 79 |
-
structured_summaries = summarizer.
|
| 80 |
vector_store, bm25, chunk_ids, query
|
| 81 |
)
|
| 82 |
return {"structured_summaries": structured_summaries}
|
|
|
|
| 76 |
|
| 77 |
def generate_summary(vector_store, bm25, chunk_ids, query, summarizer):
|
| 78 |
"""Generates an enhanced summary using the vector store and BM25 index."""
|
| 79 |
+
structured_summaries = summarizer.do_last_requests(
|
| 80 |
vector_store, bm25, chunk_ids, query
|
| 81 |
)
|
| 82 |
return {"structured_summaries": structured_summaries}
|
gerar_documento/views.py
CHANGED
|
@@ -2,7 +2,7 @@ from typing import Any, Dict, cast
|
|
| 2 |
from langchain.prompts import PromptTemplate
|
| 3 |
from _utils.Utils_Class import UtilsClass
|
| 4 |
from _utils.bubble_integrations.enviar_resposta_final import enviar_resposta_final
|
| 5 |
-
from _utils.custom_exception_handler import
|
| 6 |
from _utils.gerar_documento_utils.GerarDocumento import GerarDocumento
|
| 7 |
from _utils.langchain_utils.LLM_class import LLM
|
| 8 |
from _utils.gerar_documento_utils.utils import (
|
|
@@ -143,7 +143,9 @@ class GerarEmentaView(AsyncAPIView):
|
|
| 143 |
data = cast(Dict[str, Any], serializer.validated_data)
|
| 144 |
self.serializer = data
|
| 145 |
|
| 146 |
-
gerar_documento_instance = GerarDocumento(
|
|
|
|
|
|
|
| 147 |
|
| 148 |
listaPDFs = [l["link_arquivo"] for l in data["files"]]
|
| 149 |
|
|
@@ -210,7 +212,7 @@ class GerarEmentaView(AsyncAPIView):
|
|
| 210 |
)
|
| 211 |
except Exception as e:
|
| 212 |
print(f"ERRO GERAR EMENTA: {e}")
|
| 213 |
-
|
| 214 |
e, serializer, self.axiom_instance
|
| 215 |
)
|
| 216 |
raise
|
|
@@ -250,7 +252,7 @@ class GerarEmentaComPDFProprioView(AsyncAPIView):
|
|
| 250 |
serializer_obj = serializer.get_obj()
|
| 251 |
|
| 252 |
gerar_documento_instance = GerarDocumento(
|
| 253 |
-
serializer_obj, self.axiom_instance
|
| 254 |
)
|
| 255 |
|
| 256 |
listaPDFs = handle_pdf_files_from_serializer(
|
|
|
|
| 2 |
from langchain.prompts import PromptTemplate
|
| 3 |
from _utils.Utils_Class import UtilsClass
|
| 4 |
from _utils.bubble_integrations.enviar_resposta_final import enviar_resposta_final
|
| 5 |
+
from _utils.custom_exception_handler import custom_exception_handler_without_api_handler
|
| 6 |
from _utils.gerar_documento_utils.GerarDocumento import GerarDocumento
|
| 7 |
from _utils.langchain_utils.LLM_class import LLM
|
| 8 |
from _utils.gerar_documento_utils.utils import (
|
|
|
|
| 143 |
data = cast(Dict[str, Any], serializer.validated_data)
|
| 144 |
self.serializer = data
|
| 145 |
|
| 146 |
+
gerar_documento_instance = GerarDocumento(
|
| 147 |
+
obj, True, self.axiom_instance
|
| 148 |
+
)
|
| 149 |
|
| 150 |
listaPDFs = [l["link_arquivo"] for l in data["files"]]
|
| 151 |
|
|
|
|
| 212 |
)
|
| 213 |
except Exception as e:
|
| 214 |
print(f"ERRO GERAR EMENTA: {e}")
|
| 215 |
+
custom_exception_handler_without_api_handler(
|
| 216 |
e, serializer, self.axiom_instance
|
| 217 |
)
|
| 218 |
raise
|
|
|
|
| 252 |
serializer_obj = serializer.get_obj()
|
| 253 |
|
| 254 |
gerar_documento_instance = GerarDocumento(
|
| 255 |
+
serializer_obj, False, self.axiom_instance
|
| 256 |
)
|
| 257 |
|
| 258 |
listaPDFs = handle_pdf_files_from_serializer(
|