Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,324 +1,3 @@
|
|
| 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(
|
|
@@ -336,7 +15,6 @@ with gr.Blocks(title="Tutor de Fundamentos de Python") as demo:
|
|
| 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?"
|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16 |
gr.ChatInterface(
|
| 17 |
fn=responder,
|
|
|
|
| 18 |
title="Tire suas dúvidas",
|
| 19 |
description="Ex.: O que é uma lista em Python? Qual a diferença entre lista e tupla?"
|
| 20 |
)
|