lucas-wa commited on
Commit
6df5942
·
0 Parent(s):

Adding server

Browse files
Files changed (2) hide show
  1. server/app.py +402 -0
  2. server/requirements.txt +5 -0
server/app.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import time
4
+ from langchain_core.documents import Document
5
+ from langchain_community.document_loaders import TextLoader
6
+ from langchain.vectorstores import Chroma
7
+ from langchain_text_splitters import CharacterTextSplitter
8
+ from langchain import PromptTemplate, LLMChain
9
+ from langchain.schema.runnable import RunnablePassthrough
10
+ from langchain.schema import StrOutputParser
11
+ from langchain_google_genai import ChatGoogleGenerativeAI
12
+ from langchain_google_genai import GoogleGenerativeAIEmbeddings
13
+ from langchain.chains.query_constructor.base import AttributeInfo
14
+ from langchain.retrievers.self_query.base import SelfQueryRetriever
15
+ from langchain.output_parsers import ResponseSchema, StructuredOutputParser
16
+ from langchain.prompts import ChatPromptTemplate
17
+ from langchain_core.runnables import RunnableLambda
18
+
19
+ GOOGLE_API_KEY=""
20
+
21
+ if "GOOGLE_API_KEY" not in os.environ:
22
+ os.environ["GOOGLE_API_KEY"] = GOOGLE_API_KEY
23
+
24
+ loader = TextLoader("/content/banco_de_questoes_v3.txt").load()
25
+
26
+ gemini_embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
27
+
28
+
29
+ # db = Chroma.from_documents(documents, gemini_embeddings)
30
+ # vectorstore = Chroma.from_documents(
31
+ # documents=documents,
32
+ # embedding=gemini_embeddings,
33
+ # persist_directory="./chroma_db"
34
+ # )
35
+ # vectorstore_disk = Chroma(
36
+ # persist_directory="./chroma_db",
37
+ # embedding_function=gemini_embeddings
38
+ # )
39
+ # retriever = vectorstore_disk.as_retriever(search_kwargs={"k": 10})
40
+
41
+ questions = list(map(lambda x: "##Questão" + x, loader[0].page_content.split("##Questão")))
42
+
43
+ def parse_question(question_str):
44
+ # Extract content
45
+ content_start = question_str.find('"""') + 3
46
+ content_end = question_str.rfind('"""', content_start)
47
+ content = question_str[content_start:content_end].strip()
48
+
49
+ # Extract correct option
50
+ correct_option_start = question_str.find('opcao_correta=') + 15
51
+ correct_option_end = correct_option_start + 1
52
+ correct_option = question_str[correct_option_start:correct_option_end]
53
+
54
+ # Extract metadata
55
+ metadata_start = question_str.find("metadados=") + 10
56
+ metadata_end = question_str.find("}", metadata_start) + 1
57
+ metadata_str = question_str[metadata_start:metadata_end]
58
+ metadata = eval(metadata_str)
59
+
60
+ topico, assunto, dificuldade, tipo = metadata.values()
61
+
62
+ return Document(page_content="##Questão\n" + content, metadata={"correct_option":correct_option, "topico":topico, "assunto":assunto, "dificuldade":dificuldade, "tipo":tipo})
63
+
64
+ # Lista para armazenar os documentos
65
+ docs = []
66
+
67
+ for question in questions:
68
+ try:
69
+ docs.append(parse_question(question))
70
+ except Exception as e:
71
+ print(e, question)
72
+
73
+ docs[0]
74
+
75
+
76
+ db = Chroma.from_documents(docs, gemini_embeddings)
77
+ vectorstore = Chroma.from_documents(
78
+ documents=docs,
79
+ embedding=gemini_embeddings,
80
+ persist_directory="./chroma_db"
81
+ )
82
+ vectorstore_disk = Chroma(
83
+ persist_directory="./chroma_db",
84
+ embedding_function=gemini_embeddings
85
+ )
86
+ metadata_field_info = [
87
+ AttributeInfo(
88
+ name="topico",
89
+ description="A materia escolar da qual a questão pertence.",
90
+ type="string",
91
+ ),
92
+ AttributeInfo(
93
+ name="assunto",
94
+ description="O assunto da materia fornecida anteriormente.",
95
+ type="string",
96
+ ),
97
+ AttributeInfo(
98
+ name="dificuldade",
99
+ description="O nivel de dificuldade para resolver a questao.",
100
+ type="string",
101
+ ),
102
+ AttributeInfo(
103
+ name="tipo",
104
+ description="O tipo da questao. Pode ser ou Multipla Escolha ou Justificativa",
105
+ type="string",
106
+ ),
107
+ ]
108
+ document_content_description = "Questões de biologia"
109
+ llm = ChatGoogleGenerativeAI(model="gemini-pro",
110
+ temperature=0.7, top_p=1)
111
+ retriever = SelfQueryRetriever.from_llm(
112
+ llm, vectorstore, document_content_description, metadata_field_info, verbose=True
113
+ )
114
+
115
+ print(len(retriever.get_relevant_documents("MMLU")))
116
+
117
+ llm_prompt_template = """Olá, sou uma IA treinada para gerar conteúdo educacional. Por favor, gere cinco questões de múltipla escolha sobre o seguinte tema:
118
+ Instruções para cada questão:
119
+ - Crie uma questão clara e relevante para o tema.
120
+ - Forneça cinco opções de resposta, rotuladas de A) a E).
121
+ - Apenas uma das opções de resposta deve ser correta.
122
+ - Indique a resposta correta ao final de cada questão.
123
+
124
+ Exemplo de uma questão:
125
+ Tema: Fotossíntese
126
+
127
+ Questão:
128
+ Qual é o pigmento primário responsável pela fotossíntese nas plantas?
129
+
130
+ Opções de Resposta:
131
+ A) Clorofila
132
+ B) Hemoglobina
133
+ C) Mioglobina
134
+ D) Citocromo
135
+ E) Queratina
136
+
137
+ Resposta Correta:
138
+ A) Clorofila
139
+
140
+ Context: {context}
141
+ Question: {question}
142
+ Answer:
143
+
144
+
145
+ {format_questions_instructions}
146
+ GIVE ME THE FIVE QUESTIONS SEPARATED IN AN ARRAY
147
+ """
148
+
149
+ llm_prompt = PromptTemplate.from_template(llm_prompt_template)
150
+
151
+ print(llm_prompt)
152
+
153
+
154
+ questions_template = ChatPromptTemplate.from_template(template=llm_prompt_template)
155
+
156
+ questions_chain = LLMChain(llm=llm, prompt=questions_template)
157
+
158
+ questions_schema = ResponseSchema(
159
+ name="questions",
160
+ description="""Give the questions in json as an array""",
161
+ )
162
+
163
+ questions_schemas = [questions_schema]
164
+
165
+ questions_parser = StructuredOutputParser.from_response_schemas(questions_schemas)
166
+ format_questions_instructions = questions_parser.get_format_instructions()
167
+
168
+ print(format_questions_instructions)
169
+
170
+ def get_questions(_dict):
171
+ question = _dict["question"]
172
+ context = _dict["context"]
173
+ messages = questions_template.format_messages(
174
+ context=context,
175
+ question=question,
176
+ format_questions_instructions=format_questions_instructions,
177
+ )
178
+
179
+ chat = ChatGoogleGenerativeAI(model="gemini-pro")
180
+ response = chat.invoke(messages)
181
+ return questions_parser.parse(response.content)
182
+
183
+
184
+
185
+ def format_docs(docs):
186
+ return "\n\n".join(doc.page_content for doc in docs)
187
+
188
+
189
+ # llm = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.7, top_p=1)
190
+ rag_chain = (
191
+ {"context": retriever | RunnableLambda(format_docs),
192
+ "question": RunnablePassthrough()}
193
+ | RunnableLambda(get_questions)
194
+ )
195
+
196
+ retriever
197
+
198
+ start_time = time.time()
199
+ assunto = "Bioquimica e Biofisica"
200
+ query = f"Quero que você gere questões de biologia, sendo do assunto: {assunto}."
201
+ print(rag_chain.invoke(f"""{query}"""))
202
+ end_time = time.time()
203
+ execution_time = end_time - start_time
204
+ print(f"Tempo de execução: {execution_time:.2f} segundos.")
205
+
206
+ assunto = "Bioquimica e Biofisica"
207
+ query = f"Quero que você gere questões de biologia, sendo do assunto: {assunto}."
208
+ res = rag_chain.invoke(f"""{query}""")
209
+
210
+ res["questions"][0]
211
+
212
+ docs = retriever.invoke(f"{query}")
213
+ for doc in docs:
214
+ print(doc)
215
+ print()
216
+
217
+ """###PIPELINE 2
218
+
219
+ """
220
+
221
+
222
+
223
+
224
+ class Document:
225
+ def __init__(self, page_content, metadata):
226
+ self.page_content = page_content
227
+ self.metadata = metadata
228
+
229
+ def parse_document(text):
230
+ regex = r"Document\(\n\s+conteudo=\n\"{3}([^`]+?)\"{3}\n,\n\s+opcao_correta=\"(\w+)\"\,\n\s+metadados=\{([^}]+)\}\n\)"
231
+ matches = re.finditer(regex, text, re.DOTALL)
232
+ documents = []
233
+ for match in matches:
234
+ page_content = match.group(1).strip()
235
+ metadata_text = match.group(3).strip()
236
+ metadata = {}
237
+ metadata_entries = metadata_text.split(', ')
238
+ for entry in metadata_entries:
239
+ key, value = entry.split(': ')
240
+ metadata[key.strip("'")] = value.strip("'")
241
+
242
+ document = Document(page_content, metadata)
243
+ documents.append(document)
244
+
245
+ return documents
246
+
247
+ with open('/content/banco_de_questoes_v2.txt', 'r', encoding='utf-8') as file:
248
+ txt_data = file.read()
249
+
250
+ docs = parse_document(txt_data)
251
+
252
+ gemini_embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
253
+
254
+ db = Chroma.from_documents(docs, gemini_embeddings)
255
+ vectorstore = Chroma.from_documents(
256
+ documents=docs,
257
+ embedding=gemini_embeddings,
258
+ persist_directory="./chroma_db"
259
+ )
260
+ vectorstore_disk = Chroma(
261
+ persist_directory="./chroma_db",
262
+ embedding_function=gemini_embeddings
263
+ )
264
+
265
+ metadata_field_info = [
266
+ AttributeInfo(
267
+ name="topico",
268
+ description="A materia escolar da qual a questão pertence.",
269
+ type="string",
270
+ ),
271
+ AttributeInfo(
272
+ name="assunto",
273
+ description="O assunto da materia fornecida anteriormente.",
274
+ type="string",
275
+ ),
276
+ AttributeInfo(
277
+ name="dificuldade",
278
+ description="O nivel de dificuldade para resolver a questao.",
279
+ type="string",
280
+ ),
281
+ AttributeInfo(
282
+ name="tipo",
283
+ description="O tipo da questao. Pode ser ou Multipla Escolha ou Justificativa",
284
+ type="string",
285
+ ),
286
+ ]
287
+ document_content_description = "Questões de biologia"
288
+ llm = ChatGoogleGenerativeAI(model="gemini-pro",
289
+ temperature=0.7, top_p=1)
290
+ retriever = SelfQueryRetriever.from_llm(
291
+ llm, vectorstore, document_content_description, metadata_field_info, verbose=True
292
+ )
293
+ retriever.invoke("Qual é a importância das células")
294
+
295
+ """###PIPELINE 3
296
+
297
+ """
298
+
299
+
300
+
301
+ loader = TextLoader("/content/banco_de_questoes_v2.txt").load()
302
+
303
+ gemini_embeddings = GoogleGenerativeAIEmbeddings(model="models/embedding-001")
304
+
305
+ text_splitter = CharacterTextSplitter(chunk_size=1024, chunk_overlap=0)
306
+ documents = text_splitter.split_documents(loader)
307
+ db = Chroma.from_documents(documents, gemini_embeddings)
308
+ vectorstore = Chroma.from_documents(
309
+ documents=documents,
310
+ embedding=gemini_embeddings,
311
+ persist_directory="./chroma_db"
312
+ )
313
+ vectorstore_disk = Chroma(
314
+ persist_directory="./chroma_db",
315
+ embedding_function=gemini_embeddings
316
+ )
317
+ metadata_field_info = [
318
+ AttributeInfo(
319
+ name="topico",
320
+ description="A materia escolar da qual a questão pertence.",
321
+ type="string",
322
+ ),
323
+ AttributeInfo(
324
+ name="assunto",
325
+ description="O assunto da materia fornecida anteriormente.",
326
+ type="string",
327
+ ),
328
+ AttributeInfo(
329
+ name="dificuldade",
330
+ description="O nivel de dificuldade para resolver a questao.",
331
+ type="string",
332
+ ),
333
+ AttributeInfo(
334
+ name="tipo",
335
+ description="O tipo da questao. Pode ser ou Multipla Escolha ou Justificativa",
336
+ type="string",
337
+ ),
338
+ ]
339
+ document_content_description = "Questões de biologia"
340
+ llm = ChatGoogleGenerativeAI(model="gemini-pro",
341
+ temperature=0.7, top_p=1)
342
+ retriever = SelfQueryRetriever.from_llm(
343
+ llm, vectorstore, document_content_description, metadata_field_info, verbose=True
344
+ )
345
+
346
+ print(len(retriever.get_relevant_documents("MMLU")))
347
+
348
+ llm_prompt_template = """Olá, sou uma IA treinada para gerar conteúdo educacional. Por favor, gere cinco questões de múltipla escolha sobre o seguinte tema:
349
+ Instruções para cada questão:
350
+ - Crie uma questão clara e relevante para o tema.
351
+ - Forneça cinco opções de resposta, rotuladas de A) a E).
352
+ - Apenas uma das opções de resposta deve ser correta.
353
+ - Indique a resposta correta ao final de cada questão.
354
+
355
+ Exemplo de uma questão:
356
+ Tema: Fotossíntese
357
+
358
+ Questão:
359
+ Qual é o pigmento primário responsável pela fotossíntese nas plantas?
360
+
361
+ Opções de Resposta:
362
+ A) Clorofila
363
+ B) Hemoglobina
364
+ C) Mioglobina
365
+ D) Citocromo
366
+ E) Queratina
367
+
368
+ Resposta Correta:
369
+ A) Clorofila
370
+
371
+ Context: {context}
372
+ Question: {question}
373
+ Answer:
374
+ """
375
+
376
+ llm_prompt = PromptTemplate.from_template(llm_prompt_template)
377
+
378
+ print(llm_prompt)
379
+
380
+ def format_docs(docs):
381
+ return "\n\n".join(doc.page_content for doc in docs)
382
+ llm = ChatGoogleGenerativeAI(model="gemini-pro",
383
+ temperature=0.7, top_p=1)
384
+ rag_chain = (
385
+ {"context": retriever | format_docs, "question": RunnablePassthrough()}
386
+ | llm_prompt
387
+ | llm
388
+ | StrOutputParser()
389
+ )
390
+
391
+ start_time = time.time()
392
+ assunto = "citologia"
393
+ query = f"Preciso de cinco questões de biologia, sendo do assunto: {assunto}."
394
+ print(rag_chain.invoke(f"""
395
+ {query}
396
+ """))
397
+ end_time = time.time()
398
+ execution_time = end_time - start_time
399
+ print(f"Tempo de execução: {execution_time:.2f} segundos.")
400
+ docs = retriever.invoke(f"{query}")
401
+ len(docs)
402
+ print(docs)
server/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ langchain==0.1.6
2
+ langchain_google_genai
3
+ chromadb
4
+ langchain_text_splitters
5
+ lark