Spaces:
Sleeping

douglasribeiro commited on
Commit
9ede463
·
verified ·
1 Parent(s): 0148223

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +344 -269
app.py CHANGED
@@ -1,270 +1,345 @@
1
- import os
2
- import zipfile
3
- import tempfile
4
- import shutil
5
- from pathlib import Path
6
- from typing import List
7
-
8
- import requests
9
- import gradio as gr
10
- from bs4 import BeautifulSoup
11
-
12
- from langchain.schema import Document
13
- from langchain.text_splitter import RecursiveCharacterTextSplitter
14
- from langchain.prompts import ChatPromptTemplate
15
- from langchain_community.document_loaders import PyPDFLoader
16
- from langchain_community.vectorstores import FAISS
17
- from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
18
-
19
- # =========================
20
- # CONFIG
21
- # =========================
22
- BASE_DIR = Path(__file__).parent
23
- DATA_DIR = BASE_DIR / "data"
24
- DOCS_DIR = BASE_DIR / "python_docs"
25
- VECTOR_DIR = BASE_DIR / "vectorstore"
26
-
27
- APOSTILA_PATH = DATA_DIR / "apostila.pdf"
28
- PYTHON_DOCS_DOWNLOAD_PAGE = "https://docs.python.org/3/download.html"
29
-
30
- GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
31
-
32
- if not GOOGLE_API_KEY:
33
- raise ValueError("Defina a variável de ambiente GOOGLE_API_KEY nas Settings do Space.")
34
-
35
- # =========================
36
- # DOWNLOAD DA DOCUMENTAÇÃO
37
- # =========================
38
- def encontrar_link_zip_documentacao() -> str:
39
- """
40
- Lê a página oficial de download da documentação do Python
41
- e encontra o link do arquivo HTML .zip.
42
- """
43
- resp = requests.get(PYTHON_DOCS_DOWNLOAD_PAGE, timeout=60)
44
- resp.raise_for_status()
45
-
46
- soup = BeautifulSoup(resp.text, "html.parser")
47
-
48
- for a in soup.find_all("a", href=True):
49
- href = a["href"]
50
- texto = a.get_text(" ", strip=True).lower()
51
-
52
- # procura algo como html + zip
53
- if ("zip" in href.lower()) and ("html" in href.lower() or "html" in texto):
54
- if href.startswith("http"):
55
- return href
56
- return requests.compat.urljoin(PYTHON_DOCS_DOWNLOAD_PAGE, href)
57
-
58
- raise RuntimeError("Não foi possível localizar o ZIP HTML da documentação oficial do Python.")
59
-
60
- def baixar_e_extrair_docs_python(destino: Path):
61
- """
62
- Baixa o ZIP HTML da documentação oficial do Python e extrai.
63
- """
64
- if destino.exists() and any(destino.rglob("*.html")):
65
- return
66
-
67
- destino.mkdir(parents=True, exist_ok=True)
68
-
69
- url_zip = encontrar_link_zip_documentacao()
70
- zip_path = destino / "python_docs.zip"
71
-
72
- with requests.get(url_zip, stream=True, timeout=120) as r:
73
- r.raise_for_status()
74
- with open(zip_path, "wb") as f:
75
- for chunk in r.iter_content(chunk_size=8192):
76
- if chunk:
77
- f.write(chunk)
78
-
79
- with zipfile.ZipFile(zip_path, "r") as z:
80
- z.extractall(destino)
81
-
82
- zip_path.unlink(missing_ok=True)
83
-
84
- # =========================
85
- # LEITURA DOS DOCUMENTOS
86
- # =========================
87
- def limpar_html(html_text: str) -> str:
88
- soup = BeautifulSoup(html_text, "html.parser")
89
-
90
- for tag in soup(["script", "style", "nav", "footer", "header"]):
91
- tag.decompose()
92
-
93
- text = soup.get_text(separator="\n")
94
- lines = [line.strip() for line in text.splitlines()]
95
- lines = [line for line in lines if line]
96
- return "\n".join(lines)
97
-
98
- def carregar_apostila() -> List[Document]:
99
- docs = []
100
- if not APOSTILA_PATH.exists():
101
- return docs
102
-
103
- loader = PyPDFLoader(str(APOSTILA_PATH))
104
- pages = loader.load()
105
-
106
- for p in pages:
107
- p.metadata["source_type"] = "apostila"
108
- p.metadata["arquivo"] = APOSTILA_PATH.name
109
-
110
- docs.extend(pages)
111
- return docs
112
-
113
- def carregar_docs_python() -> List[Document]:
114
- docs = []
115
-
116
- for html_file in DOCS_DIR.rglob("*.html"):
117
- try:
118
- with open(html_file, "r", encoding="utf-8", errors="ignore") as f:
119
- html = f.read()
120
-
121
- text = limpar_html(html)
122
-
123
- if len(text) < 300:
124
- continue
125
-
126
- docs.append(
127
- Document(
128
- page_content=text,
129
- metadata={
130
- "source_type": "documentacao_python",
131
- "arquivo": html_file.name,
132
- "path": str(html_file),
133
- },
134
- )
135
- )
136
- except Exception:
137
- continue
138
-
139
- return docs
140
-
141
- # =========================
142
- # INDEXAÇÃO
143
- # =========================
144
- def construir_ou_carregar_vectorstore():
145
- embeddings = GoogleGenerativeAIEmbeddings(
146
- model="models/gemini-embedding-001",
147
- google_api_key=GOOGLE_API_KEY
148
- )
149
-
150
- if VECTOR_DIR.exists():
151
- try:
152
- vs = FAISS.load_local(
153
- str(VECTOR_DIR),
154
- embeddings,
155
- allow_dangerous_deserialization=True
156
- )
157
- return vs
158
- except Exception:
159
- shutil.rmtree(VECTOR_DIR, ignore_errors=True)
160
-
161
- baixar_e_extrair_docs_python(DOCS_DIR)
162
-
163
- docs_apostila = carregar_apostila()
164
- docs_python = carregar_docs_python()
165
-
166
- todos_docs = docs_apostila + docs_python
167
- if not todos_docs:
168
- raise RuntimeError("Nenhum documento foi carregado. Verifique a apostila e o download da documentação.")
169
-
170
- splitter = RecursiveCharacterTextSplitter(
171
- chunk_size=1200,
172
- chunk_overlap=200
173
- )
174
- chunks = splitter.split_documents(todos_docs)
175
-
176
- vs = FAISS.from_documents(chunks, embeddings)
177
- vs.save_local(str(VECTOR_DIR))
178
- return vs
179
-
180
- # =========================
181
- # LLM
182
- # =========================
183
- llm = ChatGoogleGenerativeAI(
184
- model="gemini-2.0-flash",
185
- temperature=0.2,
186
- google_api_key=GOOGLE_API_KEY
187
- )
188
-
189
- PROMPT = ChatPromptTemplate.from_template("""
190
- Você é um professor tutor especializado em Fundamentos de Python.
191
-
192
- Objetivo:
193
- - ensinar alunos iniciantes com linguagem clara e acolhedora;
194
- - responder com base prioritária na apostila do curso e na documentação oficial do Python;
195
- - quando o aluno pedir, explicar passo a passo;
196
- - sempre que possível, mostrar exemplos curtos;
197
- - ao final, sugerir um mini exercício.
198
-
199
- Regras:
200
- - se não houver base suficiente no contexto, diga isso claramente;
201
- - não invente sintaxe ou funções;
202
- - destaque as fontes usadas;
203
- - responda em português do Brasil.
204
-
205
- Contexto:
206
- {contexto}
207
-
208
- Pergunta do aluno:
209
- {pergunta}
210
- """)
211
-
212
- vectorstore = construir_ou_carregar_vectorstore()
213
- retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
214
-
215
- def formatar_contexto(docs: List[Document]) -> str:
216
- partes = []
217
- for i, doc in enumerate(docs, start=1):
218
- origem = doc.metadata.get("source_type", "desconhecido")
219
- arquivo = doc.metadata.get("arquivo", "arquivo_desconhecido")
220
- trecho = doc.page_content[:1600]
221
- partes.append(f"[Fonte {i} | {origem} | {arquivo}]\n{trecho}")
222
- return "\n\n".join(partes)
223
-
224
- def responder(mensagem, historico):
225
- docs = retriever.invoke(mensagem)
226
- contexto = formatar_contexto(docs)
227
-
228
- msgs = PROMPT.format_messages(
229
- contexto=contexto,
230
- pergunta=mensagem
231
- )
232
- resposta = llm.invoke(msgs).content
233
-
234
- fontes = []
235
- for d in docs:
236
- origem = d.metadata.get("source_type", "desconhecido")
237
- arquivo = d.metadata.get("arquivo", "arquivo_desconhecido")
238
- fontes.append(f"- {origem}: {arquivo}")
239
-
240
- resposta += "\n\n**Fontes consultadas:**\n" + "\n".join(sorted(set(fontes)))
241
- return resposta
242
-
243
- def reconstruir_base():
244
- shutil.rmtree(VECTOR_DIR, ignore_errors=True)
245
- shutil.rmtree(DOCS_DIR, ignore_errors=True)
246
-
247
- global vectorstore, retriever
248
- vectorstore = construir_ou_carregar_vectorstore()
249
- retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
250
- return "Base reconstruída com sucesso."
251
-
252
- with gr.Blocks(title="Tutor de Fundamentos de Python") as demo:
253
- gr.Markdown("# Tutor de Fundamentos de Python")
254
- gr.Markdown(
255
- "Este tutor responde com base na sua apostila e na documentação oficial do Python."
256
- )
257
-
258
- with gr.Row():
259
- btn_rebuild = gr.Button("Reconstruir base")
260
- status = gr.Textbox(label="Status", interactive=False)
261
-
262
- chat = gr.ChatInterface(
263
- fn=responder,
264
- type="messages"
265
- )
266
-
267
- btn_rebuild.click(fn=reconstruir_base, outputs=status)
268
-
269
- if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  demo.launch()
 
1
+ import os
2
+ import zipfile
3
+ import shutil
4
+ from pathlib import Path
5
+ from typing import List, Tuple
6
+
7
+ import requests
8
+ import gradio as gr
9
+ from bs4 import BeautifulSoup
10
+
11
+ from langchain.schema import Document
12
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
13
+ from langchain.prompts import ChatPromptTemplate
14
+ from langchain_community.document_loaders import PyPDFLoader
15
+ from langchain_community.vectorstores import FAISS
16
+ from langchain_community.embeddings import HuggingFaceEmbeddings
17
+ from langchain_google_genai import ChatGoogleGenerativeAI
18
+
19
+ # =========================
20
+ # CONFIGURAÇÕES GERAIS
21
+ # =========================
22
+ BASE_DIR = Path(__file__).parent
23
+ DATA_DIR = BASE_DIR / "data"
24
+ DOCS_DIR = BASE_DIR / "python_docs"
25
+ VECTOR_DIR = BASE_DIR / "vectorstore"
26
+
27
+ APOSTILA_PATH = DATA_DIR / "apostila.pdf"
28
+ PYTHON_DOCS_DOWNLOAD_PAGE = "https://docs.python.org/3/download.html"
29
+
30
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
31
+
32
+ if not GOOGLE_API_KEY:
33
+ raise ValueError(
34
+ "A variável de ambiente GOOGLE_API_KEY não foi encontrada. "
35
+ "Configure essa secret nas Settings do Space."
36
+ )
37
+
38
+ # Partes da documentação do Python mais úteis para fundamentos
39
+ DOC_PATH_FILTERS = [
40
+ "tutorial",
41
+ "library/functions",
42
+ "library/stdtypes",
43
+ "reference/expressions",
44
+ "reference/simple_stmts",
45
+ ]
46
+
47
+ # Estado global simples
48
+ vectorstore = None
49
+ retriever = None
50
+ status_inicializacao = "Base ainda não carregada."
51
+
52
+ # =========================
53
+ # MODELOS
54
+ # =========================
55
+ def criar_embeddings():
56
+ # Embeddings locais: evita estourar a cota do Gemini
57
+ return HuggingFaceEmbeddings(
58
+ model_name="sentence-transformers/all-MiniLM-L6-v2"
59
+ )
60
+
61
+ def criar_llm():
62
+ return ChatGoogleGenerativeAI(
63
+ model="gemini-2.0-flash",
64
+ temperature=0.2,
65
+ google_api_key=GOOGLE_API_KEY
66
+ )
67
+
68
+ llm = criar_llm()
69
+
70
+ PROMPT = ChatPromptTemplate.from_template("""
71
+ Você é um professor tutor especializado em Fundamentos de Python.
72
+
73
+ Objetivo:
74
+ - ensinar alunos iniciantes com linguagem clara, paciente e didática;
75
+ - responder com base prioritária na apostila do curso e na documentação oficial do Python;
76
+ - explicar passo a passo quando necessário;
77
+ - mostrar exemplos curtos e corretos;
78
+ - ao final, sugerir um mini exercício prático.
79
+
80
+ Regras:
81
+ - se não houver base suficiente no contexto, diga isso claramente;
82
+ - não invente sintaxe, funções ou recursos inexistentes;
83
+ - destaque as fontes consultadas;
84
+ - responda em português do Brasil;
85
+ - quando relevante, corrija conceitos errados com delicadeza.
86
+
87
+ Contexto:
88
+ {contexto}
89
+
90
+ Pergunta do aluno:
91
+ {pergunta}
92
+ """)
93
+
94
+ # =========================
95
+ # DOWNLOAD DA DOCUMENTAÇÃO
96
+ # =========================
97
+ def encontrar_link_zip_documentacao() -> str:
98
+ """
99
+ Encontra automaticamente o link do ZIP HTML da documentação oficial do Python.
100
+ """
101
+ resp = requests.get(PYTHON_DOCS_DOWNLOAD_PAGE, timeout=60)
102
+ resp.raise_for_status()
103
+
104
+ soup = BeautifulSoup(resp.text, "html.parser")
105
+
106
+ for a in soup.find_all("a", href=True):
107
+ href = a["href"]
108
+ texto = a.get_text(" ", strip=True).lower()
109
+
110
+ if ("zip" in href.lower()) and ("html" in href.lower() or "html" in texto):
111
+ if href.startswith("http"):
112
+ return href
113
+ return requests.compat.urljoin(PYTHON_DOCS_DOWNLOAD_PAGE, href)
114
+
115
+ raise RuntimeError(
116
+ "Não foi possível localizar automaticamente o ZIP HTML da documentação oficial do Python."
117
+ )
118
+
119
+ def baixar_e_extrair_docs_python(destino: Path):
120
+ """
121
+ Baixa e extrai a documentação oficial do Python em HTML.
122
+ """
123
+ if destino.exists() and any(destino.rglob("*.html")):
124
+ return
125
+
126
+ destino.mkdir(parents=True, exist_ok=True)
127
+
128
+ url_zip = encontrar_link_zip_documentacao()
129
+ zip_path = destino / "python_docs.zip"
130
+
131
+ with requests.get(url_zip, stream=True, timeout=180) as r:
132
+ r.raise_for_status()
133
+ with open(zip_path, "wb") as f:
134
+ for chunk in r.iter_content(chunk_size=8192):
135
+ if chunk:
136
+ f.write(chunk)
137
+
138
+ with zipfile.ZipFile(zip_path, "r") as z:
139
+ z.extractall(destino)
140
+
141
+ zip_path.unlink(missing_ok=True)
142
+
143
+ # =========================
144
+ # LEITURA E LIMPEZA
145
+ # =========================
146
+ def limpar_html(html_text: str) -> str:
147
+ soup = BeautifulSoup(html_text, "html.parser")
148
+
149
+ for tag in soup(["script", "style", "nav", "footer", "header", "aside"]):
150
+ tag.decompose()
151
+
152
+ text = soup.get_text(separator="\n")
153
+ lines = [line.strip() for line in text.splitlines()]
154
+ lines = [line for line in lines if line]
155
+ return "\n".join(lines)
156
+
157
+ def arquivo_html_eh_relevante(html_file: Path) -> bool:
158
+ path_str = str(html_file).replace("\\", "/").lower()
159
+ return any(filtro in path_str for filtro in DOC_PATH_FILTERS)
160
+
161
+ def carregar_apostila() -> List[Document]:
162
+ docs = []
163
+
164
+ if not APOSTILA_PATH.exists():
165
+ return docs
166
+
167
+ loader = PyPDFLoader(str(APOSTILA_PATH))
168
+ pages = loader.load()
169
+
170
+ for page in pages:
171
+ page.metadata["source_type"] = "apostila"
172
+ page.metadata["arquivo"] = APOSTILA_PATH.name
173
+
174
+ docs.extend(pages)
175
+ return docs
176
+
177
+ def carregar_docs_python() -> List[Document]:
178
+ docs = []
179
+
180
+ for html_file in DOCS_DIR.rglob("*.html"):
181
+ if not arquivo_html_eh_relevante(html_file):
182
+ continue
183
+
184
+ try:
185
+ with open(html_file, "r", encoding="utf-8", errors="ignore") as f:
186
+ html = f.read()
187
+
188
+ text = limpar_html(html)
189
+
190
+ if len(text) < 300:
191
+ continue
192
+
193
+ docs.append(
194
+ Document(
195
+ page_content=text,
196
+ metadata={
197
+ "source_type": "documentacao_python",
198
+ "arquivo": html_file.name,
199
+ "path": str(html_file),
200
+ },
201
+ )
202
+ )
203
+ except Exception:
204
+ continue
205
+
206
+ return docs
207
+
208
+ # =========================
209
+ # CONSTRUÇÃO DA BASE
210
+ # =========================
211
+ def construir_ou_carregar_vectorstore() -> Tuple[FAISS, str]:
212
+ embeddings = criar_embeddings()
213
+
214
+ if VECTOR_DIR.exists():
215
+ try:
216
+ vs = FAISS.load_local(
217
+ str(VECTOR_DIR),
218
+ embeddings,
219
+ allow_dangerous_deserialization=True
220
+ )
221
+ return vs, "Base carregada do índice local."
222
+ except Exception:
223
+ shutil.rmtree(VECTOR_DIR, ignore_errors=True)
224
+
225
+ baixar_e_extrair_docs_python(DOCS_DIR)
226
+
227
+ docs_apostila = carregar_apostila()
228
+ docs_python = carregar_docs_python()
229
+ todos_docs = docs_apostila + docs_python
230
+
231
+ if not todos_docs:
232
+ raise RuntimeError(
233
+ "Nenhum documento foi carregado. Verifique se a apostila está em /data/apostila.pdf "
234
+ "e se o download da documentação foi concluído."
235
+ )
236
+
237
+ splitter = RecursiveCharacterTextSplitter(
238
+ chunk_size=1000,
239
+ chunk_overlap=150
240
+ )
241
+ chunks = splitter.split_documents(todos_docs)
242
+
243
+ vs = FAISS.from_documents(chunks, embeddings)
244
+ vs.save_local(str(VECTOR_DIR))
245
+
246
+ msg = (
247
+ f"Base construída com sucesso. "
248
+ f"Documentos carregados: {len(todos_docs)} | "
249
+ f"Chunks gerados: {len(chunks)}"
250
+ )
251
+ return vs, msg
252
+
253
+ def garantir_base():
254
+ global vectorstore, retriever, status_inicializacao
255
+
256
+ if retriever is None:
257
+ vectorstore, status_inicializacao = construir_ou_carregar_vectorstore()
258
+ retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
259
+
260
+ def reconstruir_base():
261
+ global vectorstore, retriever, status_inicializacao
262
+
263
+ shutil.rmtree(VECTOR_DIR, ignore_errors=True)
264
+ shutil.rmtree(DOCS_DIR, ignore_errors=True)
265
+
266
+ vectorstore = None
267
+ retriever = None
268
+ status_inicializacao = "Base apagada. Reconstruindo..."
269
+
270
+ garantir_base()
271
+ return status_inicializacao
272
+
273
+ # =========================
274
+ # RESPOSTA DO CHAT
275
+ # =========================
276
+ def formatar_contexto(docs: List[Document]) -> str:
277
+ partes = []
278
+
279
+ for i, doc in enumerate(docs, start=1):
280
+ origem = doc.metadata.get("source_type", "desconhecido")
281
+ arquivo = doc.metadata.get("arquivo", "arquivo_desconhecido")
282
+ trecho = doc.page_content[:1400]
283
+
284
+ partes.append(f"[Fonte {i} | {origem} | {arquivo}]\n{trecho}")
285
+
286
+ return "\n\n".join(partes)
287
+
288
+ def responder(mensagem, historico):
289
+ try:
290
+ garantir_base()
291
+
292
+ docs = retriever.invoke(mensagem)
293
+ contexto = formatar_contexto(docs)
294
+
295
+ msgs = PROMPT.format_messages(
296
+ contexto=contexto,
297
+ pergunta=mensagem
298
+ )
299
+ resposta = llm.invoke(msgs).content
300
+
301
+ fontes = []
302
+ for d in docs:
303
+ origem = d.metadata.get("source_type", "desconhecido")
304
+ arquivo = d.metadata.get("arquivo", "arquivo_desconhecido")
305
+ fontes.append(f"- {origem}: {arquivo}")
306
+
307
+ resposta += "\n\n**Fontes consultadas:**\n" + "\n".join(sorted(set(fontes)))
308
+ return resposta
309
+
310
+ except Exception as e:
311
+ return (
312
+ "Ocorreu um erro ao processar sua pergunta.\n\n"
313
+ f"**Detalhes:** `{str(e)}`"
314
+ )
315
+
316
+ def obter_status():
317
+ return status_inicializacao
318
+
319
+ # =========================
320
+ # INTERFACE
321
+ # =========================
322
+ with gr.Blocks(title="Tutor de Fundamentos de Python") as demo:
323
+ gr.Markdown("# Tutor de Fundamentos de Python")
324
+ gr.Markdown(
325
+ "Este tutor responde com base na sua apostila e em partes essenciais da documentação oficial do Python."
326
+ )
327
+
328
+ with gr.Row():
329
+ btn_status = gr.Button("Ver status da base")
330
+ btn_rebuild = gr.Button("Reconstruir base")
331
+
332
+ status_box = gr.Textbox(label="Status", interactive=False)
333
+
334
+ btn_status.click(fn=obter_status, outputs=status_box)
335
+ btn_rebuild.click(fn=reconstruir_base, outputs=status_box)
336
+
337
+ gr.ChatInterface(
338
+ fn=responder,
339
+ type="messages",
340
+ title="Tire suas dúvidas",
341
+ description="Ex.: O que é uma lista em Python? Qual a diferença entre lista e tupla?"
342
+ )
343
+
344
+ if __name__ == "__main__":
345
  demo.launch()