Spaces:
Sleeping

douglasribeiro commited on
Commit
12dff9d
·
verified ·
1 Parent(s): f65fe5e

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +270 -0
app.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()