Spaces:
Sleeping

File size: 10,111 Bytes
9ede463
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12dff9d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import os
import zipfile
import shutil
from pathlib import Path
from typing import List, Tuple

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

# =========================
# CONFIGURAÇÕES GERAIS
# =========================
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(
        "A variável de ambiente GOOGLE_API_KEY não foi encontrada. "
        "Configure essa secret nas Settings do Space."
    )

# Partes da documentação do Python mais úteis para fundamentos
DOC_PATH_FILTERS = [
    "tutorial",
    "library/functions",
    "library/stdtypes",
    "reference/expressions",
    "reference/simple_stmts",
]

# Estado global simples
vectorstore = None
retriever = None
status_inicializacao = "Base ainda não carregada."

# =========================
# MODELOS
# =========================
def criar_embeddings():
    # Embeddings locais: evita estourar a cota do Gemini
    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 alunos iniciantes com linguagem clara, paciente e didática;
- responder com base prioritária na apostila do curso e na documentação oficial do Python;
- explicar passo a passo quando necessário;
- mostrar exemplos curtos e corretos;
- ao final, sugerir um mini exercício prático.

Regras:
- se não houver base suficiente no contexto, diga isso claramente;
- não invente sintaxe, funções ou recursos inexistentes;
- destaque as fontes consultadas;
- responda em português do Brasil;
- quando relevante, corrija conceitos errados com delicadeza.

Contexto:
{contexto}

Pergunta do aluno:
{pergunta}
""")

# =========================
# DOWNLOAD DA DOCUMENTAÇÃO
# =========================
def encontrar_link_zip_documentacao() -> str:
    """
    Encontra automaticamente o link do ZIP HTML da documentação oficial do Python.
    """
    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()

        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 automaticamente o ZIP HTML da documentação oficial do Python."
    )

def baixar_e_extrair_docs_python(destino: Path):
    """
    Baixa e extrai a documentação oficial do Python em HTML.
    """
    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=180) 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 E LIMPEZA
# =========================
def limpar_html(html_text: str) -> str:
    soup = BeautifulSoup(html_text, "html.parser")

    for tag in soup(["script", "style", "nav", "footer", "header", "aside"]):
        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 arquivo_html_eh_relevante(html_file: Path) -> bool:
    path_str = str(html_file).replace("\\", "/").lower()
    return any(filtro in path_str for filtro in DOC_PATH_FILTERS)

def carregar_apostila() -> List[Document]:
    docs = []

    if not APOSTILA_PATH.exists():
        return docs

    loader = PyPDFLoader(str(APOSTILA_PATH))
    pages = loader.load()

    for page in pages:
        page.metadata["source_type"] = "apostila"
        page.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"):
        if not arquivo_html_eh_relevante(html_file):
            continue

        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

# =========================
# CONSTRUÇÃO DA BASE
# =========================
def construir_ou_carregar_vectorstore() -> Tuple[FAISS, str]:
    embeddings = criar_embeddings()

    if VECTOR_DIR.exists():
        try:
            vs = FAISS.load_local(
                str(VECTOR_DIR),
                embeddings,
                allow_dangerous_deserialization=True
            )
            return vs, "Base carregada do índice local."
        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 se a apostila está em /data/apostila.pdf "
            "e se o download da documentação foi concluído."
        )

    splitter = RecursiveCharacterTextSplitter(
        chunk_size=1000,
        chunk_overlap=150
    )
    chunks = splitter.split_documents(todos_docs)

    vs = FAISS.from_documents(chunks, embeddings)
    vs.save_local(str(VECTOR_DIR))

    msg = (
        f"Base construída com sucesso. "
        f"Documentos carregados: {len(todos_docs)} | "
        f"Chunks gerados: {len(chunks)}"
    )
    return vs, msg

def garantir_base():
    global vectorstore, retriever, status_inicializacao

    if retriever is None:
        vectorstore, status_inicializacao = construir_ou_carregar_vectorstore()
        retriever = vectorstore.as_retriever(search_kwargs={"k": 5})

def reconstruir_base():
    global vectorstore, retriever, status_inicializacao

    shutil.rmtree(VECTOR_DIR, ignore_errors=True)
    shutil.rmtree(DOCS_DIR, ignore_errors=True)

    vectorstore = None
    retriever = None
    status_inicializacao = "Base apagada. Reconstruindo..."

    garantir_base()
    return status_inicializacao

# =========================
# RESPOSTA DO CHAT
# =========================
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[:1400]

        partes.append(f"[Fonte {i} | {origem} | {arquivo}]\n{trecho}")

    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

        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

    except Exception as e:
        return (
            "Ocorreu um erro ao processar sua pergunta.\n\n"
            f"**Detalhes:** `{str(e)}`"
        )

def obter_status():
    return status_inicializacao

# =========================
# INTERFACE
# =========================
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 em partes essenciais da documentação oficial do Python."
    )

    with gr.Row():
        btn_status = gr.Button("Ver status da base")
        btn_rebuild = gr.Button("Reconstruir base")

    status_box = gr.Textbox(label="Status", interactive=False)

    btn_status.click(fn=obter_status, outputs=status_box)
    btn_rebuild.click(fn=reconstruir_base, outputs=status_box)

    gr.ChatInterface(
        fn=responder,
        type="messages",
        title="Tire suas dúvidas",
        description="Ex.: O que é uma lista em Python? Qual a diferença entre lista e tupla?"
    )

if __name__ == "__main__":
    demo.launch()