Spaces:
Runtime error

Crislene commited on
Commit
ad1dcee
·
verified ·
1 Parent(s): 520fbb0

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -201
app.py DELETED
@@ -1,201 +0,0 @@
1
- # ✅ Instalar todas as bibliotecas necessárias (incluindo langchain-openai)
2
- !pip install -q langchain langchain-community langchain-openai \
3
- openai huggingface_hub sentence-transformers \
4
- beautifulsoup4 html2text faiss-cpu python-dotenv gradio pandas openpyxl requests
5
- !pip install -U langchain-huggingface
6
- import os
7
- import sqlite3
8
- import pandas as pd
9
- from dotenv import load_dotenv
10
- from bs4 import BeautifulSoup
11
- import requests
12
- from langchain_community.document_loaders import WebBaseLoader
13
- from langchain.text_splitter import RecursiveCharacterTextSplitter
14
- from langchain_community.vectorstores import FAISS
15
- from langchain_huggingface import HuggingFaceEmbeddings
16
- from langchain_openai import ChatOpenAI
17
- from langchain.chains import ConversationalRetrievalChain
18
- from langchain.memory import ConversationBufferMemory
19
- import gradio as gr
20
-
21
- # Carrega chave da API
22
- load_dotenv()
23
- os.environ["OPENAI_API_KEY"] = os.getenv("OPENROUTER_API_KEY")
24
- os.environ["OPENAI_API_BASE"] = "https://openrouter.ai/api/v1"
25
-
26
- # Embeddings fixos
27
- embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
28
-
29
- # Mapeamento de temas para links da documentação Python
30
- temas_para_links = {
31
- "estruturas de dados": "https://docs.python.org/pt-br/3/tutorial/datastructures.html",
32
- "controle de fluxo": "https://docs.python.org/pt-br/3/tutorial/controlflow.html",
33
- "introdução": "https://docs.python.org/pt-br/3/tutorial/introduction.html",
34
- "funções": "https://docs.python.org/pt-br/3/tutorial/controlflow.html#definindo-funcoes",
35
- "módulos": "https://docs.python.org/pt-br/3/tutorial/modules.html",
36
- "exceções": "https://docs.python.org/pt-br/3/tutorial/errors.html"
37
- }
38
-
39
- # Detecta tema com base na pergunta
40
- def identificar_tema(pergunta):
41
- pergunta = pergunta.lower()
42
- for tema, link in temas_para_links.items():
43
- if tema in pergunta:
44
- return link
45
- return None
46
-
47
- # Cria banco de dados SQLite se não existir
48
- conn = sqlite3.connect("historico_conversas.db")
49
- cursor = conn.cursor()
50
- cursor.execute('''
51
- CREATE TABLE IF NOT EXISTS conversas (
52
- id INTEGER PRIMARY KEY AUTOINCREMENT,
53
- aluno TEXT,
54
- pergunta TEXT,
55
- resposta TEXT,
56
- timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
57
- )
58
- ''')
59
- conn.commit()
60
- conn.close()
61
-
62
- # LLM da OpenRouter
63
- llm = ChatOpenAI(model="deepseek/deepseek-r1:free", temperature=0.4)
64
-
65
- # Memória da conversa
66
- memoria = ConversationBufferMemory(memory_key="chat_history", return_messages=True, output_key="answer")
67
-
68
- # Função para salvar no banco
69
- def salvar_conversa(nome, pergunta, resposta):
70
- conn = sqlite3.connect("historico_conversas.db")
71
- cursor = conn.cursor()
72
- cursor.execute("INSERT INTO conversas (aluno, pergunta, resposta) VALUES (?, ?, ?)",
73
- (nome or "Anônimo", pergunta, str(resposta)))
74
- conn.commit()
75
- conn.close()
76
-
77
- # Função principal com roteamento por tema
78
- def responder(pergunta, nome):
79
- try:
80
- link = identificar_tema(pergunta)
81
-
82
- if link:
83
- loader = WebBaseLoader(link)
84
- docs = loader.load()
85
- splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)
86
- documents = splitter.split_documents(docs)
87
-
88
- if len(documents) > 0:
89
- vectordb = FAISS.from_documents(documents, embeddings)
90
- retriever = vectordb.as_retriever()
91
-
92
- resultado = ConversationalRetrievalChain.from_llm(
93
- llm=llm,
94
- retriever=retriever,
95
- memory=memoria,
96
- return_source_documents=True,
97
- output_key="answer"
98
- ).invoke({"question": pergunta})
99
-
100
- raw = resultado["answer"]
101
- resposta = raw.content if hasattr(raw, "content") else str(raw)
102
-
103
- else:
104
- resposta = llm.invoke(pergunta).content
105
- else:
106
- resposta = llm.invoke(pergunta).content
107
-
108
- salvar_conversa(nome, pergunta, resposta)
109
- return resposta
110
-
111
- except Exception as e:
112
- import traceback
113
- return f"❌ **Erro:**\n```\n{traceback.format_exc()}\n```"
114
-
115
-
116
- # Resetar memória
117
- def resetar_memoria():
118
- memoria.clear()
119
- return "✅ Memória resetada com sucesso!"
120
-
121
- # Exportar conversas para arquivos
122
- def exportar_conversas():
123
- conn = sqlite3.connect("historico_conversas.db")
124
- df = pd.read_sql_query("SELECT * FROM conversas ORDER BY timestamp DESC", conn)
125
- df.to_csv("conversas_exportadas.csv", index=False)
126
- df.to_excel("conversas_exportadas.xlsx", index=False, engine="openpyxl")
127
- conn.close()
128
- return "✅ Arquivos 'conversas_exportadas.csv' e 'conversas_exportadas.xlsx' foram salvos!"
129
-
130
- # Interface Gradio
131
- with gr.Blocks() as app:
132
- gr.Markdown("## 🤖 Tutor de Python com IA + Documentação Oficial Dinâmica")
133
- nome = gr.Textbox(label="Seu nome (opcional)", placeholder="Ex: João")
134
- pergunta = gr.Textbox(label="Sua dúvida sobre Python", placeholder="Ex: Como funcionam as estruturas de dados?")
135
- resposta = gr.Markdown(value="ℹ️ Aguardando sua pergunta...")
136
-
137
- botao_enviar = gr.Button("Enviar")
138
- botao_resetar = gr.Button("🔁 Resetar Memória")
139
- botao_exportar = gr.Button("📤 Exportar Histórico")
140
-
141
- botao_enviar.click(fn=responder, inputs=[pergunta, nome], outputs=resposta)
142
- botao_resetar.click(fn=resetar_memoria, outputs=resposta)
143
- botao_exportar.click(fn=exportar_conversas, outputs=resposta)
144
-
145
- app.launch(share=True)
146
- import json
147
- import os
148
- import re
149
- import pkg_resources
150
- from zipfile import ZipFile
151
- from google.colab import files
152
-
153
- # === 0. Upload do notebook ===
154
- print("📂 Faça upload do seu arquivo .ipynb")
155
- uploaded = files.upload()
156
- NOTEBOOK_PATH = list(uploaded.keys())[0] # Pega o nome do primeiro arquivo enviado
157
-
158
- APP_FILENAME = "app.py"
159
- REQUIREMENTS_FILENAME = "requirements.txt"
160
- ZIP_NAME = "huggingface_space.zip"
161
-
162
- # === 1. Lê o notebook .ipynb ===
163
- with open(NOTEBOOK_PATH, "r", encoding="utf-8") as f:
164
- notebook = json.load(f)
165
-
166
- # === 2. Extrai código das células ===
167
- codigo_total = ""
168
- for cell in notebook["cells"]:
169
- if cell["cell_type"] == "code":
170
- codigo_total += "".join(cell["source"]) + "\n\n"
171
-
172
- # === 3. Salva como app.py ===
173
- with open(APP_FILENAME, "w", encoding="utf-8") as f:
174
- f.write(codigo_total)
175
-
176
- print("✅ Código salvo como app.py")
177
-
178
- # === 4. Gera requirements.txt baseado nas bibliotecas importadas ===
179
- imports = set(re.findall(r'^\s*(?:import|from)\s+([a-zA-Z0-9_\.]+)', codigo_total, re.MULTILINE))
180
- installed = {pkg.key for pkg in pkg_resources.working_set}
181
- reais = sorted(set([i.split('.')[0].lower() for i in imports]) & installed)
182
-
183
- # Adiciona obrigatoriamente Gradio se tiver uso no código
184
- if "gradio" in codigo_total and "gradio" not in reais:
185
- reais.append("gradio")
186
-
187
- with open(REQUIREMENTS_FILENAME, "w") as f:
188
- f.write("\n".join(reais))
189
-
190
- print("✅ requirements.txt gerado com as libs detectadas")
191
-
192
- # === 5. Compacta tudo em um .zip ===
193
- with ZipFile(ZIP_NAME, "w") as zipf:
194
- zipf.write(APP_FILENAME)
195
- zipf.write(REQUIREMENTS_FILENAME)
196
-
197
- print(f"✅ Arquivo {ZIP_NAME} gerado com sucesso")
198
-
199
- # === 6. Oferece download do .zip ===
200
- files.download(ZIP_NAME)
201
-