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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
gr.Markdown(
|
| 4 |
-
"
|
| 5 |
)
|
| 6 |
|
| 7 |
with gr.Row():
|
| 8 |
-
|
|
|
|
|
|
|
| 9 |
btn_rebuild = gr.Button("Reconstruir base")
|
| 10 |
|
| 11 |
status_box = gr.Textbox(label="Status", interactive=False)
|
| 12 |
|
| 13 |
-
btn_status.click(fn=
|
| 14 |
-
|
|
|
|
| 15 |
|
| 16 |
gr.ChatInterface(
|
| 17 |
fn=responder,
|
| 18 |
-
title="
|
| 19 |
-
description="Ex
|
| 20 |
)
|
| 21 |
|
| 22 |
if __name__ == "__main__":
|
|
|
|
| 23 |
demo.launch()
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import zipfile
|
| 3 |
+
import shutil
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import List
|
| 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 |
+
|
| 15 |
+
from langchain_community.document_loaders import PyPDFLoader
|
| 16 |
+
from langchain_community.vectorstores import FAISS
|
| 17 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 18 |
+
|
| 19 |
+
from langchain_google_genai import ChatGoogleGenerativeAI
|
| 20 |
+
|
| 21 |
+
# =========================
|
| 22 |
+
# CONFIG
|
| 23 |
+
# =========================
|
| 24 |
+
|
| 25 |
+
BASE_DIR = Path(__file__).parent
|
| 26 |
+
DATA_DIR = BASE_DIR / "data"
|
| 27 |
+
DOCS_DIR = BASE_DIR / "python_docs"
|
| 28 |
+
VECTOR_DIR = BASE_DIR / "vectorstore"
|
| 29 |
+
|
| 30 |
+
APOSTILA_PATH = DATA_DIR / "apostila.pdf"
|
| 31 |
+
|
| 32 |
+
PYTHON_DOCS_PAGE = "https://docs.python.org/3/download.html"
|
| 33 |
+
|
| 34 |
+
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
| 35 |
+
|
| 36 |
+
if not GOOGLE_API_KEY:
|
| 37 |
+
raise ValueError(
|
| 38 |
+
"Defina a variável de ambiente GOOGLE_API_KEY nas Settings do Space."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
# partes da documentação relevantes para fundamentos
|
| 42 |
+
DOC_FILTER = [
|
| 43 |
+
"tutorial",
|
| 44 |
+
"library/functions",
|
| 45 |
+
"library/stdtypes",
|
| 46 |
+
"reference/expressions",
|
| 47 |
+
"reference/simple_stmts",
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
# =========================
|
| 51 |
+
# MODELOS
|
| 52 |
+
# =========================
|
| 53 |
+
|
| 54 |
+
def criar_embeddings():
|
| 55 |
+
return HuggingFaceEmbeddings(
|
| 56 |
+
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def criar_llm():
|
| 61 |
+
return ChatGoogleGenerativeAI(
|
| 62 |
+
model="gemini-2.0-flash",
|
| 63 |
+
temperature=0.2,
|
| 64 |
+
google_api_key=GOOGLE_API_KEY
|
| 65 |
+
)
|
| 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 iniciantes
|
| 75 |
+
- explicar passo a passo
|
| 76 |
+
- mostrar exemplos simples
|
| 77 |
+
- sugerir exercícios
|
| 78 |
+
|
| 79 |
+
Regras:
|
| 80 |
+
- basear respostas na apostila e documentação Python
|
| 81 |
+
- não inventar sintaxe
|
| 82 |
+
- responder em português
|
| 83 |
+
|
| 84 |
+
Contexto:
|
| 85 |
+
{contexto}
|
| 86 |
+
|
| 87 |
+
Pergunta:
|
| 88 |
+
{pergunta}
|
| 89 |
+
""")
|
| 90 |
+
|
| 91 |
+
# =========================
|
| 92 |
+
# ESTADO GLOBAL
|
| 93 |
+
# =========================
|
| 94 |
+
|
| 95 |
+
vectorstore = None
|
| 96 |
+
retriever = None
|
| 97 |
+
status_base = "Base ainda não carregada."
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# =========================
|
| 101 |
+
# DOWNLOAD DOCS PYTHON
|
| 102 |
+
# =========================
|
| 103 |
+
|
| 104 |
+
def encontrar_zip_docs():
|
| 105 |
+
|
| 106 |
+
resp = requests.get(PYTHON_DOCS_PAGE, timeout=60)
|
| 107 |
+
soup = BeautifulSoup(resp.text, "html.parser")
|
| 108 |
+
|
| 109 |
+
for a in soup.find_all("a", href=True):
|
| 110 |
+
|
| 111 |
+
href = a["href"].lower()
|
| 112 |
+
|
| 113 |
+
if "zip" in href and "html" in href:
|
| 114 |
+
|
| 115 |
+
if href.startswith("http"):
|
| 116 |
+
return href
|
| 117 |
+
|
| 118 |
+
return "https://docs.python.org/3/" + href
|
| 119 |
+
|
| 120 |
+
raise RuntimeError("ZIP da documentação não encontrado.")
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def baixar_docs():
|
| 124 |
+
|
| 125 |
+
if DOCS_DIR.exists() and list(DOCS_DIR.rglob("*.html")):
|
| 126 |
+
return
|
| 127 |
+
|
| 128 |
+
DOCS_DIR.mkdir(parents=True, exist_ok=True)
|
| 129 |
+
|
| 130 |
+
url = encontrar_zip_docs()
|
| 131 |
+
|
| 132 |
+
zip_path = DOCS_DIR / "docs.zip"
|
| 133 |
+
|
| 134 |
+
r = requests.get(url)
|
| 135 |
+
|
| 136 |
+
with open(zip_path, "wb") as f:
|
| 137 |
+
f.write(r.content)
|
| 138 |
+
|
| 139 |
+
with zipfile.ZipFile(zip_path, "r") as z:
|
| 140 |
+
z.extractall(DOCS_DIR)
|
| 141 |
+
|
| 142 |
+
zip_path.unlink()
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# =========================
|
| 146 |
+
# LIMPEZA HTML
|
| 147 |
+
# =========================
|
| 148 |
+
|
| 149 |
+
def limpar_html(html):
|
| 150 |
+
|
| 151 |
+
soup = BeautifulSoup(html, "html.parser")
|
| 152 |
+
|
| 153 |
+
for tag in soup(["script", "style", "nav", "footer"]):
|
| 154 |
+
tag.decompose()
|
| 155 |
+
|
| 156 |
+
text = soup.get_text("\n")
|
| 157 |
+
|
| 158 |
+
lines = [l.strip() for l in text.splitlines() if l.strip()]
|
| 159 |
+
|
| 160 |
+
return "\n".join(lines)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
# =========================
|
| 164 |
+
# CARREGAMENTO
|
| 165 |
+
# =========================
|
| 166 |
+
|
| 167 |
+
def carregar_apostila():
|
| 168 |
+
|
| 169 |
+
docs = []
|
| 170 |
+
|
| 171 |
+
if APOSTILA_PATH.exists():
|
| 172 |
+
|
| 173 |
+
loader = PyPDFLoader(str(APOSTILA_PATH))
|
| 174 |
+
pages = loader.load()
|
| 175 |
+
|
| 176 |
+
for p in pages:
|
| 177 |
+
p.metadata["source"] = "apostila"
|
| 178 |
+
|
| 179 |
+
docs.extend(pages)
|
| 180 |
+
|
| 181 |
+
return docs
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def html_relevante(path):
|
| 185 |
+
|
| 186 |
+
path = str(path).lower()
|
| 187 |
+
|
| 188 |
+
return any(f in path for f in DOC_FILTER)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def carregar_docs_python():
|
| 192 |
+
|
| 193 |
+
docs = []
|
| 194 |
+
|
| 195 |
+
for html_file in DOCS_DIR.rglob("*.html"):
|
| 196 |
+
|
| 197 |
+
if not html_relevante(html_file):
|
| 198 |
+
continue
|
| 199 |
+
|
| 200 |
+
try:
|
| 201 |
+
|
| 202 |
+
html = open(html_file, encoding="utf8", errors="ignore").read()
|
| 203 |
+
|
| 204 |
+
text = limpar_html(html)
|
| 205 |
+
|
| 206 |
+
if len(text) < 300:
|
| 207 |
+
continue
|
| 208 |
+
|
| 209 |
+
docs.append(
|
| 210 |
+
Document(
|
| 211 |
+
page_content=text,
|
| 212 |
+
metadata={"source": "python_docs"}
|
| 213 |
+
)
|
| 214 |
+
)
|
| 215 |
+
|
| 216 |
+
except:
|
| 217 |
+
pass
|
| 218 |
+
|
| 219 |
+
return docs
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# =========================
|
| 223 |
+
# VECTORSTORE
|
| 224 |
+
# =========================
|
| 225 |
+
|
| 226 |
+
def construir_vectorstore():
|
| 227 |
+
|
| 228 |
+
global status_base
|
| 229 |
+
|
| 230 |
+
embeddings = criar_embeddings()
|
| 231 |
+
|
| 232 |
+
baixar_docs()
|
| 233 |
+
|
| 234 |
+
docs = carregar_apostila() + carregar_docs_python()
|
| 235 |
+
|
| 236 |
+
splitter = RecursiveCharacterTextSplitter(
|
| 237 |
+
chunk_size=1000,
|
| 238 |
+
chunk_overlap=150
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
chunks = splitter.split_documents(docs)
|
| 242 |
+
|
| 243 |
+
vs = FAISS.from_documents(chunks, embeddings)
|
| 244 |
+
|
| 245 |
+
vs.save_local(VECTOR_DIR)
|
| 246 |
+
|
| 247 |
+
status_base = f"Base criada com {len(chunks)} chunks"
|
| 248 |
+
|
| 249 |
+
return vs
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def garantir_base():
|
| 253 |
+
|
| 254 |
+
global vectorstore
|
| 255 |
+
global retriever
|
| 256 |
+
|
| 257 |
+
if retriever is not None:
|
| 258 |
+
return
|
| 259 |
+
|
| 260 |
+
embeddings = criar_embeddings()
|
| 261 |
+
|
| 262 |
+
if VECTOR_DIR.exists():
|
| 263 |
+
|
| 264 |
+
vectorstore = FAISS.load_local(
|
| 265 |
+
VECTOR_DIR,
|
| 266 |
+
embeddings,
|
| 267 |
+
allow_dangerous_deserialization=True
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
else:
|
| 271 |
+
|
| 272 |
+
vectorstore = construir_vectorstore()
|
| 273 |
+
|
| 274 |
+
retriever = vectorstore.as_retriever(search_kwargs={"k": 4})
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
# =========================
|
| 278 |
+
# CHAT
|
| 279 |
+
# =========================
|
| 280 |
+
|
| 281 |
+
def formatar_contexto(docs):
|
| 282 |
+
|
| 283 |
+
partes = []
|
| 284 |
+
|
| 285 |
+
for i, d in enumerate(docs):
|
| 286 |
+
|
| 287 |
+
partes.append(
|
| 288 |
+
f"[Fonte {i+1}]\n{d.page_content[:1200]}"
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
return "\n\n".join(partes)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def responder(mensagem, historico):
|
| 295 |
+
|
| 296 |
+
try:
|
| 297 |
+
|
| 298 |
+
garantir_base()
|
| 299 |
+
|
| 300 |
+
docs = retriever.invoke(mensagem)
|
| 301 |
+
|
| 302 |
+
contexto = formatar_contexto(docs)
|
| 303 |
+
|
| 304 |
+
msgs = PROMPT.format_messages(
|
| 305 |
+
contexto=contexto,
|
| 306 |
+
pergunta=mensagem
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
resposta = llm.invoke(msgs).content
|
| 310 |
+
|
| 311 |
+
return resposta
|
| 312 |
+
|
| 313 |
+
except Exception as e:
|
| 314 |
+
|
| 315 |
+
return f"Erro: {e}"
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
# =========================
|
| 319 |
+
# AÇÕES UI
|
| 320 |
+
# =========================
|
| 321 |
+
|
| 322 |
+
def status():
|
| 323 |
+
|
| 324 |
+
return status_base
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def reconstruir():
|
| 328 |
+
|
| 329 |
+
global vectorstore
|
| 330 |
+
global retriever
|
| 331 |
+
|
| 332 |
+
shutil.rmtree(VECTOR_DIR, ignore_errors=True)
|
| 333 |
+
shutil.rmtree(DOCS_DIR, ignore_errors=True)
|
| 334 |
+
|
| 335 |
+
vectorstore = None
|
| 336 |
+
retriever = None
|
| 337 |
+
|
| 338 |
+
garantir_base()
|
| 339 |
+
|
| 340 |
+
return status_base
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
# =========================
|
| 344 |
+
# INTERFACE
|
| 345 |
+
# =========================
|
| 346 |
+
|
| 347 |
+
with gr.Blocks(title="Tutor Python") as demo:
|
| 348 |
+
|
| 349 |
+
gr.Markdown("# 🐍 Tutor de Fundamentos de Python")
|
| 350 |
+
|
| 351 |
gr.Markdown(
|
| 352 |
+
"Baseado na apostila do curso e na documentação oficial do Python."
|
| 353 |
)
|
| 354 |
|
| 355 |
with gr.Row():
|
| 356 |
+
|
| 357 |
+
btn_status = gr.Button("Status da base")
|
| 358 |
+
|
| 359 |
btn_rebuild = gr.Button("Reconstruir base")
|
| 360 |
|
| 361 |
status_box = gr.Textbox(label="Status", interactive=False)
|
| 362 |
|
| 363 |
+
btn_status.click(fn=status, outputs=status_box)
|
| 364 |
+
|
| 365 |
+
btn_rebuild.click(fn=reconstruir, outputs=status_box)
|
| 366 |
|
| 367 |
gr.ChatInterface(
|
| 368 |
fn=responder,
|
| 369 |
+
title="Pergunte ao tutor",
|
| 370 |
+
description="Ex: o que é uma lista em Python?"
|
| 371 |
)
|
| 372 |
|
| 373 |
if __name__ == "__main__":
|
| 374 |
+
|
| 375 |
demo.launch()
|