Spaces:
Running
Running
luanpoppe
commited on
Commit
·
baeaaa5
1
Parent(s):
237192a
feat: contextual embedding funcionando com modelo de concorrência
Browse files
_utils/gerar_relatorio_modelo_usuario/EnhancedDocumentSummarizer.py
CHANGED
@@ -20,6 +20,7 @@ from rest_framework.response import Response
|
|
20 |
from _utils.gerar_relatorio_modelo_usuario.contextual_retriever import (
|
21 |
ContextualRetriever,
|
22 |
)
|
|
|
23 |
|
24 |
|
25 |
class EnhancedDocumentSummarizer(DocumentSummarizer):
|
@@ -158,7 +159,7 @@ class EnhancedDocumentSummarizer(DocumentSummarizer):
|
|
158 |
self.logger.error(f"Error in rank fusion retrieval: {str(e)}")
|
159 |
raise
|
160 |
|
161 |
-
def generate_enhanced_summary(
|
162 |
self,
|
163 |
vector_store: Chroma,
|
164 |
bm25: BM25Okapi,
|
@@ -220,17 +221,27 @@ class EnhancedDocumentSummarizer(DocumentSummarizer):
|
|
220 |
from modelos_usuarios.models import ModeloUsuarioModel
|
221 |
|
222 |
try:
|
223 |
-
modelo_buscado = ModeloUsuarioModel.objects.get(
|
|
|
|
|
|
|
|
|
|
|
224 |
pk=self.id_modelo_do_usuario
|
225 |
)
|
226 |
-
serializer = ModeloUsuarioSerializer(
|
|
|
|
|
227 |
print("serializer.data: ", serializer.data)
|
228 |
|
229 |
-
except:
|
|
|
230 |
return Response(
|
231 |
{
|
232 |
-
"error": "Ocorreu um problema. Pode ser que o modelo não tenha sido encontrado. Tente novamente e/ou entre em contato com a equipe técnica"
|
233 |
-
|
|
|
|
|
234 |
)
|
235 |
|
236 |
print("modelo_buscado: ", serializer.data["modelo"])
|
|
|
20 |
from _utils.gerar_relatorio_modelo_usuario.contextual_retriever import (
|
21 |
ContextualRetriever,
|
22 |
)
|
23 |
+
from asgiref.sync import sync_to_async
|
24 |
|
25 |
|
26 |
class EnhancedDocumentSummarizer(DocumentSummarizer):
|
|
|
159 |
self.logger.error(f"Error in rank fusion retrieval: {str(e)}")
|
160 |
raise
|
161 |
|
162 |
+
async def generate_enhanced_summary(
|
163 |
self,
|
164 |
vector_store: Chroma,
|
165 |
bm25: BM25Okapi,
|
|
|
221 |
from modelos_usuarios.models import ModeloUsuarioModel
|
222 |
|
223 |
try:
|
224 |
+
# modelo_buscado = ModeloUsuarioModel.objects.get(
|
225 |
+
# pk=self.id_modelo_do_usuario
|
226 |
+
# )
|
227 |
+
# serializer = ModeloUsuarioSerializer(modelo_buscado)
|
228 |
+
# print("serializer.data: ", serializer.data)
|
229 |
+
modelo_buscado = await sync_to_async(ModeloUsuarioModel.objects.get)(
|
230 |
pk=self.id_modelo_do_usuario
|
231 |
)
|
232 |
+
serializer = await sync_to_async(ModeloUsuarioSerializer)(
|
233 |
+
modelo_buscado
|
234 |
+
)
|
235 |
print("serializer.data: ", serializer.data)
|
236 |
|
237 |
+
except Exception as e:
|
238 |
+
print("e: ", e)
|
239 |
return Response(
|
240 |
{
|
241 |
+
"error": "Ocorreu um problema. Pode ser que o modelo não tenha sido encontrado. Tente novamente e/ou entre em contato com a equipe técnica",
|
242 |
+
"full_error": e,
|
243 |
+
},
|
244 |
+
400,
|
245 |
)
|
246 |
|
247 |
print("modelo_buscado: ", serializer.data["modelo"])
|
_utils/gerar_relatorio_modelo_usuario/contextual_retriever.py
CHANGED
@@ -21,16 +21,6 @@ from _utils.models.gerar_relatorio import (
|
|
21 |
|
22 |
lista_contador = []
|
23 |
|
24 |
-
|
25 |
-
def task(name, barrier, queue, chunk, full_text, config, claude_context_model):
|
26 |
-
"""Função independente para processar um chunk."""
|
27 |
-
print(f"Process {name} ready")
|
28 |
-
barrier.wait() # Espera todos os processos estarem prontos
|
29 |
-
retriever = ContextualRetriever(config, None, claude_context_model)
|
30 |
-
result = retriever.create_contextualized_chunk(chunk, full_text)
|
31 |
-
queue.put(result) # Armazena o resultado na fila
|
32 |
-
|
33 |
-
|
34 |
class ContextualRetriever:
|
35 |
def __init__(
|
36 |
self, config: RetrievalConfig, claude_api_key: str, claude_context_model: str
|
@@ -41,13 +31,13 @@ class ContextualRetriever:
|
|
41 |
self.bm25 = None
|
42 |
self.claude_context_model = claude_context_model
|
43 |
|
44 |
-
def llm_generate_context(self, full_text: str, chunk: DocumentChunk) -> str:
|
45 |
"""Generate contextual description using ChatOpenAI"""
|
46 |
try:
|
47 |
-
prompt = contextual_prompt(full_text, chunk.content)
|
48 |
print("COMEÇOU A REQUISIÇÃO")
|
|
|
49 |
# response = claude_answer(self.claude_client, self.claude_context_model, prompt)
|
50 |
-
response = gpt_answer(prompt)
|
51 |
return response
|
52 |
except Exception as e:
|
53 |
self.logger.error(
|
@@ -55,7 +45,7 @@ class ContextualRetriever:
|
|
55 |
)
|
56 |
return ""
|
57 |
|
58 |
-
def create_contextualized_chunk(self, chunk, full_text):
|
59 |
lista_contador.append(0)
|
60 |
print("contador: ", len(lista_contador))
|
61 |
page_content = ""
|
@@ -65,7 +55,7 @@ class ContextualRetriever:
|
|
65 |
):
|
66 |
page_content += full_text[i].page_content if full_text[i] else ""
|
67 |
|
68 |
-
context = self.llm_generate_context(page_content, chunk)
|
69 |
return ContextualizedChunk(
|
70 |
content=chunk.content,
|
71 |
page_number=chunk.page_number,
|
@@ -75,53 +65,18 @@ class ContextualRetriever:
|
|
75 |
context=context,
|
76 |
)
|
77 |
|
78 |
-
def contextualize_all_chunks(
|
79 |
self, full_text: List[Document], chunks: List[DocumentChunk]
|
80 |
) -> List[ContextualizedChunk]:
|
81 |
"""Add context to all chunks"""
|
82 |
contextualized_chunks = []
|
83 |
|
84 |
-
|
85 |
-
|
|
|
|
|
|
|
86 |
|
87 |
-
contextualized_chunks =
|
88 |
|
89 |
return contextualized_chunks
|
90 |
-
|
91 |
-
# def task(self, name, barrier, queue, chunk, full_text):
|
92 |
-
# print(f"Process {name} ready")
|
93 |
-
# barrier.wait() # Wait for all processes to be ready
|
94 |
-
# result = self.create_contextualized_chunk(chunk, full_text)
|
95 |
-
# queue.put(result) # Store the result in the queue
|
96 |
-
|
97 |
-
def main(self, chunks, full_text):
|
98 |
-
barrier = Barrier(1)
|
99 |
-
queue = Queue()
|
100 |
-
processes = []
|
101 |
-
|
102 |
-
for i in range(len(chunks)):
|
103 |
-
p = Process(
|
104 |
-
target=task,
|
105 |
-
args=(
|
106 |
-
f"P{i+1}",
|
107 |
-
barrier,
|
108 |
-
queue,
|
109 |
-
chunks[i],
|
110 |
-
full_text,
|
111 |
-
self.config,
|
112 |
-
self.claude_context_model,
|
113 |
-
),
|
114 |
-
)
|
115 |
-
processes.append(p)
|
116 |
-
p.start()
|
117 |
-
|
118 |
-
results = []
|
119 |
-
for p in processes:
|
120 |
-
p.join()
|
121 |
-
|
122 |
-
# Collect results from the queue
|
123 |
-
while not queue.empty():
|
124 |
-
print("queue.get(): ", queue.get())
|
125 |
-
results.append(queue.get())
|
126 |
-
|
127 |
-
return results
|
|
|
21 |
|
22 |
lista_contador = []
|
23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
class ContextualRetriever:
|
25 |
def __init__(
|
26 |
self, config: RetrievalConfig, claude_api_key: str, claude_context_model: str
|
|
|
31 |
self.bm25 = None
|
32 |
self.claude_context_model = claude_context_model
|
33 |
|
34 |
+
async def llm_generate_context(self, full_text: str, chunk: DocumentChunk) -> str:
|
35 |
"""Generate contextual description using ChatOpenAI"""
|
36 |
try:
|
|
|
37 |
print("COMEÇOU A REQUISIÇÃO")
|
38 |
+
prompt = contextual_prompt(full_text, chunk.content)
|
39 |
# response = claude_answer(self.claude_client, self.claude_context_model, prompt)
|
40 |
+
response = await gpt_answer(prompt)
|
41 |
return response
|
42 |
except Exception as e:
|
43 |
self.logger.error(
|
|
|
45 |
)
|
46 |
return ""
|
47 |
|
48 |
+
async def create_contextualized_chunk(self, chunk, full_text):
|
49 |
lista_contador.append(0)
|
50 |
print("contador: ", len(lista_contador))
|
51 |
page_content = ""
|
|
|
55 |
):
|
56 |
page_content += full_text[i].page_content if full_text[i] else ""
|
57 |
|
58 |
+
context = await self.llm_generate_context(page_content, chunk)
|
59 |
return ContextualizedChunk(
|
60 |
content=chunk.content,
|
61 |
page_number=chunk.page_number,
|
|
|
65 |
context=context,
|
66 |
)
|
67 |
|
68 |
+
async def contextualize_all_chunks(
|
69 |
self, full_text: List[Document], chunks: List[DocumentChunk]
|
70 |
) -> List[ContextualizedChunk]:
|
71 |
"""Add context to all chunks"""
|
72 |
contextualized_chunks = []
|
73 |
|
74 |
+
async with asyncio.TaskGroup() as tg:
|
75 |
+
tasks = [
|
76 |
+
tg.create_task(self.create_contextualized_chunk(chunk, full_text))
|
77 |
+
for chunk in chunks
|
78 |
+
]
|
79 |
|
80 |
+
contextualized_chunks = [task.result() for task in tasks]
|
81 |
|
82 |
return contextualized_chunks
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
_utils/gerar_relatorio_modelo_usuario/llm_calls.py
CHANGED
@@ -14,11 +14,12 @@ def claude_answer(claude_client, claude_context_model, prompt):
|
|
14 |
].text # O response.content é uma lista pois é passada uma lista de mensagens, e também retornado uma lista de mensagens, sendo a primeira a mais recente, que é a resposta do model
|
15 |
|
16 |
|
17 |
-
def gpt_answer(prompt):
|
18 |
gpt = ChatOpenAI(
|
19 |
temperature=0,
|
20 |
model="gpt-4o-mini",
|
21 |
api_key=os.environ.get("OPENAI_API_KEY"),
|
|
|
22 |
)
|
23 |
-
response = gpt.
|
24 |
return response.content
|
|
|
14 |
].text # O response.content é uma lista pois é passada uma lista de mensagens, e também retornado uma lista de mensagens, sendo a primeira a mais recente, que é a resposta do model
|
15 |
|
16 |
|
17 |
+
async def gpt_answer(prompt):
|
18 |
gpt = ChatOpenAI(
|
19 |
temperature=0,
|
20 |
model="gpt-4o-mini",
|
21 |
api_key=os.environ.get("OPENAI_API_KEY"),
|
22 |
+
max_retries=5,
|
23 |
)
|
24 |
+
response = await gpt.ainvoke([HumanMessage(content=prompt)])
|
25 |
return response.content
|
_utils/resumo_completo_cursor.py
CHANGED
@@ -34,7 +34,7 @@ os.environ.get("LANGCHAIN_API_KEY")
|
|
34 |
os.environ["LANGCHAIN_PROJECT"] = "VELLA"
|
35 |
|
36 |
|
37 |
-
def get_llm_summary_answer_by_cursor_complete(
|
38 |
serializer, listaPDFs=None, contexto=None
|
39 |
):
|
40 |
"""Parâmetro "contexto" só deve ser passado quando quiser utilizar o teste com ragas, e assim, não quiser passar PDFs"""
|
@@ -89,12 +89,12 @@ def get_llm_summary_answer_by_cursor_complete(
|
|
89 |
full_text = " ".join([page.page_content for page in pages])
|
90 |
# Contextualize chunks
|
91 |
if serializer["should_have_contextual_chunks"]:
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
is_contextualized_chunk = True
|
99 |
else:
|
100 |
chunks_passados = allPdfsChunks
|
@@ -136,7 +136,7 @@ Não há outras causas interruptivas ou suspensivas da prescrição.
|
|
136 |
</formato>
|
137 |
"""
|
138 |
# Generate enhanced summary
|
139 |
-
structured_summaries = summarizer.generate_enhanced_summary(
|
140 |
vector_store,
|
141 |
bm25,
|
142 |
chunk_ids
|
@@ -145,11 +145,18 @@ Não há outras causas interruptivas ou suspensivas da prescrição.
|
|
145 |
prompt_relatorio_sem_context,
|
146 |
)
|
147 |
|
|
|
|
|
|
|
|
|
|
|
148 |
# Output results as JSON
|
149 |
-
json_output = json.dumps(structured_summaries, indent=2)
|
150 |
-
print("\nStructured Summaries:")
|
151 |
-
print(json_output)
|
152 |
texto_completo = ""
|
|
|
|
|
153 |
for x in structured_summaries:
|
154 |
texto_completo = texto_completo + x["content"] + "\n"
|
155 |
return {
|
|
|
34 |
os.environ["LANGCHAIN_PROJECT"] = "VELLA"
|
35 |
|
36 |
|
37 |
+
async def get_llm_summary_answer_by_cursor_complete(
|
38 |
serializer, listaPDFs=None, contexto=None
|
39 |
):
|
40 |
"""Parâmetro "contexto" só deve ser passado quando quiser utilizar o teste com ragas, e assim, não quiser passar PDFs"""
|
|
|
89 |
full_text = " ".join([page.page_content for page in pages])
|
90 |
# Contextualize chunks
|
91 |
if serializer["should_have_contextual_chunks"]:
|
92 |
+
contextualized_chunks = (
|
93 |
+
await summarizer.contextual_retriever.contextualize_all_chunks(
|
94 |
+
pages, allPdfsChunks
|
95 |
+
)
|
96 |
+
)
|
97 |
+
chunks_passados = contextualized_chunks
|
98 |
is_contextualized_chunk = True
|
99 |
else:
|
100 |
chunks_passados = allPdfsChunks
|
|
|
136 |
</formato>
|
137 |
"""
|
138 |
# Generate enhanced summary
|
139 |
+
structured_summaries = await summarizer.generate_enhanced_summary(
|
140 |
vector_store,
|
141 |
bm25,
|
142 |
chunk_ids
|
|
|
145 |
prompt_relatorio_sem_context,
|
146 |
)
|
147 |
|
148 |
+
if not isinstance(structured_summaries, list):
|
149 |
+
from rest_framework.response import Response
|
150 |
+
|
151 |
+
return Response({"erro": structured_summaries})
|
152 |
+
|
153 |
# Output results as JSON
|
154 |
+
# json_output = json.dumps(structured_summaries, indent=2)
|
155 |
+
# print("\nStructured Summaries:")
|
156 |
+
# print(json_output)
|
157 |
texto_completo = ""
|
158 |
+
print("\n\n\n")
|
159 |
+
print("structured_summaries: ", structured_summaries)
|
160 |
for x in structured_summaries:
|
161 |
texto_completo = texto_completo + x["content"] + "\n"
|
162 |
return {
|
gerar_relatorio_modelo_usuario/views.py
CHANGED
@@ -13,13 +13,13 @@ from rest_framework.parsers import MultiPartParser
|
|
13 |
from drf_spectacular.utils import extend_schema
|
14 |
|
15 |
|
16 |
-
class ResumoSimplesCursorCompletoView(
|
17 |
parser_classes = [MultiPartParser]
|
18 |
|
19 |
@extend_schema(
|
20 |
request=ResumoCursorCompeltoSerializer,
|
21 |
)
|
22 |
-
def post(self, request):
|
23 |
serializer = ResumoCursorCompeltoSerializer(data=request.data)
|
24 |
if serializer.is_valid(raise_exception=True):
|
25 |
print("\n\n\n")
|
@@ -44,7 +44,12 @@ class ResumoSimplesCursorCompletoView(APIView):
|
|
44 |
listaPDFs.append(temp_file_path)
|
45 |
print("listaPDFs: ", listaPDFs)
|
46 |
|
47 |
-
resposta_llm = get_llm_summary_answer_by_cursor_complete(
|
|
|
|
|
|
|
|
|
|
|
48 |
|
49 |
final = resposta_llm
|
50 |
print("\n\n\n")
|
|
|
13 |
from drf_spectacular.utils import extend_schema
|
14 |
|
15 |
|
16 |
+
class ResumoSimplesCursorCompletoView(AsyncAPIView):
|
17 |
parser_classes = [MultiPartParser]
|
18 |
|
19 |
@extend_schema(
|
20 |
request=ResumoCursorCompeltoSerializer,
|
21 |
)
|
22 |
+
async def post(self, request):
|
23 |
serializer = ResumoCursorCompeltoSerializer(data=request.data)
|
24 |
if serializer.is_valid(raise_exception=True):
|
25 |
print("\n\n\n")
|
|
|
44 |
listaPDFs.append(temp_file_path)
|
45 |
print("listaPDFs: ", listaPDFs)
|
46 |
|
47 |
+
resposta_llm = await get_llm_summary_answer_by_cursor_complete(
|
48 |
+
data, listaPDFs
|
49 |
+
)
|
50 |
+
|
51 |
+
print("\n\n\n")
|
52 |
+
print("resposta_llm: ", resposta_llm)
|
53 |
|
54 |
final = resposta_llm
|
55 |
print("\n\n\n")
|