Spaces:
Sleeping

Python_Tutor / app.py
douglasribeiro's picture
Upload app.py
12dff9d verified
Raw History Blame
8.3 kB
import os
import zipfile
import tempfile
import shutil
from pathlib import Path
from typing import List
import requests
import gradio as gr
from bs4 import BeautifulSoup
from langchain.schema import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.prompts import ChatPromptTemplate
from langchain_community.document_loaders import PyPDFLoader
from langchain_community.vectorstores import FAISS
from langchain_google_genai import ChatGoogleGenerativeAI, GoogleGenerativeAIEmbeddings
# =========================
# CONFIG
# =========================
BASE_DIR = Path(__file__).parent
DATA_DIR = BASE_DIR / "data"
DOCS_DIR = BASE_DIR / "python_docs"
VECTOR_DIR = BASE_DIR / "vectorstore"
APOSTILA_PATH = DATA_DIR / "apostila.pdf"
PYTHON_DOCS_DOWNLOAD_PAGE = "https://docs.python.org/3/download.html"
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
if not GOOGLE_API_KEY:
raise ValueError("Defina a variável de ambiente GOOGLE_API_KEY nas Settings do Space.")
# =========================
# DOWNLOAD DA DOCUMENTAÇÃO
# =========================
def encontrar_link_zip_documentacao() -> str:
"""
Lê a página oficial de download da documentação do Python
e encontra o link do arquivo HTML .zip.
"""
resp = requests.get(PYTHON_DOCS_DOWNLOAD_PAGE, timeout=60)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "html.parser")
for a in soup.find_all("a", href=True):
href = a["href"]
texto = a.get_text(" ", strip=True).lower()
# procura algo como html + zip
if ("zip" in href.lower()) and ("html" in href.lower() or "html" in texto):
if href.startswith("http"):
return href
return requests.compat.urljoin(PYTHON_DOCS_DOWNLOAD_PAGE, href)
raise RuntimeError("Não foi possível localizar o ZIP HTML da documentação oficial do Python.")
def baixar_e_extrair_docs_python(destino: Path):
"""
Baixa o ZIP HTML da documentação oficial do Python e extrai.
"""
if destino.exists() and any(destino.rglob("*.html")):
return
destino.mkdir(parents=True, exist_ok=True)
url_zip = encontrar_link_zip_documentacao()
zip_path = destino / "python_docs.zip"
with requests.get(url_zip, stream=True, timeout=120) as r:
r.raise_for_status()
with open(zip_path, "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
if chunk:
f.write(chunk)
with zipfile.ZipFile(zip_path, "r") as z:
z.extractall(destino)
zip_path.unlink(missing_ok=True)
# =========================
# LEITURA DOS DOCUMENTOS
# =========================
def limpar_html(html_text: str) -> str:
soup = BeautifulSoup(html_text, "html.parser")
for tag in soup(["script", "style", "nav", "footer", "header"]):
tag.decompose()
text = soup.get_text(separator="\n")
lines = [line.strip() for line in text.splitlines()]
lines = [line for line in lines if line]
return "\n".join(lines)
def carregar_apostila() -> List[Document]:
docs = []
if not APOSTILA_PATH.exists():
return docs
loader = PyPDFLoader(str(APOSTILA_PATH))
pages = loader.load()
for p in pages:
p.metadata["source_type"] = "apostila"
p.metadata["arquivo"] = APOSTILA_PATH.name
docs.extend(pages)
return docs
def carregar_docs_python() -> List[Document]:
docs = []
for html_file in DOCS_DIR.rglob("*.html"):
try:
with open(html_file, "r", encoding="utf-8", errors="ignore") as f:
html = f.read()
text = limpar_html(html)
if len(text) < 300:
continue
docs.append(
Document(
page_content=text,
metadata={
"source_type": "documentacao_python",
"arquivo": html_file.name,
"path": str(html_file),
},
)
)
except Exception:
continue
return docs
# =========================
# INDEXAÇÃO
# =========================
def construir_ou_carregar_vectorstore():
embeddings = GoogleGenerativeAIEmbeddings(
model="models/gemini-embedding-001",
google_api_key=GOOGLE_API_KEY
)
if VECTOR_DIR.exists():
try:
vs = FAISS.load_local(
str(VECTOR_DIR),
embeddings,
allow_dangerous_deserialization=True
)
return vs
except Exception:
shutil.rmtree(VECTOR_DIR, ignore_errors=True)
baixar_e_extrair_docs_python(DOCS_DIR)
docs_apostila = carregar_apostila()
docs_python = carregar_docs_python()
todos_docs = docs_apostila + docs_python
if not todos_docs:
raise RuntimeError("Nenhum documento foi carregado. Verifique a apostila e o download da documentação.")
splitter = RecursiveCharacterTextSplitter(
chunk_size=1200,
chunk_overlap=200
)
chunks = splitter.split_documents(todos_docs)
vs = FAISS.from_documents(chunks, embeddings)
vs.save_local(str(VECTOR_DIR))
return vs
# =========================
# LLM
# =========================
llm = ChatGoogleGenerativeAI(
model="gemini-2.0-flash",
temperature=0.2,
google_api_key=GOOGLE_API_KEY
)
PROMPT = ChatPromptTemplate.from_template("""
Você é um professor tutor especializado em Fundamentos de Python.
Objetivo:
- ensinar alunos iniciantes com linguagem clara e acolhedora;
- responder com base prioritária na apostila do curso e na documentação oficial do Python;
- quando o aluno pedir, explicar passo a passo;
- sempre que possível, mostrar exemplos curtos;
- ao final, sugerir um mini exercício.
Regras:
- se não houver base suficiente no contexto, diga isso claramente;
- não invente sintaxe ou funções;
- destaque as fontes usadas;
- responda em português do Brasil.
Contexto:
{contexto}
Pergunta do aluno:
{pergunta}
""")
vectorstore = construir_ou_carregar_vectorstore()
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
def formatar_contexto(docs: List[Document]) -> str:
partes = []
for i, doc in enumerate(docs, start=1):
origem = doc.metadata.get("source_type", "desconhecido")
arquivo = doc.metadata.get("arquivo", "arquivo_desconhecido")
trecho = doc.page_content[:1600]
partes.append(f"[Fonte {i} | {origem} | {arquivo}]\n{trecho}")
return "\n\n".join(partes)
def responder(mensagem, historico):
docs = retriever.invoke(mensagem)
contexto = formatar_contexto(docs)
msgs = PROMPT.format_messages(
contexto=contexto,
pergunta=mensagem
)
resposta = llm.invoke(msgs).content
fontes = []
for d in docs:
origem = d.metadata.get("source_type", "desconhecido")
arquivo = d.metadata.get("arquivo", "arquivo_desconhecido")
fontes.append(f"- {origem}: {arquivo}")
resposta += "\n\n**Fontes consultadas:**\n" + "\n".join(sorted(set(fontes)))
return resposta
def reconstruir_base():
shutil.rmtree(VECTOR_DIR, ignore_errors=True)
shutil.rmtree(DOCS_DIR, ignore_errors=True)
global vectorstore, retriever
vectorstore = construir_ou_carregar_vectorstore()
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
return "Base reconstruída com sucesso."
with gr.Blocks(title="Tutor de Fundamentos de Python") as demo:
gr.Markdown("# Tutor de Fundamentos de Python")
gr.Markdown(
"Este tutor responde com base na sua apostila e na documentação oficial do Python."
)
with gr.Row():
btn_rebuild = gr.Button("Reconstruir base")
status = gr.Textbox(label="Status", interactive=False)
chat = gr.ChatInterface(
fn=responder,
type="messages"
)
btn_rebuild.click(fn=reconstruir_base, outputs=status)
if __name__ == "__main__":
demo.launch()