Spaces:
Sleeping
Sleeping
Download app.py from douglasribeiro/treino_sql: direct link, hf CLI and curl.
- Browser
- Download file 19.6 kB
-
https://huggingface.co/spaces/douglasribeiro/treino_sql/resolve/main/app.py
- Command line
-
hf download hf://spaces/douglasribeiro/treino_sql/app.py
-
curl -L -o app.py https://huggingface.co/spaces/douglasribeiro/treino_sql/resolve/main/app.py
19.6 kB
| import os | |
| import sqlite3 | |
| import tempfile | |
| import shutil | |
| from datetime import datetime | |
| import pandas as pd | |
| import gradio as gr | |
| # ========================= | |
| # CONFIGURAÇÕES | |
| # ========================= | |
| DEFAULT_DB_PATH = "data/base_treinamento.db" | |
| # ========================= | |
| # FUNÇÕES AUXILIARES | |
| # ========================= | |
| def ensure_default_db(): | |
| """ | |
| Garante que exista um banco padrão mínimo para o app iniciar. | |
| Se você já tiver o seu .db real, basta colocá-lo em: | |
| data/base_treinamento.db | |
| """ | |
| if os.path.exists(DEFAULT_DB_PATH): | |
| return | |
| os.makedirs(os.path.dirname(DEFAULT_DB_PATH), exist_ok=True) | |
| conn = sqlite3.connect(DEFAULT_DB_PATH) | |
| cur = conn.cursor() | |
| cur.executescript( | |
| """ | |
| PRAGMA foreign_keys = ON; | |
| CREATE TABLE IF NOT EXISTS Categorias ( | |
| CategoriaID INTEGER PRIMARY KEY, | |
| Departamento TEXT, | |
| Categoria TEXT, | |
| MargemAlvoPct REAL | |
| ); | |
| CREATE TABLE IF NOT EXISTS Clientes ( | |
| ClienteID INTEGER PRIMARY KEY, | |
| Nome TEXT, | |
| Genero TEXT, | |
| DataNascimento TEXT, | |
| Cidade TEXT, | |
| Estado TEXT, | |
| Regiao TEXT, | |
| SegmentoCliente TEXT, | |
| FaixaRenda TEXT, | |
| DataCadastro TEXT, | |
| ScoreFidelidade INTEGER, | |
| Email TEXT | |
| ); | |
| CREATE TABLE IF NOT EXISTS Fornecedores ( | |
| FornecedorID INTEGER PRIMARY KEY, | |
| Fornecedor TEXT, | |
| PaisOrigem TEXT, | |
| Segmento TEXT, | |
| PrazoMedioDias INTEGER, | |
| Rating REAL | |
| ); | |
| CREATE TABLE IF NOT EXISTS Lojas ( | |
| LojaID INTEGER PRIMARY KEY, | |
| CodigoLoja TEXT, | |
| TipoLoja TEXT, | |
| Cidade TEXT, | |
| Estado TEXT, | |
| Regiao TEXT, | |
| DataAbertura TEXT, | |
| AreaM2 INTEGER, | |
| MetaMensal REAL | |
| ); | |
| CREATE TABLE IF NOT EXISTS Funcionarios ( | |
| FuncionarioID INTEGER PRIMARY KEY, | |
| LojaID INTEGER, | |
| Nome TEXT, | |
| Cargo TEXT, | |
| DataAdmissao TEXT, | |
| SalarioBase REAL, | |
| MetaMensal REAL, | |
| Turno TEXT, | |
| Status TEXT, | |
| FOREIGN KEY (LojaID) REFERENCES Lojas(LojaID) | |
| ); | |
| CREATE TABLE IF NOT EXISTS Produtos ( | |
| ProdutoID INTEGER PRIMARY KEY, | |
| SKU TEXT, | |
| Produto TEXT, | |
| Marca TEXT, | |
| CategoriaID INTEGER, | |
| FornecedorID INTEGER, | |
| CustoUnitario REAL, | |
| PrecoLista REAL, | |
| AtivoDesde TEXT, | |
| PesoKg REAL, | |
| StatusProduto TEXT, | |
| FOREIGN KEY (CategoriaID) REFERENCES Categorias(CategoriaID), | |
| FOREIGN KEY (FornecedorID) REFERENCES Fornecedores(FornecedorID) | |
| ); | |
| CREATE TABLE IF NOT EXISTS Pedidos ( | |
| PedidoID INTEGER PRIMARY KEY, | |
| DataPedido TEXT, | |
| ClienteID INTEGER, | |
| LojaID INTEGER, | |
| FuncionarioID INTEGER, | |
| CanalVenda TEXT, | |
| StatusPedido TEXT, | |
| Cupom TEXT, | |
| Frete REAL, | |
| DescontoPedido REAL, | |
| ValorItens REAL, | |
| ValorTotal REAL, | |
| FOREIGN KEY (ClienteID) REFERENCES Clientes(ClienteID), | |
| FOREIGN KEY (LojaID) REFERENCES Lojas(LojaID), | |
| FOREIGN KEY (FuncionarioID) REFERENCES Funcionarios(FuncionarioID) | |
| ); | |
| CREATE TABLE IF NOT EXISTS ItensPedido ( | |
| ItemID INTEGER, | |
| PedidoID INTEGER, | |
| ProdutoID INTEGER, | |
| Quantidade INTEGER, | |
| PrecoUnitario REAL, | |
| DescontoItemPct REAL, | |
| CustoUnitario REAL, | |
| FOREIGN KEY (PedidoID) REFERENCES Pedidos(PedidoID), | |
| FOREIGN KEY (ProdutoID) REFERENCES Produtos(ProdutoID) | |
| ); | |
| CREATE TABLE IF NOT EXISTS Pagamentos ( | |
| PagamentoID INTEGER, | |
| PedidoID INTEGER, | |
| SequenciaPagamento INTEGER, | |
| MetodoPagamento TEXT, | |
| Parcelas INTEGER, | |
| ValorPago REAL, | |
| StatusPagamento TEXT, | |
| DataPagamento TEXT, | |
| Gateway TEXT, | |
| FOREIGN KEY (PedidoID) REFERENCES Pedidos(PedidoID) | |
| ); | |
| """ | |
| ) | |
| cur.executescript( | |
| """ | |
| INSERT INTO Categorias VALUES | |
| (1, 'Mercearia', 'Alimentos', 0.30), | |
| (2, 'Bebidas', 'Refrigerantes', 0.25), | |
| (3, 'Higiene', 'Perfumaria', 0.35); | |
| INSERT INTO Fornecedores VALUES | |
| (1, 'Fornecedor Alfa', 'Brasil', 'Nacional', 15, 4.5), | |
| (2, 'Fornecedor Beta', 'Argentina', 'Importado', 22, 4.2); | |
| INSERT INTO Lojas VALUES | |
| (1, 'LJ001', 'Rua', 'São Paulo', 'SP', 'Sudeste', '2022-01-10', 300, 120000), | |
| (2, 'LJ002', 'Shopping', 'Campinas', 'SP', 'Sudeste', '2023-05-20', 180, 90000); | |
| INSERT INTO Clientes VALUES | |
| (1, 'Ana Souza', 'F', '1990-05-10', 'São Paulo', 'SP', 'Sudeste', 'Premium', 'Alta', '2024-01-10', 95, 'ana@email.com'), | |
| (2, 'Bruno Lima', 'M', '1988-08-20', 'Campinas', 'SP', 'Sudeste', 'Regular', 'Media', '2024-02-11', 80, 'bruno@email.com'), | |
| (3, 'Carla Mendes', 'F', '1995-02-15', 'Jundiaí', 'SP', 'Sudeste', 'Premium', 'Alta', '2024-03-01', 91, 'carla@email.com'); | |
| INSERT INTO Funcionarios VALUES | |
| (1, 1, 'Mariana Costa', 'Vendedora', '2023-01-05', 2500, 30000, 'Manhã', 'Ativo'), | |
| (2, 1, 'João Alves', 'Caixa', '2023-03-12', 2200, 20000, 'Tarde', 'Ativo'), | |
| (3, 2, 'Fernanda Rocha', 'Gerente', '2022-10-01', 5500, 60000, 'Integral', 'Ativo'); | |
| INSERT INTO Produtos VALUES | |
| (1, 'SKU001', 'Arroz 5kg', 'Marca A', 1, 1, 18.00, 27.90, '2023-01-01', 5.0, 'Ativo'), | |
| (2, 'SKU002', 'Refrigerante 2L', 'Marca B', 2, 2, 4.50, 8.99, '2023-01-01', 2.0, 'Ativo'), | |
| (3, 'SKU003', 'Shampoo 400ml', 'Marca C', 3, 1, 9.00, 18.50, '2023-01-01', 0.4, 'Ativo'); | |
| INSERT INTO Pedidos VALUES | |
| (1, '2026-04-01', 1, 1, 1, 'Loja Física', 'Concluído', 'DESC10', 5.00, 2.00, 45.88, 48.88), | |
| (2, '2026-04-02', 2, 1, 2, 'Site', 'Concluído', NULL, 8.00, 0.00, 27.90, 35.90), | |
| (3, '2026-04-03', 3, 2, 3, 'App', 'Concluído', 'APP5', 6.00, 1.50, 18.50, 23.00); | |
| INSERT INTO ItensPedido VALUES | |
| (1, 1, 2, 2, 8.99, 0.00, 4.50), | |
| (2, 1, 3, 1, 18.50, 0.10, 9.00), | |
| (3, 2, 1, 1, 27.90, 0.00, 18.00), | |
| (4, 3, 3, 1, 18.50, 0.00, 9.00); | |
| INSERT INTO Pagamentos VALUES | |
| (1, 1, 1, 'Cartão', 1, 48.88, 'Aprovado', '2026-04-01', 'GatewayX'), | |
| (2, 2, 1, 'Pix', 1, 35.90, 'Aprovado', '2026-04-02', 'GatewayY'), | |
| (3, 3, 1, 'Cartão', 2, 23.00, 'Aprovado', '2026-04-03', 'GatewayX'); | |
| """ | |
| ) | |
| conn.commit() | |
| conn.close() | |
| def create_lab_copy(source_db_path: str): | |
| """ | |
| Cria uma cópia temporária do banco para o modo laboratório. | |
| """ | |
| temp_dir = tempfile.mkdtemp(prefix="sql_lab_") | |
| lab_db_path = os.path.join(temp_dir, "lab.db") | |
| shutil.copy2(source_db_path, lab_db_path) | |
| return temp_dir, lab_db_path | |
| def connect_db(db_path: str): | |
| conn = sqlite3.connect(db_path, check_same_thread=False) | |
| conn.execute("PRAGMA foreign_keys = ON;") | |
| return conn | |
| def list_tables_and_columns(db_path: str) -> str: | |
| conn = connect_db(db_path) | |
| cur = conn.cursor() | |
| try: | |
| tables = cur.execute( | |
| """ | |
| SELECT name | |
| FROM sqlite_master | |
| WHERE type='table' | |
| AND name NOT LIKE 'sqlite_%' | |
| ORDER BY name; | |
| """ | |
| ).fetchall() | |
| lines = [] | |
| for (table_name,) in tables: | |
| lines.append(f"📦 {table_name}") | |
| cols = cur.execute(f'PRAGMA table_info("{table_name}")').fetchall() | |
| for col in cols: | |
| _, name, col_type, notnull, _, pk = col | |
| pk_txt = " [PK]" if pk else "" | |
| nn_txt = " NOT NULL" if notnull else "" | |
| lines.append(f" - {name} ({col_type}){pk_txt}{nn_txt}") | |
| lines.append("") | |
| return "\n".join(lines).strip() if lines else "Nenhuma tabela encontrada." | |
| finally: | |
| conn.close() | |
| def list_relationships(db_path: str) -> str: | |
| conn = connect_db(db_path) | |
| cur = conn.cursor() | |
| try: | |
| tables = cur.execute( | |
| """ | |
| SELECT name | |
| FROM sqlite_master | |
| WHERE type='table' | |
| AND name NOT LIKE 'sqlite_%' | |
| ORDER BY name; | |
| """ | |
| ).fetchall() | |
| lines = [] | |
| for (table_name,) in tables: | |
| fks = cur.execute(f'PRAGMA foreign_key_list("{table_name}")').fetchall() | |
| if fks: | |
| lines.append(f"🔗 {table_name}") | |
| for fk in fks: | |
| _, _, ref_table, from_col, to_col, on_update, on_delete, _ = fk | |
| lines.append( | |
| f" - {from_col} -> {ref_table}.{to_col} " | |
| f"(ON UPDATE {on_update}, ON DELETE {on_delete})" | |
| ) | |
| lines.append("") | |
| return "\n".join(lines).strip() if lines else "Nenhum relacionamento encontrado." | |
| finally: | |
| conn.close() | |
| def get_examples(): | |
| return { | |
| "SELECT básico": "SELECT * FROM Produtos LIMIT 10;", | |
| "WHERE": "SELECT * FROM Clientes WHERE Cidade = 'São Paulo';", | |
| "ORDER BY": "SELECT Produto, PrecoLista FROM Produtos ORDER BY PrecoLista DESC;", | |
| "GROUP BY": """ | |
| SELECT MetodoPagamento, SUM(ValorPago) AS TotalPago | |
| FROM Pagamentos | |
| GROUP BY MetodoPagamento; | |
| """.strip(), | |
| "JOIN": """ | |
| SELECT | |
| p.PedidoID, | |
| c.Nome AS Cliente, | |
| l.CodigoLoja, | |
| f.Nome AS Funcionario | |
| FROM Pedidos p | |
| JOIN Clientes c ON p.ClienteID = c.ClienteID | |
| JOIN Lojas l ON p.LojaID = l.LojaID | |
| JOIN Funcionarios f ON p.FuncionarioID = f.FuncionarioID; | |
| """.strip(), | |
| "JOIN com agregação": """ | |
| SELECT | |
| pr.Produto, | |
| SUM(ip.Quantidade) AS QuantidadeVendida | |
| FROM ItensPedido ip | |
| JOIN Produtos pr ON ip.ProdutoID = pr.ProdutoID | |
| GROUP BY pr.Produto | |
| ORDER BY QuantidadeVendida DESC; | |
| """.strip(), | |
| "HAVING": """ | |
| SELECT | |
| MetodoPagamento, | |
| SUM(ValorPago) AS Total | |
| FROM Pagamentos | |
| GROUP BY MetodoPagamento | |
| HAVING SUM(ValorPago) > 20; | |
| """.strip(), | |
| "Subquery": """ | |
| SELECT * | |
| FROM Produtos | |
| WHERE PrecoLista > ( | |
| SELECT AVG(PrecoLista) FROM Produtos | |
| ); | |
| """.strip(), | |
| "CTE": """ | |
| WITH TotalPorCliente AS ( | |
| SELECT | |
| c.ClienteID, | |
| c.Nome, | |
| SUM(p.ValorTotal) AS TotalGasto | |
| FROM Clientes c | |
| JOIN Pedidos p ON c.ClienteID = p.ClienteID | |
| GROUP BY c.ClienteID, c.Nome | |
| ) | |
| SELECT * | |
| FROM TotalPorCliente | |
| ORDER BY TotalGasto DESC; | |
| """.strip(), | |
| "INSERT": """ | |
| INSERT INTO Categorias (CategoriaID, Departamento, Categoria, MargemAlvoPct) | |
| VALUES (99, 'Teste', 'Categoria Teste', 0.20); | |
| """.strip(), | |
| "UPDATE": """ | |
| UPDATE Produtos | |
| SET PrecoLista = PrecoLista * 1.10 | |
| WHERE CategoriaID = 1; | |
| """.strip(), | |
| "DELETE": """ | |
| DELETE FROM Pagamentos | |
| WHERE PagamentoID = 999; | |
| """.strip(), | |
| "CREATE TABLE": """ | |
| CREATE TABLE Exemplo ( | |
| ID INTEGER PRIMARY KEY, | |
| Nome TEXT, | |
| Nota REAL | |
| ); | |
| """.strip(), | |
| } | |
| def load_example(example_name: str) -> str: | |
| return get_examples().get(example_name, "") | |
| def history_to_text(history): | |
| if not history: | |
| return "Nenhuma query executada ainda." | |
| return "\n\n".join( | |
| [f"[{item['horario']}] {item['sql']}" for item in history] | |
| ) | |
| def normalize_query(sql_text: str) -> str: | |
| return (sql_text or "").strip() | |
| def is_select_like(sql_text: str) -> bool: | |
| sql_upper = sql_text.strip().upper() | |
| return ( | |
| sql_upper.startswith("SELECT") | |
| or sql_upper.startswith("WITH") | |
| or sql_upper.startswith("PRAGMA") | |
| or sql_upper.startswith("EXPLAIN") | |
| ) | |
| def dataframe_to_csv_file(df: pd.DataFrame): | |
| """ | |
| Salva o DataFrame em CSV temporário e devolve o caminho para download. | |
| """ | |
| if df is None or df.empty: | |
| return None | |
| temp_dir = tempfile.mkdtemp(prefix="sql_csv_") | |
| timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") | |
| file_path = os.path.join(temp_dir, f"resultado_query_{timestamp}.csv") | |
| df.to_csv(file_path, index=False, encoding="utf-8-sig") | |
| return file_path | |
| def run_sql(sql_text: str, db_path: str, history): | |
| sql_text = normalize_query(sql_text) | |
| if not sql_text: | |
| return pd.DataFrame(), "Digite uma query SQL.", history, None | |
| conn = connect_db(db_path) | |
| cur = conn.cursor() | |
| try: | |
| if is_select_like(sql_text): | |
| df = pd.read_sql_query(sql_text, conn) | |
| msg = f"Consulta executada com sucesso. {len(df)} linha(s) retornada(s)." | |
| csv_file = dataframe_to_csv_file(df) | |
| else: | |
| cur.executescript(sql_text) | |
| conn.commit() | |
| df = pd.DataFrame({"status": ["OK"]}) | |
| msg = "Comando executado com sucesso." | |
| csv_file = None | |
| history = history or [] | |
| history.insert( | |
| 0, | |
| { | |
| "horario": datetime.now().strftime("%d/%m/%Y %H:%M:%S"), | |
| "sql": sql_text, | |
| }, | |
| ) | |
| history = history[:30] | |
| return df, msg, history, csv_file | |
| except Exception as e: | |
| return pd.DataFrame(), f"Erro ao executar SQL: {e}", history, None | |
| finally: | |
| conn.close() | |
| def use_uploaded_db(uploaded_file): | |
| if uploaded_file is None: | |
| return None, "Nenhum arquivo enviado." | |
| temp_dir = tempfile.mkdtemp(prefix="sql_upload_") | |
| target_path = os.path.join(temp_dir, "uploaded.db") | |
| shutil.copy2(uploaded_file.name, target_path) | |
| return target_path, f"Banco enviado carregado com sucesso: {os.path.basename(uploaded_file.name)}" | |
| def reset_lab(default_source_db: str): | |
| _, lab_db = create_lab_copy(default_source_db) | |
| schema = list_tables_and_columns(lab_db) | |
| relationships = list_relationships(lab_db) | |
| return lab_db, schema, relationships, "Banco de laboratório resetado com sucesso." | |
| # ========================= | |
| # INICIALIZAÇÃO | |
| # ========================= | |
| ensure_default_db() | |
| _, initial_lab_db = create_lab_copy(DEFAULT_DB_PATH) | |
| initial_schema = list_tables_and_columns(initial_lab_db) | |
| initial_relationships = list_relationships(initial_lab_db) | |
| example_names = list(get_examples().keys()) | |
| # ========================= | |
| # INTERFACE | |
| # ========================= | |
| with gr.Blocks(title="Laboratório SQL com SQLite") as demo: | |
| gr.Markdown( | |
| """ | |
| # Laboratório SQL com SQLite | |
| Treine SQL em um banco SQLite real. | |
| ### Recursos | |
| - carregamento automático do banco `.db` | |
| - upload de outro banco SQLite | |
| - editor SQL livre | |
| - execução de consultas | |
| - schema das tabelas | |
| - relacionamentos detectados | |
| - histórico de queries | |
| - exportação do resultado em CSV | |
| - reset do ambiente de laboratório | |
| """ | |
| ) | |
| db_state = gr.State(initial_lab_db) | |
| history_state = gr.State([]) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.Markdown("## Base de dados") | |
| upload_db = gr.File( | |
| label="Enviar outro arquivo .db ou .sqlite", | |
| file_types=[".db", ".sqlite"], | |
| ) | |
| btn_use_upload = gr.Button("Usar banco enviado") | |
| btn_reset = gr.Button("Resetar banco de laboratório") | |
| db_status = gr.Textbox( | |
| label="Status do banco", | |
| value="Banco padrão carregado.", | |
| interactive=False, | |
| ) | |
| gr.Markdown("## Exemplos") | |
| example_dropdown = gr.Dropdown( | |
| choices=example_names, | |
| label="Escolha um exemplo", | |
| value=example_names[0] if example_names else None, | |
| ) | |
| btn_load_example = gr.Button("Carregar exemplo no editor") | |
| with gr.Column(scale=2): | |
| gr.Markdown("## Editor SQL") | |
| sql_input = gr.Code( | |
| label="Digite sua query SQL", | |
| language="sql", | |
| value="SELECT * FROM Produtos LIMIT 10;", | |
| lines=16, | |
| ) | |
| btn_run = gr.Button("Executar SQL", variant="primary") | |
| sql_message = gr.Textbox(label="Mensagem", interactive=False) | |
| with gr.Row(): | |
| with gr.Column(scale=2): | |
| result_df = gr.Dataframe(label="Resultado da query", wrap=True) | |
| download_csv = gr.File(label="Baixar resultado em CSV") | |
| with gr.Column(scale=1): | |
| schema_box = gr.Textbox( | |
| label="Schema das tabelas", | |
| value=initial_schema, | |
| lines=22, | |
| interactive=False, | |
| ) | |
| with gr.Row(): | |
| with gr.Column(): | |
| rel_box = gr.Textbox( | |
| label="Relacionamentos detectados", | |
| value=initial_relationships, | |
| lines=12, | |
| interactive=False, | |
| ) | |
| with gr.Column(): | |
| history_box = gr.Textbox( | |
| label="Histórico das queries", | |
| value="Nenhuma query executada ainda.", | |
| lines=12, | |
| interactive=False, | |
| ) | |
| def handle_run(sql_text, current_db, history): | |
| df, msg, new_history, csv_file = run_sql(sql_text, current_db, history) | |
| schema = list_tables_and_columns(current_db) | |
| relationships = list_relationships(current_db) | |
| history_text = history_to_text(new_history) | |
| return df, msg, schema, relationships, new_history, history_text, csv_file | |
| btn_run.click( | |
| fn=handle_run, | |
| inputs=[sql_input, db_state, history_state], | |
| outputs=[ | |
| result_df, | |
| sql_message, | |
| schema_box, | |
| rel_box, | |
| history_state, | |
| history_box, | |
| download_csv, | |
| ], | |
| ) | |
| btn_load_example.click( | |
| fn=load_example, | |
| inputs=[example_dropdown], | |
| outputs=[sql_input], | |
| ) | |
| def handle_upload(uploaded_file): | |
| uploaded_db_path, msg = use_uploaded_db(uploaded_file) | |
| if uploaded_db_path is None: | |
| return ( | |
| gr.update(), | |
| msg, | |
| gr.update(), | |
| gr.update(), | |
| [], | |
| "Nenhuma query executada ainda.", | |
| None, | |
| ) | |
| schema = list_tables_and_columns(uploaded_db_path) | |
| relationships = list_relationships(uploaded_db_path) | |
| return ( | |
| uploaded_db_path, | |
| msg, | |
| schema, | |
| relationships, | |
| [], | |
| "Nenhuma query executada ainda.", | |
| None, | |
| ) | |
| btn_use_upload.click( | |
| fn=handle_upload, | |
| inputs=[upload_db], | |
| outputs=[ | |
| db_state, | |
| db_status, | |
| schema_box, | |
| rel_box, | |
| history_state, | |
| history_box, | |
| download_csv, | |
| ], | |
| ) | |
| def handle_reset(): | |
| lab_db, schema, relationships, msg = reset_lab(DEFAULT_DB_PATH) | |
| return ( | |
| lab_db, | |
| schema, | |
| relationships, | |
| msg, | |
| [], | |
| "Nenhuma query executada ainda.", | |
| None, | |
| ) | |
| btn_reset.click( | |
| fn=handle_reset, | |
| inputs=[], | |
| outputs=[ | |
| db_state, | |
| schema_box, | |
| rel_box, | |
| db_status, | |
| history_state, | |
| history_box, | |
| download_csv, | |
| ], | |
| ) | |
| demo.launch() |