Spaces:
Sleeping
Sleeping
Download app.py from douglasribeiro/Python_Tutor: direct link, hf CLI and curl.
- Browser
- Download file 7.24 kB
-
https://huggingface.co/spaces/douglasribeiro/Python_Tutor/resolve/main/app.py
- Command line
-
hf download hf://spaces/douglasribeiro/Python_Tutor/app.py
-
curl -L -o app.py https://huggingface.co/spaces/douglasribeiro/Python_Tutor/resolve/main/app.py
7.24 kB
| import os | |
| import zipfile | |
| 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_community.embeddings import HuggingFaceEmbeddings | |
| from langchain_google_genai import ChatGoogleGenerativeAI | |
| # ========================= | |
| # 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_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." | |
| ) | |
| # partes da documentação relevantes para fundamentos | |
| DOC_FILTER = [ | |
| "tutorial", | |
| "library/functions", | |
| "library/stdtypes", | |
| "reference/expressions", | |
| "reference/simple_stmts", | |
| ] | |
| # ========================= | |
| # MODELOS | |
| # ========================= | |
| def criar_embeddings(): | |
| return HuggingFaceEmbeddings( | |
| model_name="sentence-transformers/all-MiniLM-L6-v2" | |
| ) | |
| def criar_llm(): | |
| return ChatGoogleGenerativeAI( | |
| model="gemini-2.0-flash", | |
| temperature=0.2, | |
| google_api_key=GOOGLE_API_KEY | |
| ) | |
| llm = criar_llm() | |
| PROMPT = ChatPromptTemplate.from_template(""" | |
| Você é um professor tutor especializado em Fundamentos de Python. | |
| Objetivo: | |
| - ensinar iniciantes | |
| - explicar passo a passo | |
| - mostrar exemplos simples | |
| - sugerir exercícios | |
| Regras: | |
| - basear respostas na apostila e documentação Python | |
| - não inventar sintaxe | |
| - responder em português | |
| Contexto: | |
| {contexto} | |
| Pergunta: | |
| {pergunta} | |
| """) | |
| # ========================= | |
| # ESTADO GLOBAL | |
| # ========================= | |
| vectorstore = None | |
| retriever = None | |
| status_base = "Base ainda não carregada." | |
| # ========================= | |
| # DOWNLOAD DOCS PYTHON | |
| # ========================= | |
| def encontrar_zip_docs(): | |
| resp = requests.get(PYTHON_DOCS_PAGE, timeout=60) | |
| soup = BeautifulSoup(resp.text, "html.parser") | |
| for a in soup.find_all("a", href=True): | |
| href = a["href"].lower() | |
| if "zip" in href and "html" in href: | |
| if href.startswith("http"): | |
| return href | |
| return "https://docs.python.org/3/" + href | |
| raise RuntimeError("ZIP da documentação não encontrado.") | |
| def baixar_docs(): | |
| if DOCS_DIR.exists() and list(DOCS_DIR.rglob("*.html")): | |
| return | |
| DOCS_DIR.mkdir(parents=True, exist_ok=True) | |
| url = encontrar_zip_docs() | |
| zip_path = DOCS_DIR / "docs.zip" | |
| r = requests.get(url) | |
| with open(zip_path, "wb") as f: | |
| f.write(r.content) | |
| with zipfile.ZipFile(zip_path, "r") as z: | |
| z.extractall(DOCS_DIR) | |
| zip_path.unlink() | |
| # ========================= | |
| # LIMPEZA HTML | |
| # ========================= | |
| def limpar_html(html): | |
| soup = BeautifulSoup(html, "html.parser") | |
| for tag in soup(["script", "style", "nav", "footer"]): | |
| tag.decompose() | |
| text = soup.get_text("\n") | |
| lines = [l.strip() for l in text.splitlines() if l.strip()] | |
| return "\n".join(lines) | |
| # ========================= | |
| # CARREGAMENTO | |
| # ========================= | |
| def carregar_apostila(): | |
| docs = [] | |
| if APOSTILA_PATH.exists(): | |
| loader = PyPDFLoader(str(APOSTILA_PATH)) | |
| pages = loader.load() | |
| for p in pages: | |
| p.metadata["source"] = "apostila" | |
| docs.extend(pages) | |
| return docs | |
| def html_relevante(path): | |
| path = str(path).lower() | |
| return any(f in path for f in DOC_FILTER) | |
| def carregar_docs_python(): | |
| docs = [] | |
| for html_file in DOCS_DIR.rglob("*.html"): | |
| if not html_relevante(html_file): | |
| continue | |
| try: | |
| html = open(html_file, encoding="utf8", errors="ignore").read() | |
| text = limpar_html(html) | |
| if len(text) < 300: | |
| continue | |
| docs.append( | |
| Document( | |
| page_content=text, | |
| metadata={"source": "python_docs"} | |
| ) | |
| ) | |
| except: | |
| pass | |
| return docs | |
| # ========================= | |
| # VECTORSTORE | |
| # ========================= | |
| def construir_vectorstore(): | |
| global status_base | |
| embeddings = criar_embeddings() | |
| baixar_docs() | |
| docs = carregar_apostila() + carregar_docs_python() | |
| splitter = RecursiveCharacterTextSplitter( | |
| chunk_size=1000, | |
| chunk_overlap=150 | |
| ) | |
| chunks = splitter.split_documents(docs) | |
| vs = FAISS.from_documents(chunks, embeddings) | |
| vs.save_local(VECTOR_DIR) | |
| status_base = f"Base criada com {len(chunks)} chunks" | |
| return vs | |
| def garantir_base(): | |
| global vectorstore | |
| global retriever | |
| if retriever is not None: | |
| return | |
| embeddings = criar_embeddings() | |
| if VECTOR_DIR.exists(): | |
| vectorstore = FAISS.load_local( | |
| VECTOR_DIR, | |
| embeddings, | |
| allow_dangerous_deserialization=True | |
| ) | |
| else: | |
| vectorstore = construir_vectorstore() | |
| retriever = vectorstore.as_retriever(search_kwargs={"k": 4}) | |
| # ========================= | |
| # CHAT | |
| # ========================= | |
| def formatar_contexto(docs): | |
| partes = [] | |
| for i, d in enumerate(docs): | |
| partes.append( | |
| f"[Fonte {i+1}]\n{d.page_content[:1200]}" | |
| ) | |
| return "\n\n".join(partes) | |
| def responder(mensagem, historico): | |
| try: | |
| garantir_base() | |
| docs = retriever.invoke(mensagem) | |
| contexto = formatar_contexto(docs) | |
| msgs = PROMPT.format_messages( | |
| contexto=contexto, | |
| pergunta=mensagem | |
| ) | |
| resposta = llm.invoke(msgs).content | |
| return resposta | |
| except Exception as e: | |
| return f"Erro: {e}" | |
| # ========================= | |
| # AÇÕES UI | |
| # ========================= | |
| def status(): | |
| return status_base | |
| def reconstruir(): | |
| global vectorstore | |
| global retriever | |
| shutil.rmtree(VECTOR_DIR, ignore_errors=True) | |
| shutil.rmtree(DOCS_DIR, ignore_errors=True) | |
| vectorstore = None | |
| retriever = None | |
| garantir_base() | |
| return status_base | |
| # ========================= | |
| # INTERFACE | |
| # ========================= | |
| with gr.Blocks(title="Tutor Python") as demo: | |
| gr.Markdown("# 🐍 Tutor de Fundamentos de Python") | |
| gr.Markdown( | |
| "Baseado na apostila do curso e na documentação oficial do Python." | |
| ) | |
| with gr.Row(): | |
| btn_status = gr.Button("Status da base") | |
| btn_rebuild = gr.Button("Reconstruir base") | |
| status_box = gr.Textbox(label="Status", interactive=False) | |
| btn_status.click(fn=status, outputs=status_box) | |
| btn_rebuild.click(fn=reconstruir, outputs=status_box) | |
| gr.ChatInterface( | |
| fn=responder, | |
| title="Pergunte ao tutor", | |
| description="Ex: o que é uma lista em Python?" | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |