diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 52e6721..7fef68b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,11 +20,25 @@ jobs: model: gpt-4o-mini - provider: google model: gemini-2.5-flash + # PostgreSQL para os testes que precisam de um banco real (fixture pg_engine) + services: + postgres: + image: postgres:16 + env: + POSTGRES_PASSWORD: postgres + ports: + - 5432:5432 + options: >- + --health-cmd pg_isready + --health-interval 5s + --health-timeout 5s + --health-retries 10 env: TEXT_TO_INSIGHT_TEST_PROVIDER: ${{ matrix.provider }} TEXT_TO_INSIGHT_TEST_MODEL: ${{ matrix.model }} OPENAI_API_KEY: ${{ matrix.provider == 'openai' && 'dummy-key' || '' }} GOOGLE_API_KEY: ${{ matrix.provider == 'google' && 'dummy-key' || '' }} + TEXT_TO_INSIGHT_TEST_PG_URL: postgresql+psycopg2://postgres:postgres@localhost:5432/postgres steps: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 @@ -33,7 +47,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install -r requirements.txt && pip install -e . + pip install -r requirements.txt && pip install -e ".[postgres,mysql]" - name: Download test database run: | mkdir -p data @@ -45,9 +59,10 @@ jobs: pytest tests/test_componentes.py tests/test_nodes.py \ tests/test_integracao.py tests/test_main_engine_integracao.py \ tests/test_biblioteca_integracao.py tests/test_data_exploration.py \ + tests/test_data_exploration_postgres.py \ tests/test_model_selection.py tests/test_token_tracking.py \ tests/test_bird_eval.py tests/test_spider2_eval.py \ - -v -s --record-mode=none -m "not real_api and not schemacrawler" + -v -s --record-mode=none -m "not real_api" record-vcr-cassettes: name: Record VCR cassettes - ${{ matrix.provider }} / ${{ matrix.model }} @@ -74,7 +89,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install -r requirements.txt && pip install -e . + pip install -r requirements.txt && pip install -e ".[postgres,mysql]" # Mesmo setup de banco dos outros jobs - name: Download test database @@ -140,7 +155,7 @@ jobs: - name: Install dependencies run: | python -m pip install --upgrade pip - pip install -r requirements.txt && pip install -e . + pip install -r requirements.txt && pip install -e ".[postgres,mysql]" # ✅ Banco de dados presente aqui também - name: Download test database diff --git a/.gitignore b/.gitignore index b53ab3b..89a16f3 100644 --- a/.gitignore +++ b/.gitignore @@ -100,6 +100,7 @@ celerybeat.pid # Environments .env .venv +projeto-raia/ env/ venv/ ENV/ diff --git a/README.md b/README.md index 628fe68..6ce4cff 100644 --- a/README.md +++ b/README.md @@ -1,225 +1,107 @@ # Text-to-Insight -Biblioteca Python para transformar perguntas em linguagem natural em SQL executada com seguranca em SQLite, com avaliacao automatica e resposta final em linguagem natural. +Biblioteca Python que transforma perguntas em linguagem natural em consultas SQL seguras, executadas no seu banco, com resposta final em linguagem natural (e gráfico, quando fizer sentido). -O namespace oficial do pacote e `text_to_insight`. +O fluxo é um grafo de agentes em [LangGraph](https://github.com/langchain-ai/langgraph): lê o schema do banco, seleciona as tabelas relevantes (GraphRAG), calcula estatísticas das colunas, gera a SQL, executa em modo somente leitura, corrige a si mesmo em caso de erro e responde. Opcionalmente pausa para pedir esclarecimentos ao usuário (human-in-the-loop). -## Contrato minimo - -O runtime padrao garante: - -- fluxo completo do grafo (planejador -> schema -> agente de codigo -> executor -> salvar CSV -> roteador grafico -> gerador grafico (quando aplicavel) -> resposta); -- loop de auto-correcao em caso de erro no executor (executor -> planejador -> agente de codigo); -- HITL ligado e desligado; -- retomada por `thread_id`; -- persistencia de metricas em `data/metricas_execucao.csv`; -- geracao opcional de graficos quando a visualizacao for relevante. - - -## Contrato HITL (perguntas) - -- `pergunta_original`: pergunta inicial da thread, imutavel apos o primeiro set. -- `pergunta_atual`: pergunta corrente e fonte de verdade para o fluxo. -- Em HITL, se a resposta do usuario for classificada como "nova pergunta", - o sistema atualiza `pergunta_atual` e reinicia o ciclo, sem alterar a original. - -## Instalacao +## Instalação ```bash -pip install -r requirements.txt -pip install -e . +pip install text-to-insight ``` -Configure a chave da API: +SQLite funciona sem nada extra. Para PostgreSQL ou MySQL, instale o driver junto: ```bash -echo "GOOGLE_API_KEY=sua_chave_aqui" > .env +pip install "text-to-insight[postgres]" # psycopg2 +pip install "text-to-insight[mysql]" # pymysql ``` +Modelos suportados: Gemini (`GOOGLE_API_KEY`) e OpenAI (`OPENAI_API_KEY`). + ## Uso como biblioteca +A biblioteca **não abre conexões com o banco**. Você cria uma [Engine do SQLAlchemy](https://docs.sqlalchemy.org/en/20/core/engines.html), passa para a `InsightEngine` e continua sendo dono dela (pool, credenciais, `dispose()`). A engine nunca entra no estado do grafo, então nada sobre a conexão vai para o checkpoint do LangGraph. + ```python +from sqlalchemy import create_engine from text_to_insight import InsightEngine +# SQLite em modo somente leitura +db = create_engine("sqlite:///file:dados/loja.db?mode=ro&uri=true") +# PostgreSQL: create_engine("postgresql+psycopg2://usuario:senha@host:5432/banco") + engine = InsightEngine( api_key="...", - model="google/gemini-2.5-flash", - db_path="data/olist_relational.db", + model="gemini-2.5-flash", # ou "gpt-5-mini", "openai/gpt-4o", ... + db_engine=db, hitl=True, - inferir_fks_virtuais=False, # (Opcional) Infere FKs baseadas em colunas _id (ex: tabelas do Spider 2) - usar_schemacrawler=False, # (Opcional) Ative caso queira introspecção via SchemaCrawler (default: False) ) -resultado = engine.run( - thread_id="sessao_1", - query="Quantos pedidos existem no banco?", -) +resultado = engine.run(thread_id="sessao_1", query="Quantos pedidos existem no banco?") if resultado.get("status") == "AWAITING_USER": - resultado = engine.resume( - thread_id="sessao_1", - user_response="Pode assumir status entregue.", - ) -``` - -API publica congelada do pacote: - -- `text_to_insight.InsightEngine` -- `text_to_insight.Graph` -- `text_to_insight.EstadoTextToInsight` - -Imports antigos via `src` nao sao mais suportados. - -## Uso via CLI - -O arquivo `main.py` e um adaptador fino da CLI da biblioteca. - -```bash -# via adaptador local -python main.py --hitl on "Quais categorias vendem mais?" - -# modo nao interativo -python main.py --hitl off "Quais categorias vendem mais?" - -# desativando schemacrawler e forçando FKs virtuais (Spider 2 local) -python main.py --hitl off --infer-fks on --use-schemacrawler off "Quantos times tem no banco?" - -# via entrypoint instalado pelo pacote -text-to-insight --hitl on "Quantos pedidos existem no banco?" -``` - -### Saida do terminal - -Apos a execucao, o resultado da query e exibido no bloco `RESULTADO` em formato tabular: - -``` ----------------------------------------------------------------------- -RESULTADO: ----------------------------------------------------------------------- -+------------+ -| COUNT(*) | -+============+ -| 99441 | -+------------+ -Total de linhas retornadas: 1 -``` - -O template de apresentacao usa `tabulate` para montar as linhas da query: -- Ate 5 linhas: exibe a tabela completa -- Acima de 5 linhas: mostra as 3 primeiras, omite as intermediarias, exibe as 2 ultimas -- Resultado completo e exportado em CSV em `results/` automaticamente - -### Geração de gráficos - -Quando o roteador de gráficos decide que a visualização é útil, um grafico é salvo em `graphs/` a partir do CSV de resultados. - -## Testes - -Camadas atuais: + print(resultado["message"]) # pergunta do agente para o usuário + resultado = engine.resume(thread_id="sessao_1", user_response="Considere só pedidos entregues.") -```bash -# Camada 1 - componentes deterministicos (sem API) -pytest tests/test_componentes.py -v -s - -# Camada 2 - nos individuais com VCR (replay, sem gravar) -pytest tests/test_nodes.py -v -s --record-mode=none - -# Camada 2 - nos individuais com VCR (gravar/atualizar cassetes) -pytest tests/test_nodes.py -v -s --record-mode=new_episodes - -# Camada 3 - integracao do grafo com VCR (replay, sem gravar) -pytest tests/test_integracao.py -v -s --record-mode=none - -# Camada 3 - integracao do grafo com VCR (gravar/atualizar cassetes) -pytest tests/test_integracao.py -v -s --record-mode=new_episodes - -# Integracao dedicada main + InsightEngine -pytest tests/test_main_engine_integracao.py -v -s -``` - -Fluxo recomendado de gravacao VCR: - -```bash -# gravar/atualizar -pytest tests/test_nodes.py tests/test_integracao.py -v -s --record-mode=new_episodes - -# validar replay deterministico -pytest tests/test_nodes.py tests/test_integracao.py -v -s --record-mode=none -``` - -As cassetes ficam em `tests/cassettes/`. - -Para gravar cassetes com um provider/modelo especifico, sobrescreva o ambiente antes de rodar o pytest: - -```bash -TEXT_TO_INSIGHT_TEST_PROVIDER=google \ -TEXT_TO_INSIGHT_TEST_MODEL=gemini-2.5-flash \ -pytest tests/test_nodes.py tests/test_integracao.py -v -s --record-mode=new_episodes -``` +print(resultado["sql_gerada"]) +print(resultado["resposta_natural"]) -```bash -TEXT_TO_INSIGHT_TEST_PROVIDER=openai \ -TEXT_TO_INSIGHT_TEST_MODEL=gpt-4o-mini \ -pytest tests/test_nodes.py tests/test_integracao.py -v -s --record-mode=new_episodes +db.dispose() ``` -Se você preferir definir em comandos separados, use `export` antes de rodar o `pytest`. Sem `export`, a variavel fica apenas no shell atual e os testes nao herdam o valor. +Toda SQL gerada passa por uma validação (apenas `SELECT`/`WITH`, uma única instrução, sem comandos de escrita ou de leitura de arquivos) e roda com timeout. Mesmo assim, use um usuário de banco com permissão só de leitura. -Uso recomendado: - -```bash -export TEXT_TO_INSIGHT_TEST_PROVIDER=google -export TEXT_TO_INSIGHT_TEST_MODEL=gemini-2.5-flash -pytest tests/test_nodes.py tests/test_integracao.py -v -s --record-mode=new_episodes -``` +### Opções da `InsightEngine` -Se quiser tudo em uma linha só, sem `export`, use: +| Parâmetro | Padrão | O que faz | +|---|---|---| +| `db_engine` | obrigatório | Engine do SQLAlchemy do banco a consultar. | +| `hitl` | `False` | Permite que o agente pause e peça esclarecimentos (`AWAITING_USER`). | +| `use_rag` | `True` | Seleciona só as tabelas relevantes quando o schema é grande (GraphRAG). | +| `enrich_rag` | `False` | Gera, com o LLM, descrições curtas das colunas antes do RAG. O resultado fica em cache. | +| `use_data_exploration` | `True` | Inclui estatísticas das colunas no prompt (SQLite e PostgreSQL; outros bancos pulam esta etapa). | +| `use_exploration_selector` | `"off"` | Escolhe quais colunas explorar: `"off"`, `"llm"` ou `"rag"`. | +| `use_cot` | `True` | Pede raciocínio passo a passo antes da SQL. | +| `inferir_fks_virtuais` | `False` | Infere chaves estrangeiras por nome (`*_id`) quando o banco não as declara. | +| `enable_graphs` | `True` | Gera um gráfico (matplotlib) quando a visualização for útil. | +| `model_kwargs` | `None` | Parâmetros do LLM, ex.: `{"temperature": 0}`. | +| `cache_dir` | pasta de cache do usuário | Onde ficam o schema enriquecido e o índice do ChromaDB. | -```bash -TEXT_TO_INSIGHT_TEST_PROVIDER=google TEXT_TO_INSIGHT_TEST_MODEL=gemini-2.5-flash \ -pytest tests/test_nodes.py tests/test_integracao.py -v -s --record-mode=new_episodes -``` +Por padrão o cache fica em `~/.cache/text-to-insight` (Linux), `~/Library/Caches/text-to-insight` (macOS) ou `%LOCALAPPDATA%\text-to-insight\Cache` (Windows). O schema enriquecido é indexado pelo conteúdo do schema: se o banco mudar, ele é gerado de novo. -Sem esses overrides, a suite tenta `GOOGLE_API_KEY` primeiro e depois `OPENAI_API_KEY`. +### Resultado -Teste opcional com API real (drift provider/modelo): +`run` e `resume` devolvem o estado final do grafo. Os campos mais úteis: -```bash -pytest tests/test_real_api_smoke.py -v -s -m real_api -``` +- `status`: `"aprovado"`, `"exec_erro"`, `"AWAITING_USER"` ou `"bloqueado_hitl"`; +- `sql_gerada`, `linhas_resultado_completo`, `total_linhas_resultado`; +- `resposta_natural`: resposta em linguagem natural; +- `caminho_csv_resultado`, `caminho_grafico`: caminhos do CSV com o resultado completo e do gráfico, quando gerado; +- `tokens_input`, `tokens_output`, `tokens_total`, `tokens_by_node`: uso de tokens. -## Benchmark Spider +API pública: `text_to_insight.InsightEngine`, `text_to_insight.Graph`, `text_to_insight.EstadoTextToInsight`. -Spider 1.0 (requer `spider_data/` com `dev.json` e `database/`): +## Uso via linha de comando ```bash -python scripts/test_spider_eval.py --sample-size 10 --seed 42 --data-dir spider_data -``` +export GOOGLE_API_KEY=... -Spider 2.0 Lite (requer `spider2-lite/` e bancos em `spider2-lite/resource/databases/spider2-localdb`): +# arquivo SQLite (aberto somente leitura) +text-to-insight --db-path dados/loja.db --model gemini-2.5-flash --api-key-env GOOGLE_API_KEY \ + "Quais categorias vendem mais?" -```bash -python scripts/test_spider2_eval.py --sample-size 10 --seed 42 \ - --data-dir spider2-lite \ - --sqlite-dir spider2-lite/resource/databases/spider2-localdb +# qualquer banco via URL (também lida de DATABASE_URL) +text-to-insight --db-url postgresql://usuario:senha@host:5432/banco --hitl off \ + "Qual o ticket médio por estado?" ``` -## CI hibrida - -Workflow em `.github/workflows/ci.yml`: +`text-to-insight --help` lista as demais opções (`--hitl`, `--enrich-rag`, `--infer-fks`, `--cot`, `--data-exploration`, `--exploration-selector`, `--temperature`, `--max-tokens`). -- `tests-vcr`: job padrao em PR/push com execucao deterministica (`--record-mode=none`); -- `record-vcr-cassettes`: job manual em `workflow_dispatch` para gravar/atualizar cassetes e publicar artifact; -- `tests-real-api`: job opcional manual/noturno com `GOOGLE_API_KEY` real para detectar drift. +## Desenvolvimento -## Validacao de distribuicao +- [Guia de desenvolvimento e testes](https://github.com/gruporaia/TextToInsight/blob/main/docs/DESENVOLVIMENTO.md) +- [Arquitetura](https://github.com/gruporaia/TextToInsight/blob/main/docs/ARQUITETURA.md) +- Benchmarks: [BIRD](https://github.com/gruporaia/TextToInsight/blob/main/docs/BENCHMARK_BIRD.md), [Spider 1.0 e 2.0](https://github.com/gruporaia/TextToInsight/blob/main/docs/BENCHMARK_SPIDER.md) -```bash -python -m build - -python -m venv .venv-smoke -source .venv-smoke/bin/activate -pip install dist/*.whl - -python -c "from text_to_insight import InsightEngine, Graph; print('import_ok')" -``` +Desenvolvido pelo grupo RAIA (USP). Licença MIT. diff --git a/commit.txt b/commit.txt deleted file mode 100644 index a310cc7..0000000 --- a/commit.txt +++ /dev/null @@ -1,13 +0,0 @@ -fix(bird): harden query executor sandbox and improve csv reporter robustness - -- Query Executor (`src/bird/query_executor.py`): - - Strip single/double quoted string literals and comments prior to regex inspection in `_verify_read_only_intent`, preventing false-positive permission blocks on read-only queries with mutation keywords (e.g., `WHERE status = 'DELETE'`). - - Introduce safe wrappers (`_safe_trig`, `_safe_abs`, `_safe_sign`) for SQLite mathematical and trigonometric UDFs (`SIN`, `COS`, `TAN`, `ASIN`, `ACOS`, `ATAN`, `RADIANS`, `DEGREES`, `ABS`, `SIGN`), gracefully evaluating non-numeric/text input to SQL `NULL` instead of aborting queries with `OperationalError`. - -- CSV Reporter (`src/bird/csv_reporter.py`): - - Add defensive sort by `attempt_number` in `export_predictions_from_rows` and `generate_summary` to ensure accurate final predictions and self-correction calculations regardless of row ordering. - - Support unified key resolution (`sql`/`agent_sql` and `erro`/`error`) in `format_markdown_report`, ensuring attempts extracted from either in-memory states or serialized CSV rows render properly. - - Guard `format_result_rows_markdown_table` against 0-column tuples (`[()]`), rendering `"*(0 columns returned)*"`. - -- Tests (`tests/test_bird_eval.py`): - - Add test cases covering string literal mutation bypass, safe non-numeric trig evaluation, 0-column table formatting, and markdown report key fallback. diff --git a/ARQUITETURA.md b/docs/ARQUITETURA.md similarity index 66% rename from ARQUITETURA.md rename to docs/ARQUITETURA.md index f8a44e9..2999f6c 100644 --- a/ARQUITETURA.md +++ b/docs/ARQUITETURA.md @@ -94,7 +94,19 @@ Arquivos: - `text_to_insight/cli.py` - `main.py` -`main.py` e um wrapper fino da CLI do pacote. +`main.py` e um wrapper fino da CLI do pacote. O CLI e quem cria a Engine do +SQLAlchemy (a partir de `--db-path` ou `--db-url`) e a descarta ao final. + +### 5) Conexao com o banco e cache + +- A `InsightEngine` recebe `db_engine`, uma Engine do SQLAlchemy criada e + descartada pelo chamador. A biblioteca nunca abre conexoes por conta propria. +- `graph.py` injeta a engine nos nos que acessam o banco (schema, data + exploration, agente de codigo e executor) via `functools.partial`. Ela nunca + entra no estado, entao nada sobre a conexao vai para o checkpoint. +- `text_to_insight/cache.py` define a pasta de cache (padrao do usuario via + `platformdirs`, ou `cache_dir`), com o schema enriquecido indexado pelo hash + do schema e o indice do ChromaDB. ## Nos do grafo @@ -111,8 +123,27 @@ Arquivos: ### Schema (`text_to_insight/nodes/schema.py`) -- introspeccao SQLite real em modo read-only -- extrai tabelas, colunas e relacionamentos +- introspeccao via `sqlalchemy.inspect` na Engine do chamador (qualquer dialeto suportado pelo SQLAlchemy) +- extrai tabelas, colunas (tipo, PK, NOT NULL, DEFAULT) e chaves estrangeiras +- opcionalmente infere FKs virtuais pelo nome das colunas (`inferir_fks_virtuais`) +- com `enrich_rag` ligado, reaproveita o schema enriquecido do cache (`tem_descricao=True`) + +### Enriquecimento (`text_to_insight/nodes/enrich_schema.py`, opcional) + +- gera descricoes curtas das colunas com o LLM, em lotes, e grava o resultado no cache + +### Retriever (`text_to_insight/nodes/retriever.py`) + +- para schemas grandes, recupera so as tabelas relevantes (ChromaDB + grafo de FKs) em `contexto_rag_schema` + +### Seletor de colunas e Data Exploration (`text_to_insight/nodes/data_exploration.py`) + +- o seletor (`off`, `llm` ou `rag`) escolhe quais colunas explorar +- a exploracao calcula estatisticas por coluna numa amostra de ate 10 mil linhas (SQLite e PostgreSQL) e guarda em `cache_data_exploration` para nao repetir trabalho dentro da mesma pergunta +- todas as estatisticas de uma coluna (media, mediana, desvio, min, max, nulos) saem da mesma amostra, e os valores de exemplo sao sorteados com semente fixa por coluna +- no PostgreSQL roda numa transacao somente leitura, com timeout por consulta, desfeita ao final (se a engine usa autocommit, ele e desligado durante a exploracao e religado depois); tabelas sao resolvidas pelo `search_path`, como no no de schema +- cada tabela, coluna e consulta opcional roda num savepoint: o que falhar e pulado sem derrubar o resto, e se a conexao cair as tabelas ja exploradas sao mantidas +- tabelas com estimativa do catalogo acima de 100 mil linhas usam a estimativa; abaixo disso (ou sem estimativa) a contagem para em 100 mil ### Agente de Codigo (`text_to_insight/nodes/code_agent/code_agent.py`) @@ -120,7 +151,7 @@ Arquivos: ### Executor (`text_to_insight/nodes/sandbox.py`) -- valida SQL e executa via `code_sql.py` +- valida SQL e executa na Engine do chamador via `executar_sql_via_engine` (`code_sql.py`), com timeout e sessao somente leitura quando o dialeto permite - devolve preview + total de linhas completas - em caso de erro de sintaxe/execucao, define `status: exec_erro` e captura `erro_execucao` @@ -156,7 +187,8 @@ Campos obrigatorios: - `pergunta_original` - `pergunta_atual` -- `db_path` + +O banco nao faz parte do estado: a Engine e injetada nos nos (ver "Conexao com o banco e cache"). Campos principais do fluxo: @@ -164,14 +196,14 @@ Campos principais do fluxo: - `erro_execucao`, `saida_terminal`, `resposta_natural` - `status`, `tentativas_loop`, `historico_conversa`, `espera_humana`, `pergunta_ao_usuario`, `historico_tentativas` - `caminho_csv_resultado`, `grafico_gerado`, `caminho_grafico` -- telemetria: `tokens_input`, `tokens_output`, `tokens_total` +- telemetria: `tokens_input`, `tokens_output`, `tokens_total`, `tokens_by_node` ## Benchmarks -- BIRD Benchmark: `scripts/test_bird_eval.py` + `src/bird/` (loader, executor read-only, metrics, csv_reporter, BENCHMARK.md) +- BIRD Benchmark: `scripts/test_bird_eval.py` + `src/bird/` (loader, executor read-only, metrics, csv_reporter); manual em [BENCHMARK_BIRD.md](BENCHMARK_BIRD.md) - Spider 1.0: `scripts/test_spider_eval.py` - Spider 2.0 Lite: `scripts/test_spider2_eval.py` -- Componentes Spider: `src/spider/` (loader, executor, metrics, csv_reporter, analise_empirica, BENCHMARK.md) +- Componentes Spider: `src/spider/` (loader, executor, metrics, csv_reporter, analise_empirica); manual em [BENCHMARK_SPIDER.md](BENCHMARK_SPIDER.md) ## HITL e perguntas diff --git a/src/bird/BENCHMARK.md b/docs/BENCHMARK_BIRD.md similarity index 99% rename from src/bird/BENCHMARK.md rename to docs/BENCHMARK_BIRD.md index 7f7873a..329dd07 100644 --- a/src/bird/BENCHMARK.md +++ b/docs/BENCHMARK_BIRD.md @@ -117,7 +117,6 @@ O orquestrador de avaliacao e acionado via `scripts/test_bird_eval.py`. | `--cot` | `on`, `off` | `on` | Ativa raciocinio explicito passo a passo (Chain of Thought). | | `--data-exploration` | `on`, `off` | `on` | Permite que o agente consulte amostras de valores nas tabelas. | | `--exploration-selector` | `off`, `heuristic`, `llm` | `off` | Modo de selecao de colunas para exploracao de dados. | -| `--schemacrawler` | `on`, `off` | `off` | Ativa/desativa introspeccao via SchemaCrawler (padrao: `off`, usa PRAGMA nativo do SQLite). | | `--timeout` | Inteiro | `30` | Tempo limite em segundos para execucao de queries no SQLite. | | `--dry-run` | Flag | Desativado | Simula a geracao de SQL sem custo de API. | | `--log` | `on`, `off` | `on` | Controla geracao do arquivo de log detalhado de execucao (`.log`). | diff --git a/src/spider/BENCHMARK.md b/docs/BENCHMARK_SPIDER.md similarity index 98% rename from src/spider/BENCHMARK.md rename to docs/BENCHMARK_SPIDER.md index eda09e1..ebe009a 100644 --- a/src/spider/BENCHMARK.md +++ b/docs/BENCHMARK_SPIDER.md @@ -126,8 +126,6 @@ The Spider 2.0 evaluation orchestrator is invoked via `scripts/test_spider2_eval | `--cot` | `on`, `off` | `on` | Enables Chain-of-Thought explicit reasoning in Code Agent. | | `--data-exploration` | `on`, `off` | `on` | Enables active exploratory SQL sampling against tables. | | `--exploration-selector` | `off`, `llm`, `rag` | `off` | Column selection mode for data exploration. | -| `--schemacrawler` | `on`, `off` | `off` | Enables SchemaCrawler database introspection (default: `off`). | -| `--no-schemacrawler` | Flag | Disabled | Deprecated alias to disable SchemaCrawler introspection. | | `--infer-fks` | `on`, `off` | `off` | Enables virtual foreign key inference heuristic. | | `--with-graphs` | `on`, `off` | `off` | Enables chart generation (matplotlib) and CSV data exports. | | `--use-evidence` | `on`, `off` | `on` | Injects external knowledge documents and hints into prompt context. | diff --git a/DESENVOLVIMENTO.md b/docs/DESENVOLVIMENTO.md similarity index 75% rename from DESENVOLVIMENTO.md rename to docs/DESENVOLVIMENTO.md index 1ef53e1..a42b031 100644 --- a/DESENVOLVIMENTO.md +++ b/docs/DESENVOLVIMENTO.md @@ -22,13 +22,13 @@ python -m venv .venv source .venv/bin/activate pip install -r requirements.txt -pip install -e . +pip install -e ".[dev,postgres,mysql]" ``` - `python -m venv .venv`: cria um ambiente isolado. - `source .venv/bin/activate`: ativa esse ambiente. -- `pip install -r requirements.txt`: instala dependências de runtime e ferramentas de teste usadas no projeto. -- `pip install -e .`: instala o TextToInsight em modo editável usando os metadados do `pyproject.toml`. +- `pip install -r requirements.txt`: instala as versões fixadas de runtime e das ferramentas de teste (é o que a CI usa). +- `pip install -e ".[dev,postgres,mysql]"`: instala o TextToInsight em modo editável, com as ferramentas de desenvolvimento e os drivers de PostgreSQL/MySQL (extras do `pyproject.toml`). ### Configuração @@ -36,7 +36,11 @@ pip install -e . echo "GOOGLE_API_KEY=sua_chave" > .env ``` -Banco SQLite esperado por padrão: `data/olist_relational.db`. +Banco de teste (Olist, ~130 MB), usado pela suíte de testes e pelos exemplos abaixo: + +```bash +gh release download dados-teste -R gruporaia/TextToInsight -p olist_relational.db -D data/ +``` ### Verificação Rápida (Smoke) de import @@ -44,6 +48,32 @@ Banco SQLite esperado por padrão: `data/olist_relational.db`. python -c "from text_to_insight import InsightEngine, Graph; print('OK')" ``` +## Conexão com o banco + +A biblioteca não abre conexões. Quem usa a `InsightEngine` cria uma Engine do +SQLAlchemy e passa em `db_engine`; a engine é injetada direto nos nós do grafo +(via `functools.partial` em `graph.py`) e nunca entra no estado, então nada +sobre a conexão vai para o checkpoint do LangGraph. O dialeto do prompt vem de +`engine.dialect.name`. + +Quem abre conexões são os chamadores: o CLI (`text_to_insight/cli.py`, a partir +de `--db-path` ou `--db-url`), os scripts de avaliação em `scripts/` e os +testes (fixture `olist_engine` em `tests/conftest.py`). Todos abrem SQLite em +modo somente leitura (`sqlite:///file:...?mode=ro&uri=true`). + +## Cache em disco + +`text_to_insight/cache.py` concentra o que a biblioteca grava entre execuções, +numa pasta por usuário (via `platformdirs`) ou em `InsightEngine(cache_dir=...)`: + +- `schemas/_enriched.txt`: schema enriquecido pelo LLM (`enrich_rag`), + indexado pelo hash do schema. Só é lido quando `enrich_rag` está ligado, para + que execuções sem enriquecimento nunca recebam descrições de execuções anteriores; +- `chroma_db/`: índice do ChromaDB do RAG e do seletor de colunas. + +Nos testes, a fixture `cache_dir_isolado` (autouse) redireciona o cache para uma +pasta temporária. + ## Contrato de execução API estável da engine: @@ -71,17 +101,20 @@ Critérios mínimos: ```bash # adaptador local -python main.py --hitl on "Quantos pedidos existem no banco?" +python main.py --db-path data/olist_relational.db --hitl on "Quantos pedidos existem no banco?" # biblioteca instalada (entrypoint) -text-to-insight --hitl off "Quais categorias vendem mais?" +text-to-insight --db-path data/olist_relational.db --hitl off "Quais categorias vendem mais?" # com modelo OpenAI set -a && source .env && set +a -python main.py --hitl off --model openai/gpt-4o-mini --api-key-env OPENAI_API_KEY "Quantos pedidos existem?" +python main.py --db-path data/olist_relational.db --hitl off --model openai/gpt-4o-mini --api-key-env OPENAI_API_KEY "Quantos pedidos existem?" + +# bancos sem FK declarada (ex.: Spider 2): inferência de FKs pelo nome das colunas +python main.py --db-path caminho/do/banco.sqlite --hitl off --infer-fks on "Qual a soma dos resultados?" -# testes locais com bancos do Spider 2 (SQLite sem FK explícita e PRAGMA nativo) -python main.py --hitl off --infer-fks on --use-schemacrawler off "Qual a soma dos resultados?" +# PostgreSQL/MySQL via URL (ou variável DATABASE_URL) +python main.py --db-url postgresql://usuario:senha@host:5432/banco --hitl off "Quantos clientes existem?" ``` O resultado é exibido no terminal em formato tabular sob o bloco `RESULTADO:`, junto com SQL gerada, status de execução e resposta natural. @@ -105,9 +138,14 @@ text_to_insight/ runtime.py graph.py state.py - model_selection.py + cache.py + model_selection/ nodes/ + retriever/ routers/ +scripts/ # avaliação em benchmarks (Spider, Spider 2.0, BIRD) +src/ # componentes dos benchmarks (loaders, executores, métricas) +docs/ tests/ test_componentes.py test_nodes.py @@ -142,8 +180,16 @@ pytest tests/test_main_engine_integracao.py -v -s # integracao do pacote como biblioteca (sem chamadas de API, testa HITL e run/resume) pytest tests/test_biblioteca_integracao.py -v -s + +# data exploration em PostgreSQL (pulados sem TEXT_TO_INSIGHT_TEST_PG_URL) +TEXT_TO_INSIGHT_TEST_PG_URL=postgresql+psycopg2://postgres:postgres@localhost:5432/postgres \ +pytest tests/test_data_exploration_postgres.py -v ``` +Os testes de PostgreSQL criam e apagam o schema `tti_testes` no banco da URL; +use um banco descartável. Na CI, o job `tests-vcr` sobe um serviço `postgres:16` +e define a variável. + ### Gravação de cassetes VCR (fluxo recomendado) Use este fluxo quando mudar prompts, comportamento de nos ou quando adicionar testes com `@pytest.mark.vcr`: @@ -281,7 +327,7 @@ python scripts/test_bird_eval.py --sample-size 50 --seed 123 --rag off --output ``` Opções úteis: `--db-filter`, `--difficulty` (`simple`, `moderate`, `challenging`), `--stratify`, `--use-evidence` (`on`/`off`), `--dry-run`, `--output`. -Consulte o manual operacional completo em `src/bird/BENCHMARK.md`. +Consulte o manual operacional completo em [BENCHMARK_BIRD.md](BENCHMARK_BIRD.md). Spider 1.0 e 2.0: [BENCHMARK_SPIDER.md](BENCHMARK_SPIDER.md). ## CI hibrida @@ -310,9 +356,11 @@ python -c "from text_to_insight import InsightEngine; print('wheel_ok')" `ModuleNotFoundError`: ```bash pip install -r requirements.txt -pip install -e . +pip install -e ".[dev,postgres,mysql]" ``` +`No module named 'psycopg2'` / `'pymysql'`: instale o extra do banco, ex.: `pip install "text-to-insight[postgres]"`. + `429 RESOURCE_EXHAUSTED`: - aguardar reset de quota; - preferir testes com VCR no dia a dia. @@ -320,4 +368,4 @@ pip install -e . ## Configuração do .env (variáveis de ambiente) - `GOOGLE_API_KEY`: chave de API para Google Gemini (se usar modelo Gemini). - `OPENAI_API_KEY`: chave de API para OpenAI (se usar modelo OpenAI). -- `SCHEMACRAWLER_BIN`: caminho para o binário do SchemaCrawler (se usar este recurso). +- `DATABASE_URL`: URL do banco usada pelo CLI quando `--db-url` não é informado. diff --git a/projeto-raia/bin/Activate.ps1 b/projeto-raia/bin/Activate.ps1 deleted file mode 100644 index b49d77b..0000000 --- a/projeto-raia/bin/Activate.ps1 +++ /dev/null @@ -1,247 +0,0 @@ -<# -.Synopsis -Activate a Python virtual environment for the current PowerShell session. - -.Description -Pushes the python executable for a virtual environment to the front of the -$Env:PATH environment variable and sets the prompt to signify that you are -in a Python virtual environment. Makes use of the command line switches as -well as the `pyvenv.cfg` file values present in the virtual environment. - -.Parameter VenvDir -Path to the directory that contains the virtual environment to activate. The -default value for this is the parent of the directory that the Activate.ps1 -script is located within. - -.Parameter Prompt -The prompt prefix to display when this virtual environment is activated. By -default, this prompt is the name of the virtual environment folder (VenvDir) -surrounded by parentheses and followed by a single space (ie. '(.venv) '). - -.Example -Activate.ps1 -Activates the Python virtual environment that contains the Activate.ps1 script. - -.Example -Activate.ps1 -Verbose -Activates the Python virtual environment that contains the Activate.ps1 script, -and shows extra information about the activation as it executes. - -.Example -Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv -Activates the Python virtual environment located in the specified location. - -.Example -Activate.ps1 -Prompt "MyPython" -Activates the Python virtual environment that contains the Activate.ps1 script, -and prefixes the current prompt with the specified string (surrounded in -parentheses) while the virtual environment is active. - -.Notes -On Windows, it may be required to enable this Activate.ps1 script by setting the -execution policy for the user. You can do this by issuing the following PowerShell -command: - -PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser - -For more information on Execution Policies: -https://go.microsoft.com/fwlink/?LinkID=135170 - -#> -Param( - [Parameter(Mandatory = $false)] - [String] - $VenvDir, - [Parameter(Mandatory = $false)] - [String] - $Prompt -) - -<# Function declarations --------------------------------------------------- #> - -<# -.Synopsis -Remove all shell session elements added by the Activate script, including the -addition of the virtual environment's Python executable from the beginning of -the PATH variable. - -.Parameter NonDestructive -If present, do not remove this function from the global namespace for the -session. - -#> -function global:deactivate ([switch]$NonDestructive) { - # Revert to original values - - # The prior prompt: - if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) { - Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt - Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT - } - - # The prior PYTHONHOME: - if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) { - Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME - Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME - } - - # The prior PATH: - if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) { - Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH - Remove-Item -Path Env:_OLD_VIRTUAL_PATH - } - - # Just remove the VIRTUAL_ENV altogether: - if (Test-Path -Path Env:VIRTUAL_ENV) { - Remove-Item -Path env:VIRTUAL_ENV - } - - # Just remove VIRTUAL_ENV_PROMPT altogether. - if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) { - Remove-Item -Path env:VIRTUAL_ENV_PROMPT - } - - # Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether: - if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) { - Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force - } - - # Leave deactivate function in the global namespace if requested: - if (-not $NonDestructive) { - Remove-Item -Path function:deactivate - } -} - -<# -.Description -Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the -given folder, and returns them in a map. - -For each line in the pyvenv.cfg file, if that line can be parsed into exactly -two strings separated by `=` (with any amount of whitespace surrounding the =) -then it is considered a `key = value` line. The left hand string is the key, -the right hand is the value. - -If the value starts with a `'` or a `"` then the first and last character is -stripped from the value before being captured. - -.Parameter ConfigDir -Path to the directory that contains the `pyvenv.cfg` file. -#> -function Get-PyVenvConfig( - [String] - $ConfigDir -) { - Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg" - - # Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue). - $pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue - - # An empty map will be returned if no config file is found. - $pyvenvConfig = @{ } - - if ($pyvenvConfigPath) { - - Write-Verbose "File exists, parse `key = value` lines" - $pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath - - $pyvenvConfigContent | ForEach-Object { - $keyval = $PSItem -split "\s*=\s*", 2 - if ($keyval[0] -and $keyval[1]) { - $val = $keyval[1] - - # Remove extraneous quotations around a string value. - if ("'""".Contains($val.Substring(0, 1))) { - $val = $val.Substring(1, $val.Length - 2) - } - - $pyvenvConfig[$keyval[0]] = $val - Write-Verbose "Adding Key: '$($keyval[0])'='$val'" - } - } - } - return $pyvenvConfig -} - - -<# Begin Activate script --------------------------------------------------- #> - -# Determine the containing directory of this script -$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition -$VenvExecDir = Get-Item -Path $VenvExecPath - -Write-Verbose "Activation script is located in path: '$VenvExecPath'" -Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)" -Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)" - -# Set values required in priority: CmdLine, ConfigFile, Default -# First, get the location of the virtual environment, it might not be -# VenvExecDir if specified on the command line. -if ($VenvDir) { - Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values" -} -else { - Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir." - $VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/") - Write-Verbose "VenvDir=$VenvDir" -} - -# Next, read the `pyvenv.cfg` file to determine any required value such -# as `prompt`. -$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir - -# Next, set the prompt from the command line, or the config file, or -# just use the name of the virtual environment folder. -if ($Prompt) { - Write-Verbose "Prompt specified as argument, using '$Prompt'" -} -else { - Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value" - if ($pyvenvCfg -and $pyvenvCfg['prompt']) { - Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'" - $Prompt = $pyvenvCfg['prompt']; - } - else { - Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)" - Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'" - $Prompt = Split-Path -Path $venvDir -Leaf - } -} - -Write-Verbose "Prompt = '$Prompt'" -Write-Verbose "VenvDir='$VenvDir'" - -# Deactivate any currently active virtual environment, but leave the -# deactivate function in place. -deactivate -nondestructive - -# Now set the environment variable VIRTUAL_ENV, used by many tools to determine -# that there is an activated venv. -$env:VIRTUAL_ENV = $VenvDir - -if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) { - - Write-Verbose "Setting prompt to '$Prompt'" - - # Set the prompt to include the env name - # Make sure _OLD_VIRTUAL_PROMPT is global - function global:_OLD_VIRTUAL_PROMPT { "" } - Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT - New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt - - function global:prompt { - Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) " - _OLD_VIRTUAL_PROMPT - } - $env:VIRTUAL_ENV_PROMPT = $Prompt -} - -# Clear PYTHONHOME -if (Test-Path -Path Env:PYTHONHOME) { - Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME - Remove-Item -Path Env:PYTHONHOME -} - -# Add the venv to the PATH -Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH -$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH" diff --git a/projeto-raia/bin/activate b/projeto-raia/bin/activate deleted file mode 100644 index 503c906..0000000 --- a/projeto-raia/bin/activate +++ /dev/null @@ -1,70 +0,0 @@ -# This file must be used with "source bin/activate" *from bash* -# You cannot run it directly - -deactivate () { - # reset old environment variables - if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then - PATH="${_OLD_VIRTUAL_PATH:-}" - export PATH - unset _OLD_VIRTUAL_PATH - fi - if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then - PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}" - export PYTHONHOME - unset _OLD_VIRTUAL_PYTHONHOME - fi - - # Call hash to forget past commands. Without forgetting - # past commands the $PATH changes we made may not be respected - hash -r 2> /dev/null - - if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then - PS1="${_OLD_VIRTUAL_PS1:-}" - export PS1 - unset _OLD_VIRTUAL_PS1 - fi - - unset VIRTUAL_ENV - unset VIRTUAL_ENV_PROMPT - if [ ! "${1:-}" = "nondestructive" ] ; then - # Self destruct! - unset -f deactivate - fi -} - -# unset irrelevant variables -deactivate nondestructive - -# on Windows, a path can contain colons and backslashes and has to be converted: -if [ "${OSTYPE:-}" = "cygwin" ] || [ "${OSTYPE:-}" = "msys" ] ; then - # transform D:\path\to\venv to /d/path/to/venv on MSYS - # and to /cygdrive/d/path/to/venv on Cygwin - export VIRTUAL_ENV=$(cygpath /home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia) -else - # use the path as-is - export VIRTUAL_ENV=/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia -fi - -_OLD_VIRTUAL_PATH="$PATH" -PATH="$VIRTUAL_ENV/"bin":$PATH" -export PATH - -# unset PYTHONHOME if set -# this will fail if PYTHONHOME is set to the empty string (which is bad anyway) -# could use `if (set -u; : $PYTHONHOME) ;` in bash -if [ -n "${PYTHONHOME:-}" ] ; then - _OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}" - unset PYTHONHOME -fi - -if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then - _OLD_VIRTUAL_PS1="${PS1:-}" - PS1='(projeto-raia) '"${PS1:-}" - export PS1 - VIRTUAL_ENV_PROMPT='(projeto-raia) ' - export VIRTUAL_ENV_PROMPT -fi - -# Call hash to forget past commands. Without forgetting -# past commands the $PATH changes we made may not be respected -hash -r 2> /dev/null diff --git a/projeto-raia/bin/activate.csh b/projeto-raia/bin/activate.csh deleted file mode 100644 index 62b36bd..0000000 --- a/projeto-raia/bin/activate.csh +++ /dev/null @@ -1,27 +0,0 @@ -# This file must be used with "source bin/activate.csh" *from csh*. -# You cannot run it directly. - -# Created by Davide Di Blasi . -# Ported to Python 3.3 venv by Andrew Svetlov - -alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate' - -# Unset irrelevant variables. -deactivate nondestructive - -setenv VIRTUAL_ENV /home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia - -set _OLD_VIRTUAL_PATH="$PATH" -setenv PATH "$VIRTUAL_ENV/"bin":$PATH" - - -set _OLD_VIRTUAL_PROMPT="$prompt" - -if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then - set prompt = '(projeto-raia) '"$prompt" - setenv VIRTUAL_ENV_PROMPT '(projeto-raia) ' -endif - -alias pydoc python -m pydoc - -rehash diff --git a/projeto-raia/bin/activate.fish b/projeto-raia/bin/activate.fish deleted file mode 100644 index 803ed0d..0000000 --- a/projeto-raia/bin/activate.fish +++ /dev/null @@ -1,69 +0,0 @@ -# This file must be used with "source /bin/activate.fish" *from fish* -# (https://fishshell.com/). You cannot run it directly. - -function deactivate -d "Exit virtual environment and return to normal shell environment" - # reset old environment variables - if test -n "$_OLD_VIRTUAL_PATH" - set -gx PATH $_OLD_VIRTUAL_PATH - set -e _OLD_VIRTUAL_PATH - end - if test -n "$_OLD_VIRTUAL_PYTHONHOME" - set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME - set -e _OLD_VIRTUAL_PYTHONHOME - end - - if test -n "$_OLD_FISH_PROMPT_OVERRIDE" - set -e _OLD_FISH_PROMPT_OVERRIDE - # prevents error when using nested fish instances (Issue #93858) - if functions -q _old_fish_prompt - functions -e fish_prompt - functions -c _old_fish_prompt fish_prompt - functions -e _old_fish_prompt - end - end - - set -e VIRTUAL_ENV - set -e VIRTUAL_ENV_PROMPT - if test "$argv[1]" != "nondestructive" - # Self-destruct! - functions -e deactivate - end -end - -# Unset irrelevant variables. -deactivate nondestructive - -set -gx VIRTUAL_ENV /home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia - -set -gx _OLD_VIRTUAL_PATH $PATH -set -gx PATH "$VIRTUAL_ENV/"bin $PATH - -# Unset PYTHONHOME if set. -if set -q PYTHONHOME - set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME - set -e PYTHONHOME -end - -if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" - # fish uses a function instead of an env var to generate the prompt. - - # Save the current fish_prompt function as the function _old_fish_prompt. - functions -c fish_prompt _old_fish_prompt - - # With the original prompt function renamed, we can override with our own. - function fish_prompt - # Save the return status of the last command. - set -l old_status $status - - # Output the venv prompt; color taken from the blue of the Python logo. - printf "%s%s%s" (set_color 4B8BBE) '(projeto-raia) ' (set_color normal) - - # Restore the return status of the previous command. - echo "exit $old_status" | . - # Output the original/"old" prompt. - _old_fish_prompt - end - - set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV" - set -gx VIRTUAL_ENV_PROMPT '(projeto-raia) ' -end diff --git a/projeto-raia/bin/distro b/projeto-raia/bin/distro deleted file mode 100755 index 9dda94e..0000000 --- a/projeto-raia/bin/distro +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from distro.distro import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/projeto-raia/bin/dotenv b/projeto-raia/bin/dotenv deleted file mode 100755 index 3c3640a..0000000 --- a/projeto-raia/bin/dotenv +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from dotenv.__main__ import cli -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(cli()) diff --git a/projeto-raia/bin/filetype b/projeto-raia/bin/filetype deleted file mode 100755 index 6baebd3..0000000 --- a/projeto-raia/bin/filetype +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from filetype.__main__ import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/projeto-raia/bin/httpx b/projeto-raia/bin/httpx deleted file mode 100755 index 1a4903a..0000000 --- a/projeto-raia/bin/httpx +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from httpx import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/projeto-raia/bin/jsondiff b/projeto-raia/bin/jsondiff deleted file mode 100755 index 967b5c0..0000000 --- a/projeto-raia/bin/jsondiff +++ /dev/null @@ -1,41 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- - -from __future__ import print_function - -import sys -import json -import jsonpatch -import argparse - - -parser = argparse.ArgumentParser(description='Diff two JSON files') -parser.add_argument('FILE1', type=argparse.FileType('r')) -parser.add_argument('FILE2', type=argparse.FileType('r')) -parser.add_argument('--indent', type=int, default=None, - help='Indent output by n spaces') -parser.add_argument('-u', '--preserve-unicode', action='store_true', - help='Output Unicode character as-is without using Code Point') -parser.add_argument('-v', '--version', action='version', - version='%(prog)s ' + jsonpatch.__version__) - - -def main(): - try: - diff_files() - except KeyboardInterrupt: - sys.exit(1) - - -def diff_files(): - """ Diffs two JSON files and prints a patch """ - args = parser.parse_args() - doc1 = json.load(args.FILE1) - doc2 = json.load(args.FILE2) - patch = jsonpatch.make_patch(doc1, doc2) - if patch.patch: - print(json.dumps(patch.patch, indent=args.indent, ensure_ascii=not(args.preserve_unicode))) - sys.exit(1) - -if __name__ == "__main__": - main() diff --git a/projeto-raia/bin/jsonpatch b/projeto-raia/bin/jsonpatch deleted file mode 100755 index baaf531..0000000 --- a/projeto-raia/bin/jsonpatch +++ /dev/null @@ -1,107 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- - -import sys -import os.path -import json -import jsonpatch -import tempfile -import argparse - - -parser = argparse.ArgumentParser( - description='Apply a JSON patch on a JSON file') -parser.add_argument('ORIGINAL', type=argparse.FileType('r'), - help='Original file') -parser.add_argument('PATCH', type=argparse.FileType('r'), - nargs='?', default=sys.stdin, - help='Patch file (read from stdin if omitted)') -parser.add_argument('--indent', type=int, default=None, - help='Indent output by n spaces') -parser.add_argument('-b', '--backup', action='store_true', - help='Back up ORIGINAL if modifying in-place') -parser.add_argument('-i', '--in-place', action='store_true', - help='Modify ORIGINAL in-place instead of to stdout') -parser.add_argument('-v', '--version', action='version', - version='%(prog)s ' + jsonpatch.__version__) -parser.add_argument('-u', '--preserve-unicode', action='store_true', - help='Output Unicode character as-is without using Code Point') - -def main(): - try: - patch_files() - except KeyboardInterrupt: - sys.exit(1) - - -def patch_files(): - """ Diffs two JSON files and prints a patch """ - args = parser.parse_args() - doc = json.load(args.ORIGINAL) - patch = json.load(args.PATCH) - result = jsonpatch.apply_patch(doc, patch) - - if args.in_place: - dirname = os.path.abspath(os.path.dirname(args.ORIGINAL.name)) - - try: - # Attempt to replace the file atomically. We do this by - # creating a temporary file in the same directory as the - # original file so we can atomically move the new file over - # the original later. (This is done in the same directory - # because atomic renames do not work across mount points.) - - fd, pathname = tempfile.mkstemp(dir=dirname) - fp = os.fdopen(fd, 'w') - atomic = True - - except OSError: - # We failed to create the temporary file for an atomic - # replace, so fall back to non-atomic mode by backing up - # the original (if desired) and writing a new file. - - if args.backup: - os.rename(args.ORIGINAL.name, args.ORIGINAL.name + '.orig') - fp = open(args.ORIGINAL.name, 'w') - atomic = False - - else: - # Since we're not replacing the original file in-place, write - # the modified JSON to stdout instead. - - fp = sys.stdout - - # By this point we have some sort of file object we can write the - # modified JSON to. - - json.dump(result, fp, indent=args.indent, ensure_ascii=not(args.preserve_unicode)) - fp.write('\n') - - if args.in_place: - # Close the new file. If we aren't replacing atomically, this - # is our last step, since everything else is already in place. - - fp.close() - - if atomic: - try: - # Complete the atomic replace by linking the original - # to a backup (if desired), fixing up the permissions - # on the temporary file, and moving it into place. - - if args.backup: - os.link(args.ORIGINAL.name, args.ORIGINAL.name + '.orig') - os.chmod(pathname, os.stat(args.ORIGINAL.name).st_mode) - os.rename(pathname, args.ORIGINAL.name) - - except OSError: - # In the event we could not actually do the atomic - # replace, unlink the original to move it out of the - # way and finally move the temporary file into place. - - os.unlink(args.ORIGINAL.name) - os.rename(pathname, args.ORIGINAL.name) - - -if __name__ == "__main__": - main() diff --git a/projeto-raia/bin/jsonpointer b/projeto-raia/bin/jsonpointer deleted file mode 100755 index a8a7614..0000000 --- a/projeto-raia/bin/jsonpointer +++ /dev/null @@ -1,66 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 - - -import argparse -import json -import sys - -import jsonpointer - -parser = argparse.ArgumentParser( - description='Resolve a JSON pointer on JSON files') - -# Accept pointer as argument or as file -ptr_group = parser.add_mutually_exclusive_group(required=True) - -ptr_group.add_argument('-f', '--pointer-file', type=argparse.FileType('r'), - nargs='?', - help='File containing a JSON pointer expression') - -ptr_group.add_argument('POINTER', type=str, nargs='?', - help='A JSON pointer expression') - -parser.add_argument('FILE', type=argparse.FileType('r'), nargs='+', - help='Files for which the pointer should be resolved') -parser.add_argument('--indent', type=int, default=None, - help='Indent output by n spaces') -parser.add_argument('-v', '--version', action='version', - version='%(prog)s ' + jsonpointer.__version__) - - -def main(): - try: - resolve_files() - except KeyboardInterrupt: - sys.exit(1) - - -def parse_pointer(args): - if args.POINTER: - ptr = args.POINTER - elif args.pointer_file: - ptr = args.pointer_file.read().strip() - else: - parser.print_usage() - sys.exit(1) - - return ptr - - -def resolve_files(): - """ Resolve a JSON pointer on JSON files """ - args = parser.parse_args() - - ptr = parse_pointer(args) - - for f in args.FILE: - doc = json.load(f) - try: - result = jsonpointer.resolve_pointer(doc, ptr) - print(json.dumps(result, indent=args.indent)) - except jsonpointer.JsonPointerException as e: - print('Could not resolve pointer: %s' % str(e), file=sys.stderr) - - -if __name__ == "__main__": - main() diff --git a/projeto-raia/bin/normalizer b/projeto-raia/bin/normalizer deleted file mode 100755 index e8e795d..0000000 --- a/projeto-raia/bin/normalizer +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from charset_normalizer.cli import cli_detect -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(cli_detect()) diff --git a/projeto-raia/bin/pip b/projeto-raia/bin/pip deleted file mode 100755 index 80760a2..0000000 --- a/projeto-raia/bin/pip +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from pip._internal.cli.main import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/projeto-raia/bin/pip3 b/projeto-raia/bin/pip3 deleted file mode 100755 index 80760a2..0000000 --- a/projeto-raia/bin/pip3 +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from pip._internal.cli.main import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/projeto-raia/bin/pip3.12 b/projeto-raia/bin/pip3.12 deleted file mode 100755 index 80760a2..0000000 --- a/projeto-raia/bin/pip3.12 +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from pip._internal.cli.main import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/projeto-raia/bin/py.test b/projeto-raia/bin/py.test deleted file mode 100755 index 9943710..0000000 --- a/projeto-raia/bin/py.test +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from pytest import console_main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(console_main()) diff --git a/projeto-raia/bin/pygmentize b/projeto-raia/bin/pygmentize deleted file mode 100755 index 559002d..0000000 --- a/projeto-raia/bin/pygmentize +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from pygments.cmdline import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/projeto-raia/bin/pytest b/projeto-raia/bin/pytest deleted file mode 100755 index 9943710..0000000 --- a/projeto-raia/bin/pytest +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from pytest import console_main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(console_main()) diff --git a/projeto-raia/bin/python b/projeto-raia/bin/python deleted file mode 120000 index b8a0adb..0000000 --- a/projeto-raia/bin/python +++ /dev/null @@ -1 +0,0 @@ -python3 \ No newline at end of file diff --git a/projeto-raia/bin/python3 b/projeto-raia/bin/python3 deleted file mode 120000 index ae65fda..0000000 --- a/projeto-raia/bin/python3 +++ /dev/null @@ -1 +0,0 @@ -/usr/bin/python3 \ No newline at end of file diff --git a/projeto-raia/bin/python3.12 b/projeto-raia/bin/python3.12 deleted file mode 120000 index b8a0adb..0000000 --- a/projeto-raia/bin/python3.12 +++ /dev/null @@ -1 +0,0 @@ -python3 \ No newline at end of file diff --git a/projeto-raia/bin/websockets b/projeto-raia/bin/websockets deleted file mode 100755 index e9a8e4a..0000000 --- a/projeto-raia/bin/websockets +++ /dev/null @@ -1,8 +0,0 @@ -#!/home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia/bin/python3 -# -*- coding: utf-8 -*- -import re -import sys -from websockets.cli import main -if __name__ == '__main__': - sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0]) - sys.exit(main()) diff --git a/projeto-raia/lib64 b/projeto-raia/lib64 deleted file mode 120000 index 7951405..0000000 --- a/projeto-raia/lib64 +++ /dev/null @@ -1 +0,0 @@ -lib \ No newline at end of file diff --git a/projeto-raia/pyvenv.cfg b/projeto-raia/pyvenv.cfg deleted file mode 100644 index ff5363e..0000000 --- a/projeto-raia/pyvenv.cfg +++ /dev/null @@ -1,5 +0,0 @@ -home = /usr/bin -include-system-site-packages = false -version = 3.12.3 -executable = /usr/bin/python3.12 -command = /usr/bin/python3 -m venv /home/jonasmelo/ProjectsAndStudies/TextToInsight/projeto-raia diff --git a/pyproject.toml b/pyproject.toml index 80cfae1..1555fe2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,15 +43,18 @@ dependencies = [ "networkx>=3.0", "chromadb>=1.5.9", "tabulate>=0.10.0", - "psycopg2-binary>=2.9.0", - "pymysql>=1.1.0", "sqlalchemy>=2.0.0", + "platformdirs>=3.0", ] [project.scripts] text-to-insight = "text_to_insight.cli:main" [project.optional-dependencies] +# Drivers de banco: a biblioteca recebe uma Engine do SQLAlchemy pronta, então +# só precisa do driver de quem for usar PostgreSQL/MySQL (SQLite já vem no Python). +postgres = ["psycopg2-binary>=2.9.0"] +mysql = ["pymysql>=1.1.0"] dev = [ "pytest>=7.0", "pytest-cov>=4.0", @@ -96,5 +99,4 @@ disallow_untyped_defs = false [tool.pytest.ini_options] markers = [ "real_api: testes que executam chamadas reais ao provedor/modelo LLM", - "schemacrawler: Marca os testes que dependem do SchemaCrawler e do Java." ] diff --git a/scripts/test_bird_eval.py b/scripts/test_bird_eval.py index 4bd36b0..79cd1bb 100755 --- a/scripts/test_bird_eval.py +++ b/scripts/test_bird_eval.py @@ -254,12 +254,6 @@ def parse_arguments() -> argparse.Namespace: default="off", help="Column exploration selector mode: off, llm, rag (default: off, accepts legacy 'heuristic')", ) - parser.add_argument( - "--schemacrawler", - choices=["on", "off"], - default="off", - help="Enable SchemaCrawler for schema introspection (default: off)", - ) parser.add_argument( "--timeout", type=int, @@ -503,6 +497,8 @@ def main() -> None: # 5. Engine cache by db_id engine_cache: dict[str, Any] = {} + # One read-only SQLAlchemy Engine per database; the script owns it and disposes it at the end. + db_engines: dict[str, Any] = {} # LLM constructor kwargs (empty -> provider defaults apply) model_kwargs: dict[str, Any] = dict(args.model_kwargs) @@ -530,7 +526,6 @@ def main() -> None: print(f" - Chain of Thought: {args.cot}") print(f" - Data Exploration: {args.data_exploration}") print(f" - Exploration Selector: {args.exploration_selector}") - print(f" - SchemaCrawler: {args.schemacrawler}") print(f" - Infer FKs: {'on' if infer_fks_enabled else 'off'}") print(f" - With Graphs: {'on' if with_graphs_enabled else 'off'}") print(f" - Logging: {args.log}") @@ -553,7 +548,6 @@ def main() -> None: "use_cot": (args.cot == "on"), "use_data_exploration": (args.data_exploration == "on"), "exploration_selector": args.exploration_selector, - "schemacrawler": (args.schemacrawler == "on"), "infer_fks": infer_fks_enabled, "with_graphs": with_graphs_enabled, "db_filter": args.db_filter, @@ -604,6 +598,8 @@ def main() -> None: agent_time_ms = (time.perf_counter() - agent_start) * 1000 else: # Import InsightEngine lazily only when executing live runs + from sqlalchemy import create_engine + from text_to_insight import InsightEngine # Resolve db path @@ -615,10 +611,13 @@ def main() -> None: # Cache InsightEngine per database ID if db_id not in engine_cache: try: + db_engines[db_id] = create_engine( + f"sqlite:///file:{db_path_obj.resolve()}?mode=ro&uri=true" + ) engine_cache[db_id] = InsightEngine( api_key=api_key, model=args.model, - db_path=str(db_path_obj), + db_engine=db_engines[db_id], hitl=False, show_output=False, enable_graphs=with_graphs_enabled, @@ -628,7 +627,6 @@ def main() -> None: use_rag=(args.rag == "on"), enrich_rag=(args.enrich_rag == "on"), inferir_fks_virtuais=infer_fks_enabled, - usar_schemacrawler=(args.schemacrawler == "on"), model_kwargs=model_kwargs, ) except Exception as e: @@ -841,6 +839,9 @@ def main() -> None: print(f" ⚠️ Error: {agent_exec_error[:80]}") + for db_engine in db_engines.values(): + db_engine.dispose() + total_elapsed = time.perf_counter() - start_total_time # 7. Summary & Reporting @@ -874,7 +875,6 @@ def main() -> None: "use_cot": (args.cot == "on"), "use_data_exploration": (args.data_exploration == "on"), "exploration_selector": args.exploration_selector, - "schemacrawler": (args.schemacrawler == "on"), "infer_fks": infer_fks_enabled, "with_graphs": with_graphs_enabled, "use_evidence": (args.use_evidence == "on"), diff --git a/scripts/test_spider2_eval.py b/scripts/test_spider2_eval.py index 37c7cb6..e6db4ff 100755 --- a/scripts/test_spider2_eval.py +++ b/scripts/test_spider2_eval.py @@ -200,19 +200,6 @@ def parse_arguments() -> argparse.Namespace: default="off", help="Column selection mode for exploration: off, llm, rag (default: off)", ) - parser.add_argument( - "--schemacrawler", - choices=["on", "off"], - nargs="?", - const="on", - default="off", - help="Enable SchemaCrawler introspection (default: off)", - ) - parser.add_argument( - "--no-schemacrawler", - action="store_true", - help="Deprecated alias to disable SchemaCrawler", - ) parser.add_argument( "--infer-fks", choices=["on", "off"], @@ -554,7 +541,6 @@ def generate_markdown_report( lines.append(f"| CoT | {'ON' if config_info.get('use_cot') else 'OFF'} |") lines.append(f"| DataExploration | {'ON' if config_info.get('use_data_exploration') else 'OFF'} |") lines.append(f"| ExplorationSelector | `{config_info.get('exploration_selector')}` |") - lines.append(f"| SchemaCrawler | {'ON' if config_info.get('schemacrawler') else 'OFF'} |") lines.append(f"| InferFKs | {'ON' if config_info.get('infer_fks') else 'OFF'} |") lines.append(f"| WithGraphs | {'ON' if config_info.get('with_graphs') else 'OFF'} |") lines.append(f"| UseEvidence | {'ON' if config_info.get('use_evidence') else 'OFF'} |") @@ -757,8 +743,6 @@ def main() -> None: if args.max_tokens is not None: model_kwargs["max_tokens"] = args.max_tokens - # SchemaCrawler resolution - use_schemacrawler = (args.schemacrawler == "on") and (not args.no_schemacrawler) infer_fks = (args.infer_fks == "on") with_graphs = (args.with_graphs == "on") use_cot = (args.cot == "on") @@ -838,7 +822,6 @@ def main() -> None: "use_cot": use_cot, "use_data_exploration": use_data_exploration, "exploration_selector": args.exploration_selector, - "schemacrawler": use_schemacrawler, "infer_fks": infer_fks, "with_graphs": with_graphs, "use_evidence": use_evidence, @@ -908,7 +891,6 @@ def main() -> None: engine_cache[db_id] = InsightEngine( api_key=api_key, model=concrete_model, - db_path=db_path, db_engine=db_engine, hitl=False, show_output=False, @@ -919,7 +901,6 @@ def main() -> None: use_rag=use_rag, enrich_rag=enrich_rag, inferir_fks_virtuais=infer_fks, - usar_schemacrawler=use_schemacrawler, model_kwargs=model_kwargs, ) engine = engine_cache[db_id] diff --git a/scripts/test_spider_eval.py b/scripts/test_spider_eval.py index f8fb4ff..81933ba 100644 --- a/scripts/test_spider_eval.py +++ b/scripts/test_spider_eval.py @@ -495,7 +495,6 @@ def main(): engine_cache[db_id] = InsightEngine( api_key=api_key, model=model, - db_path=db_path, db_engine=db_engines[db_id], hitl=False, show_output=False, diff --git a/src/bird/logger.py b/src/bird/logger.py index 933b712..8a47110 100644 --- a/src/bird/logger.py +++ b/src/bird/logger.py @@ -127,7 +127,6 @@ def log_run_header(self, config_info: dict[str, Any]) -> None: use_cot = "ON" if config_info.get("use_cot") else "OFF" use_exploration = "ON" if config_info.get("use_data_exploration") else "OFF" exploration_selector = config_info.get("exploration_selector") or "off" - schemacrawler = "ON" if config_info.get("schemacrawler") else "OFF" infer_fks = "ON" if config_info.get("infer_fks") else "OFF" with_graphs_str = f" | WithGraphs: {'ON' if config_info.get('with_graphs') else 'OFF'}" if "with_graphs" in config_info else "" raw_kwargs = config_info.get("model_kwargs") or {} @@ -152,7 +151,7 @@ def log_run_header(self, config_info: dict[str, Any]) -> None: f"Seed: {seed}", f"Configuration: RAG: {use_rag} | EnrichRAG: {enrich_rag} | Evidence: {use_evidence} | CoT: {use_cot} | " f"DataExploration: {use_exploration} (Selector: {exploration_selector}) | " - f"SchemaCrawler: {schemacrawler} | InferFKs: {infer_fks}{with_graphs_str}{kwargs_str}", + f"InferFKs: {infer_fks}{with_graphs_str}{kwargs_str}", filter_line, f"Output Directory: {self.output_dir}", f"Log File: {self.log_path.name}", diff --git a/src/spider/logger.py b/src/spider/logger.py index 04c95e9..092956a 100644 --- a/src/spider/logger.py +++ b/src/spider/logger.py @@ -146,7 +146,6 @@ def log_run_header(self, config_info: dict[str, Any]) -> None: use_cot = "ON" if config_info.get("use_cot", True) else "OFF" use_exploration = "ON" if config_info.get("use_data_exploration", True) else "OFF" exploration_selector = config_info.get("exploration_selector") or "off" - schemacrawler = "ON" if config_info.get("schemacrawler", False) else "OFF" infer_fks = "ON" if config_info.get("infer_fks", False) else "OFF" with_graphs = "ON" if config_info.get("with_graphs", False) else "OFF" timeout = config_info.get("timeout", 30) @@ -171,7 +170,7 @@ def log_run_header(self, config_info: dict[str, Any]) -> None: f"Seed: {seed}", f"Configuration: RAG: {use_rag} | EnrichRAG: {enrich_rag} | Evidence: {use_evidence} | CoT: {use_cot} | " f"DataExploration: {use_exploration} (Selector: {exploration_selector}) | " - f"SchemaCrawler: {schemacrawler} | InferFKs: {infer_fks} | WithGraphs: {with_graphs} | Timeout: {timeout}s{kwargs_str}", + f"InferFKs: {infer_fks} | WithGraphs: {with_graphs} | Timeout: {timeout}s{kwargs_str}", f"Filters: DB: {db_filter} | Question: {question_filter}", f"Output Directory: {self.output_dir}", f"Log File: {self.log_path.name}", diff --git a/tests/conftest.py b/tests/conftest.py index 45df2ab..0c0ac0b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -221,4 +221,72 @@ def default_cassette_name(request, llm_profile): else: base_name = _default_cassette_name(request.cls, request.node.name) - return f"{base_name}{llm_profile.cassette_suffix}" \ No newline at end of file + return f"{base_name}{llm_profile.cassette_suffix}" + +# ============================================================ +# Banco de teste e cache +# ============================================================ + +DB_OLIST = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "olist_relational.db") + + +def criar_engine_sqlite(caminho: str): + """Engine SQLAlchemy somente leitura para um arquivo SQLite (como os scripts de avaliação).""" + from pathlib import Path + from sqlalchemy import create_engine + + return create_engine(f"sqlite:///file:{Path(caminho).resolve()}?mode=ro&uri=true") + + +@pytest.fixture(scope="session") +def olist_engine(): + """Engine somente leitura do banco olist (baixado da release `dados-teste`).""" + engine = criar_engine_sqlite(DB_OLIST) + yield engine + engine.dispose() + + +@pytest.fixture(scope="session") +def _cache_dir_testes(tmp_path_factory): + return tmp_path_factory.mktemp("text_to_insight_cache") + + +@pytest.fixture(autouse=True) +def cache_dir_isolado(monkeypatch, _cache_dir_testes): + """Nenhum teste grava na pasta de cache real do usuário (schema enriquecido, ChromaDB).""" + import text_to_insight.cache as cache_mod + + monkeypatch.setattr(cache_mod, "user_cache_dir", lambda *_a, **_k: str(_cache_dir_testes)) + return _cache_dir_testes + + +# ============================================================ +# PostgreSQL (opcional): definido via TEXT_TO_INSIGHT_TEST_PG_URL +# ============================================================ + +PG_URL_ENV = "TEXT_TO_INSIGHT_TEST_PG_URL" +PG_SCHEMA_TESTES = "tti_testes" + + +@pytest.fixture +def pg_engine(): + """ + Engine de um PostgreSQL real, com search_path num schema próprio e vazio. + Pula o teste se TEXT_TO_INSIGHT_TEST_PG_URL não estiver definida + (ex.: postgresql+psycopg2://postgres:postgres@localhost:5432/postgres). + """ + url = os.getenv(PG_URL_ENV) + if not url: + pytest.skip(f"{PG_URL_ENV} não definida; testes de PostgreSQL pulados.") + from sqlalchemy import create_engine, text + + admin = create_engine(url) + with admin.begin() as conn: + conn.execute(text(f"DROP SCHEMA IF EXISTS {PG_SCHEMA_TESTES} CASCADE")) + conn.execute(text(f"CREATE SCHEMA {PG_SCHEMA_TESTES}")) + engine = create_engine(url, connect_args={"options": f"-c search_path={PG_SCHEMA_TESTES}"}) + yield engine + engine.dispose() + with admin.begin() as conn: + conn.execute(text(f"DROP SCHEMA IF EXISTS {PG_SCHEMA_TESTES} CASCADE")) + admin.dispose() diff --git a/tests/run_data_exploration_test.py b/tests/run_data_exploration_test.py deleted file mode 100644 index 21e8509..0000000 --- a/tests/run_data_exploration_test.py +++ /dev/null @@ -1,146 +0,0 @@ -#!/usr/bin/env python3 -"""Quick smoke test for data_exploration module.""" -import sqlite3 -import sys -import tempfile -from pathlib import Path - -# Ensure the project root is on the path -sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) - -from text_to_insight.nodes.data_exploration import ( - _classify_column_type, - explore_table, - explore_tables, - format_exploration_for_prompt, - nos_nodo_data_exploration, - NumericColumnStats, - CategoricalColumnStats, - DateColumnStats, - BooleanColumnStats, -) - -def create_test_db(): - db_path = Path(tempfile.mkdtemp()) / "test.db" - conn = sqlite3.connect(str(db_path)) - cur = conn.cursor() - cur.execute(""" - CREATE TABLE products ( - id INTEGER PRIMARY KEY, - name TEXT NOT NULL, - price REAL, - category TEXT, - is_active BOOLEAN, - created_at DATETIME, - stock_count INTEGER - ) - """) - products = [ - (1, "Widget A", 19.99, "Electronics", 1, "2024-01-15 10:30:00", 150), - (2, "Widget B", 29.99, "Electronics", 1, "2024-02-20 14:00:00", 80), - (3, "Gadget C", 49.99, "Home", 0, "2024-03-10 09:15:00", 0), - (4, "Gadget D", 9.99, "Home", 1, "2024-04-05 16:45:00", 200), - (5, "Tool E", 99.99, "Industrial", 1, "2024-05-01 11:00:00", 50), - (6, "Tool F", None, "Industrial", None, None, None), - ] - cur.executemany("INSERT INTO products VALUES (?, ?, ?, ?, ?, ?, ?)", products) - conn.commit() - conn.close() - return str(db_path) - -def main(): - passed = 0 - failed = 0 - - # Test 1: Type classification - print("Test 1: Type classification...") - assert _classify_column_type("INTEGER") == "numeric" - assert _classify_column_type("TEXT") == "categorical" - assert _classify_column_type("DATETIME") == "date" - assert _classify_column_type("BOOLEAN") == "boolean" - assert _classify_column_type("") == "categorical" - print(" PASSED") - passed += 1 - - # Test 2: Explore single table - print("Test 2: Explore single table...") - db_path = create_test_db() - conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) - result = explore_table(conn, "products") - assert result.table_name == "products" - assert result.row_count_estimate == 6 - assert len(result.columns) == 7 - assert isinstance(result.columns["price"], NumericColumnStats) - assert isinstance(result.columns["category"], CategoricalColumnStats) - assert isinstance(result.columns["is_active"], BooleanColumnStats) - assert isinstance(result.columns["created_at"], DateColumnStats) - conn.close() - print(" PASSED") - passed += 1 - - # Test 3: Numeric stats - print("Test 3: Numeric column stats...") - conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) - result = explore_table(conn, "products") - price = result.columns["price"] - assert price.min is not None - assert price.max is not None - assert price.mean is not None - assert price.null_rate > 0 # 1 NULL out of 6 - conn.close() - print(" PASSED") - passed += 1 - - # Test 4: Multi-table exploration - print("Test 4: Multi-table exploration...") - results = explore_tables(db_path, ["products"]) - assert "products" in results - print(" PASSED") - passed += 1 - - # Test 5: Format for prompt - print("Test 5: Format for prompt...") - results = explore_tables(db_path, ["products"]) - text = format_exploration_for_prompt(results) - assert "Tabela: products" in text - assert "DATA EXPLORATION" in text - assert "price [numeric]" in text - assert "category [categorical]" in text - print(" PASSED") - passed += 1 - - # Test 6: Graph node - print("Test 6: Graph node integration...") - estado = { - "db_path": db_path, - "contexto_rag_schema": "Tabela: products\n- id: INTEGER\n", - } - result = nos_nodo_data_exploration(estado) - assert "contexto_data_exploration" in result - assert "products" in result["contexto_data_exploration"] - print(" PASSED") - passed += 1 - - # Test 7: Empty context returns empty - print("Test 7: Missing context returns empty...") - result = nos_nodo_data_exploration({"db_path": db_path, "contexto_rag_schema": ""}) - assert result == {} - print(" PASSED") - passed += 1 - - # Test 8: Format compactness - print("Test 8: Output compactness...") - results = explore_tables(db_path, ["products"]) - text = format_exploration_for_prompt(results) - assert len(text) < 5000, f"Output too large: {len(text)} chars" - print(" PASSED") - passed += 1 - - print(f"\n{'='*40}") - print(f"Results: {passed} passed, {failed} failed") - if failed: - sys.exit(1) - print("All tests passed!") - -if __name__ == "__main__": - main() diff --git a/tests/test_biblioteca_integracao.py b/tests/test_biblioteca_integracao.py index a68a033..d8ece2b 100644 --- a/tests/test_biblioteca_integracao.py +++ b/tests/test_biblioteca_integracao.py @@ -117,11 +117,17 @@ def patched_runtime(monkeypatch): monkeypatch.setenv("GOOGLE_API_KEY", "fake-key") +def _engine_em_memoria(): + from sqlalchemy import create_engine + + return create_engine("sqlite://") + + def _fabricar_engine(hitl: bool = False) -> InsightEngine: return InsightEngine( api_key="fake-key", model="gemini-2.5-flash", - db_path="data/olist_relational.db", + db_engine=_engine_em_memoria(), hitl=hitl, show_output=False, ) @@ -147,14 +153,41 @@ def test_simbolos_publicos_expostos_no_topo_do_pacote(): def test_engine_constroi_com_defaults_documentados(patched_runtime): """O construtor aceita só os campos obrigatórios e aplica defaults sensatos.""" + db_engine = _engine_em_memoria() engine = InsightEngine( api_key="fake-key", model="gemini-2.5-flash", - db_path="data/olist_relational.db", + db_engine=db_engine, ) assert engine._hitl_ativado is False assert engine._show_output is False - assert engine._db_path == "data/olist_relational.db" + assert engine._db_engine is db_engine + assert engine._cache_dir is None + + +@pytest.mark.parametrize("db_engine", [None, "data/olist_relational.db"]) +def test_engine_exige_engine_sqlalchemy(patched_runtime, db_engine): + """A biblioteca não abre conexões: sem uma Engine do SQLAlchemy, o construtor falha cedo.""" + with pytest.raises(TypeError, match="db_engine"): + InsightEngine(api_key="fake-key", model="gemini-2.5-flash", db_engine=db_engine) + + +def test_engine_repassa_cache_dir_para_o_grafo(monkeypatch, tmp_path): + """`cache_dir` chega ao Graph, que o repassa aos nós com cache em disco.""" + insight_engine_module = importlib.import_module("text_to_insight.InsightEngine") + capturado = {} + + class _GraphEspiao(_FakeGraph): + def __init__(self, *args, **kwargs): + capturado.update(kwargs) + super().__init__(*args, **kwargs) + + monkeypatch.setattr(insight_engine_module, "Graph", _GraphEspiao) + db_engine = _engine_em_memoria() + InsightEngine(api_key="k", model="gemini-2.5-flash", db_engine=db_engine, cache_dir=tmp_path) + + assert capturado["db_engine"] is db_engine + assert capturado["cache_dir"] == tmp_path # --------------------------------------------------------------------------- # diff --git a/tests/test_bird_eval.py b/tests/test_bird_eval.py index 465836d..5af2754 100644 --- a/tests/test_bird_eval.py +++ b/tests/test_bird_eval.py @@ -652,7 +652,6 @@ def test_bird_execution_logger_lifecycle_and_formatting(tmp_path: Path) -> None: "use_cot": True, "use_data_exploration": False, "exploration_selector": "off", - "schemacrawler": False, "infer_fks": False, "db_filter": "school", "difficulty_filter": "simple", @@ -756,7 +755,7 @@ def test_bird_execution_logger_lifecycle_and_formatting(tmp_path: Path) -> None: assert "TEXTTOINSIGHT - BIRD BENCHMARK EXECUTION LOG" in content assert "Timestamp: 2026-10-14_17-45-00" in content assert "Model: gpt-5-turbo" in content - assert "RAG: ON | EnrichRAG: OFF | Evidence: ON | CoT: ON | DataExploration: OFF (Selector: off) | SchemaCrawler: OFF | InferFKs: OFF" in content + assert "RAG: ON | EnrichRAG: OFF | Evidence: ON | CoT: ON | DataExploration: OFF (Selector: off) | InferFKs: OFF" in content assert "Filters: DB: school | Difficulty: simple" in content # QID 1 assertions @@ -983,8 +982,8 @@ def test_cli_orchestrator_model_kwargs_flag(mock_bird_env: Path, tmp_path: Path, assert '| **Model kwargs** | `{"temperature": 0.3}` |' in out_csv.with_suffix(".md").read_text(encoding="utf-8") -def test_cli_orchestrator_schemacrawler_and_selector_flags(mock_bird_env: Path, tmp_path: Path) -> None: - """Verifies that --schemacrawler and --exploration-selector flags parse and log correctly.""" +def test_cli_orchestrator_selector_and_enrich_flags(mock_bird_env: Path, tmp_path: Path) -> None: + """Verifies that --exploration-selector and --enrich-rag flags parse and log correctly.""" out_csv = tmp_path / "sc_selector_report.csv" cmd = [ sys.executable, @@ -992,20 +991,18 @@ def test_cli_orchestrator_schemacrawler_and_selector_flags(mock_bird_env: Path, "--data-dir", str(mock_bird_env), "--sample-size", "1", "--dry-run", - "--schemacrawler", "on", "--exploration-selector", "heuristic", "--enrich-rag", "on", "--output", str(out_csv), ] result = subprocess.run(cmd, capture_output=True, text=True) assert result.returncode == 0, f"CLI command failed:\n{result.stderr}" - assert "SchemaCrawler: on" in result.stdout # 'heuristic' is cleanly mapped to 'rag' for full parity assert "Exploration Selector: rag" in result.stdout assert "Enrich RAG: on" in result.stdout log_content = out_csv.with_suffix(".log").read_text(encoding="utf-8") - assert "SchemaCrawler: ON" in log_content + assert "SchemaCrawler" not in log_content assert "Selector: rag" in log_content assert "EnrichRAG: ON" in log_content diff --git a/tests/test_componentes.py b/tests/test_componentes.py index 1c4850e..73a3dc6 100644 --- a/tests/test_componentes.py +++ b/tests/test_componentes.py @@ -22,29 +22,50 @@ # Schema Node # ============================================================ -def test_schema_extrai_tabelas(): +def test_schema_extrai_tabelas(olist_engine): """Schema node retorna contexto com tabelas do olist DB.""" from text_to_insight.nodes.schema import nos_nodo_esquema - estado = {"db_path": DB_PATH, "pergunta_atual": "teste"} - resultado = nos_nodo_esquema(estado) + resultado = nos_nodo_esquema({"pergunta_atual": "teste"}, engine=olist_engine) assert resultado["status"] == "schema_obtido" + assert resultado["tem_descricao"] is False assert "Tabela:" in resultado["contexto_schema"] assert len(resultado["contexto_schema"]) > 100 -def test_schema_erro_db_invalido(): - """Schema node retorna erro quando db_path não existe.""" +def test_schema_erro_engine_sem_banco(tmp_path): + """Schema node retorna exec_erro quando a engine não consegue abrir o banco.""" + from tests.conftest import criar_engine_sqlite from text_to_insight.nodes.schema import nos_nodo_esquema - estado = {"db_path": "/caminho/inexistente.db", "pergunta_atual": "teste"} - resultado = nos_nodo_esquema(estado) + engine = criar_engine_sqlite(str(tmp_path / "inexistente.db")) + try: + resultado = nos_nodo_esquema({"pergunta_atual": "teste"}, engine=engine) + finally: + engine.dispose() assert resultado["status"] == "exec_erro" assert resultado["contexto_schema"] == "" +def test_schema_usa_cache_enriquecido_so_com_enrich_rag(olist_engine, tmp_path): + """O schema enriquecido em cache só é usado quando enrich_rag está ligado.""" + from text_to_insight.cache import salvar_schema_enriquecido + from text_to_insight.nodes.schema import nos_nodo_esquema + + bruto = nos_nodo_esquema({}, engine=olist_engine, cache_dir=tmp_path)["contexto_schema"] + salvar_schema_enriquecido(tmp_path, bruto, "SCHEMA ENRIQUECIDO") + + sem_enrich = nos_nodo_esquema({}, engine=olist_engine, enrich_rag=False, cache_dir=tmp_path) + com_enrich = nos_nodo_esquema({}, engine=olist_engine, enrich_rag=True, cache_dir=tmp_path) + + assert sem_enrich["contexto_schema"] == bruto + assert sem_enrich["tem_descricao"] is False + assert com_enrich["contexto_schema"] == "SCHEMA ENRIQUECIDO" + assert com_enrich["tem_descricao"] is True + + # ============================================================ # SQL Validation (code_sql.py) # ============================================================ @@ -160,135 +181,133 @@ def test_sql_legitima_continua_permitida(sql): # SQL Execution (code_sql.py) # ============================================================ -def test_execucao_sql_valida(): +def test_execucao_sql_valida(olist_engine): """Executa SELECT real no olist DB e retorna resultados.""" - from text_to_insight.nodes.code_agent.code_sql import executar_sql_sqlite + from text_to_insight.nodes.code_agent.code_sql import executar_sql_via_engine - resultado = executar_sql_sqlite(DB_PATH, "SELECT COUNT(*) as total FROM orders") + resultado = executar_sql_via_engine(olist_engine, "SELECT COUNT(*) as total FROM orders") assert resultado["ok"] is True assert resultado["total_linhas_resultado"] == 1 assert resultado["linhas_resultado_preview"][0]["total"] > 0 -def test_execucao_sql_com_limite(): +def test_execucao_sql_com_limite(olist_engine): """Respeita limite_preview.""" - from text_to_insight.nodes.code_agent.code_sql import executar_sql_sqlite + from text_to_insight.nodes.code_agent.code_sql import executar_sql_via_engine - resultado = executar_sql_sqlite(DB_PATH, "SELECT * FROM orders", limite_preview=5) + resultado = executar_sql_via_engine(olist_engine, "SELECT * FROM orders", limite_preview=5) assert resultado["ok"] is True assert len(resultado["linhas_resultado_preview"]) <= 5 -def test_execucao_sql_invalida(): +def test_execucao_sql_invalida(olist_engine): """Retorna erro para SQL com sintaxe inválida.""" - from text_to_insight.nodes.code_agent.code_sql import executar_sql_sqlite + from text_to_insight.nodes.code_agent.code_sql import executar_sql_via_engine - resultado = executar_sql_sqlite(DB_PATH, "SELECT FROM") + resultado = executar_sql_via_engine(olist_engine, "SELECT FROM") assert resultado["ok"] is False assert resultado["erro_execucao"] != "" -def test_execucao_db_inexistente(): - """Retorna erro para DB inexistente.""" - from text_to_insight.nodes.code_agent.code_sql import executar_sql_sqlite +def test_execucao_sqlite_somente_leitura(olist_engine): + """A engine dos testes abre o SQLite em mode=ro: mesmo sem a validação, nada é escrito.""" + from sqlalchemy import text + from sqlalchemy.exc import OperationalError - resultado = executar_sql_sqlite("/nao/existe.db", "SELECT 1") - assert resultado["ok"] is False + with pytest.raises(OperationalError): + with olist_engine.connect() as conn: + conn.execute(text("CREATE TABLE x (a INT)")) # ============================================================ -# Executor Node (sandbox.py refatorado) +# Executor Node (sandbox.py) # ============================================================ -def test_executor_sucesso(): +def test_executor_sucesso(olist_engine): """Executor executa SQL do estado e retorna resultado.""" from text_to_insight.nodes.sandbox import nos_nodo_sandbox - estado = { - "sql_gerada": "SELECT COUNT(*) as total FROM orders", - "db_path": DB_PATH, - "pergunta_atual": "teste", - } - resultado = nos_nodo_sandbox(estado) + estado = {"sql_gerada": "SELECT COUNT(*) as total FROM orders", "pergunta_atual": "teste"} + resultado = nos_nodo_sandbox(estado, engine=olist_engine) assert resultado["status"] == "exec_ok" assert resultado["total_linhas_resultado"] == 1 assert len(resultado["linhas_resultado_preview"]) > 0 -def test_executor_sql_vazia(): +def test_executor_sql_vazia(olist_engine): """Executor retorna erro quando sql_gerada está vazia.""" from text_to_insight.nodes.sandbox import nos_nodo_sandbox - estado = { - "sql_gerada": "", - "db_path": DB_PATH, - "pergunta_atual": "teste", - } - resultado = nos_nodo_sandbox(estado) + resultado = nos_nodo_sandbox({"sql_gerada": "", "pergunta_atual": "teste"}, engine=olist_engine) assert resultado["status"] == "exec_erro" -def test_executor_sql_com_erro(): +def test_executor_sql_com_erro(olist_engine): """Executor retorna exec_erro para SQL com problema.""" from text_to_insight.nodes.sandbox import nos_nodo_sandbox - estado = { - "sql_gerada": "SELECT * FROM tabela_que_nao_existe", - "db_path": DB_PATH, - "pergunta_atual": "teste", - } - resultado = nos_nodo_sandbox(estado) + estado = {"sql_gerada": "SELECT * FROM tabela_que_nao_existe", "pergunta_atual": "teste"} + resultado = nos_nodo_sandbox(estado, engine=olist_engine) assert resultado["status"] == "exec_erro" assert resultado["erro_execucao"] != "" # ============================================================ -# Conexão "caller-owned" via Engine SQLAlchemy +# Execução via Engine SQLAlchemy # -# Estes testes cobrem o caminho em que o chamador constrói e possui a -# Engine (em vez de db_path/db_url no estado do grafo). Usamos uma -# Engine SQLite apontando pro mesmo fixture DB só para não depender de -# um Postgres/MySQL real nos testes — o código exercitado +# Usamos uma Engine SQLite apontando pro banco de teste só para não +# depender de um Postgres/MySQL real — o código exercitado # (executar_sql_via_engine, _formatar_schema_sqlalchemy, # _resolver_info_dialeto) é o mesmo independente do dialeto. # ============================================================ def _engine_sqlite_fixture(): + """Engine própria (não a da sessão) para testes que mexem no pool.""" from sqlalchemy import create_engine return create_engine(f"sqlite:///{DB_PATH}") -def test_schema_via_engine(): - """Nó de schema usa a Engine injetada em vez de db_path/db_url do estado.""" - from text_to_insight.nodes.schema import nos_nodo_esquema +@pytest.mark.parametrize("sql, esperado", [ + ("SELECT 'Status :ativo' AS v", "Status :ativo"), + ("SELECT '12:30' AS v", "12:30"), + ("SELECT 'a % b' AS v", "a % b"), +]) +def test_executor_via_engine_preserva_literais_com_dois_pontos(sql, esperado): + """A SQL do agente vai crua ao driver: ':palavra' em literal não vira parâmetro de bind.""" + from text_to_insight.nodes.code_agent.code_sql import executar_sql_via_engine engine = _engine_sqlite_fixture() try: - resultado = nos_nodo_esquema({}, engine=engine) + resultado = executar_sql_via_engine(engine, sql) finally: engine.dispose() - assert resultado["status"] == "schema_obtido" - assert "Tabela:" in resultado["contexto_schema"] + assert resultado["ok"], resultado["erro_execucao"] + assert resultado["linhas_resultado_preview"][0]["v"] == esperado -def test_executor_via_engine(): - """Executor roda a SQL via Engine injetada, sem precisar de db_path/db_url.""" - from text_to_insight.nodes.sandbox import nos_nodo_sandbox +@pytest.mark.parametrize("sql, esperado", [ + ("SELECT '50%' AS v", "50%"), + ("SELECT 'abc' LIKE '%b%' AS v", True), + ("SELECT 10 % 3 AS v", 1), + ("SELECT '%(x)s' AS v", "%(x)s"), + ("SELECT 'Status :ativo' AS v", "Status :ativo"), +]) +def test_executor_postgres_preserva_porcento_e_dois_pontos(pg_engine, sql, esperado): + """ + psycopg2 trata "%" como marcador de parâmetro: sem no_parameters, LIKE '%b%', + '50%' e o operador de módulo quebravam no PostgreSQL (no SQLite "%" não é especial). + """ + from text_to_insight.nodes.code_agent.code_sql import executar_sql_via_engine - engine = _engine_sqlite_fixture() - try: - estado = {"sql_gerada": "SELECT COUNT(*) as total FROM orders"} - resultado = nos_nodo_sandbox(estado, engine=engine) - finally: - engine.dispose() + resultado = executar_sql_via_engine(pg_engine, sql) - assert resultado["status"] == "exec_ok" - assert resultado["total_linhas_resultado"] == 1 + assert resultado["ok"], resultado["erro_execucao"] + assert resultado["linhas_resultado_preview"][0]["v"] == esperado def test_executor_via_engine_nao_deixa_timeout_na_conexao_do_pool(): @@ -314,39 +333,35 @@ def test_executor_via_engine_nao_deixa_timeout_na_conexao_do_pool(): assert total > 0 -def test_data_exploration_via_engine_ignora_db_path(): - """Com engine injetada, a exploração usa o banco da engine, não o db_path do estado.""" +def test_data_exploration_via_engine(olist_engine): + """A exploração lê as estatísticas do banco da engine injetada.""" from text_to_insight.nodes.data_exploration import nos_nodo_data_exploration - engine = _engine_sqlite_fixture() - try: - estado = { - "contexto_rag_schema": "Tabela: orders\n- order_id: TEXT", - "db_path": "/nao/existe.db", - "colunas_para_explorar": {"orders": ["order_status"]}, - } - resultado = nos_nodo_data_exploration(estado, engine=engine) - finally: - engine.dispose() + estado = { + "contexto_rag_schema": "Tabela: orders\n- order_id: TEXT", + "colunas_para_explorar": {"orders": ["order_status"]}, + } + resultado = nos_nodo_data_exploration(estado, engine=olist_engine) assert "order_status" in resultado["contexto_data_exploration"] -def test_data_exploration_engine_nao_sqlite_pula(): - """Exploração é SQLite-only: com engine de outro dialeto, pula sem tocar no db_path.""" +def test_data_exploration_dialeto_sem_suporte_pula(): + """Exploração suporta SQLite e PostgreSQL: com outro dialeto, pula sem conectar.""" from sqlalchemy import create_engine from text_to_insight.nodes.data_exploration import nos_nodo_data_exploration - engine = create_engine("postgresql+psycopg2://u:p@localhost:1/nao_conecta") - estado = {"contexto_rag_schema": "Tabela: orders", "db_path": DB_PATH} + engine = create_engine("mysql+pymysql://u:p@localhost:1/nao_conecta") + estado = {"contexto_rag_schema": "Tabela: orders"} resultado = nos_nodo_data_exploration(estado, engine=engine) assert resultado == {"contexto_data_exploration": ""} -def test_enrich_com_engine_nao_grava_cache_do_db_path(tmp_path): - """Schema vindo da engine não pode sobrescrever o cache do SQLite local.""" +def test_enrich_grava_cache_pelo_hash_do_schema(tmp_path): + """O enriquecimento grava o cache na pasta de cache, indexado pelo schema recebido.""" from types import SimpleNamespace + from text_to_insight.cache import ler_schema_enriquecido from text_to_insight.nodes.enrich_schema import nos_nodo_enrich class _FakeLLM: @@ -354,26 +369,24 @@ def bind(self, **_): return self def batch(self, prompts, config=None): - return [SimpleNamespace(content="{}") for _ in prompts] + return [SimpleNamespace(content='{"t": {"a": "coluna a"}}') for _ in prompts] - db_path = tmp_path / "local.db" - estado = {"db_path": str(db_path), "contexto_schema": "Tabela: t\n- a: INT"} - engine = _engine_sqlite_fixture() - try: - nos_nodo_enrich(estado, _FakeLLM(), engine=engine) - finally: - engine.dispose() + schema = "Tabela: t\n- a: INT\n" + resultado = nos_nodo_enrich({"contexto_schema": schema}, _FakeLLM(), cache_dir=tmp_path) - assert list(tmp_path.iterdir()) == [] + assert resultado["tem_descricao"] is True + assert "coluna a" in resultado["contexto_schema"] + assert ler_schema_enriquecido(tmp_path, schema) == resultado["contexto_schema"] + assert ler_schema_enriquecido(tmp_path, "Tabela: outra\n") is None def test_resolver_dialeto_via_engine(): - """Dialeto do prompt é lido de engine.dialect.name, não de db_url.""" + """Dialeto do prompt é lido de engine.dialect.name.""" from text_to_insight.nodes.code_agent.code_agent import _resolver_info_dialeto engine = _engine_sqlite_fixture() try: - nome, nota = _resolver_info_dialeto({}, engine=engine) + nome, nota = _resolver_info_dialeto(engine) finally: engine.dispose() @@ -451,8 +464,14 @@ def test_roteador_planejador_espera_humana(): # ============================================================ def _schema_olist_real(): + from tests.conftest import criar_engine_sqlite from text_to_insight.nodes.schema import nos_nodo_esquema - return nos_nodo_esquema({"db_path": DB_PATH, "pergunta_atual": "x"})["contexto_schema"] + + engine = criar_engine_sqlite(DB_PATH) + try: + return nos_nodo_esquema({"pergunta_atual": "x"}, engine=engine)["contexto_schema"] + finally: + engine.dispose() def test_schema_graph_constroi_nos_e_arestas_do_olist(): @@ -486,9 +505,8 @@ def test_schema_graph_rag_retrieve_reduz_e_liga(tmp_path, monkeypatch): import chromadb from text_to_insight.retriever import engine as engine_mod - # Isola o índice persistente em tmp_path para não poluir o disco do projeto. - monkeypatch.setattr(engine_mod, "BASE_DIR", tmp_path) - rag = engine_mod.SchemaGraphRAG(schema={"contexto_schema": _schema_olist_real()}) + # Isola o índice persistente em tmp_path para não poluir o cache do usuário. + rag = engine_mod.SchemaGraphRAG(schema={"contexto_schema": _schema_olist_real()}, cache_dir=tmp_path) # Query em inglês: o embedder default do Chroma (all-MiniLM-L6-v2) é treinado em inglês. # PT-BR fica out-of-scope para o MVP (ver Fora de escopo no plano). tabs, rels = rag.retrieve("How many orders does each customer have?") @@ -504,8 +522,8 @@ def test_no_retriever_reduz_contexto_schema(): from text_to_insight.nodes.retriever import nos_nodo_retriever from text_to_insight.nodes.schema import nos_nodo_esquema - estado = {"db_path": DB_PATH, "pergunta_atual": "How many orders does each customer have?"} - schema_base = nos_nodo_esquema(estado)["contexto_schema"] + estado = {"pergunta_atual": "How many orders does each customer have?"} + schema_base = _schema_olist_real() # Adiciona linhas de comentário para ultrapassar o limiar de 5000 chars e acionar o RAG estado["contexto_schema"] = schema_base + "\n" + ("-- padding de teste para atingir threshold de RAG\n" * 100) tam_original = len(estado["contexto_schema"]) @@ -521,49 +539,14 @@ def test_no_retriever_schema_pequeno_mantem_original(): from text_to_insight.nodes.retriever import nos_nodo_retriever from text_to_insight.nodes.schema import nos_nodo_esquema - estado = {"db_path": DB_PATH, "pergunta_atual": "How many orders does each customer have?"} - estado["contexto_schema"] = nos_nodo_esquema(estado)["contexto_schema"] + estado = {"pergunta_atual": "How many orders does each customer have?"} + estado["contexto_schema"] = _schema_olist_real() assert len(estado["contexto_schema"]) < 5000 out = nos_nodo_retriever(estado) assert out.get("contexto_rag_schema") == "" assert out.get("status") == "schema_obtido" -# ============================================================ -# TESTES DO SCHEMA CRAWLER -# ============================================================ -SC_BIN = os.getenv("SCHEMACRAWLER_BIN") -DB_PATH = os.path.join(os.path.dirname(__file__), "..", "data", "olist_relational.db") - - -# --- Camada 1: sem SC, sempre roda no CI --- -def test_deteccao_dialeto_sqlite(): - from text_to_insight.nodes.schema import _detectar_dialeto - assert _detectar_dialeto("banco.db") == "sqlite" - assert _detectar_dialeto("dados.duckdb") == "duckdb" - assert _detectar_dialeto("arquivo.unknown") == "sqlite" # fallback - - -# --- Camada 2: requer SC instalado --- - -@pytest.mark.schemacrawler -@pytest.mark.skipif(not SC_BIN, reason="SCHEMACRAWLER_BIN não configurado no .env") -def test_extracao_schema_com_schemacrawler(): - """Testa extração de schema usando Schema Crawler. Requer SC instalado e Java.""" - from text_to_insight.nodes.schema import _rodar_schemacrawler - - schema = _rodar_schemacrawler( - db_path=DB_PATH, - dialeto="sqlite", - sc_bin=SC_BIN, - ) - - assert "orders" in schema.lower() - assert "customers" in schema.lower() - assert "products" in schema.lower() - assert "customer_id" in schema.lower() - assert "order_id" in schema.lower() - # ============================================================ # TESTES NOVOS (FKs Virtuais, Roteador e Injeção Matemática) # ============================================================ diff --git a/tests/test_data_exploration.py b/tests/test_data_exploration.py index 9e28749..a9d1eee 100644 --- a/tests/test_data_exploration.py +++ b/tests/test_data_exploration.py @@ -19,8 +19,8 @@ TableExplorationResult, _classify_column_type, _extract_table_names_from_rag_context, + _explorar_tabelas, explore_table, - explore_tables, format_exploration_for_prompt, nos_nodo_data_exploration, nos_nodo_exploration_selector, @@ -92,6 +92,25 @@ def sample_db(tmp_path): return str(db_path) +@pytest.fixture +def sample_engine(sample_db): + """Engine SQLAlchemy somente leitura do banco de exemplo (como o chamador passaria).""" + from tests.conftest import criar_engine_sqlite + + engine = criar_engine_sqlite(sample_db) + yield engine + engine.dispose() + + +def explore_tables(db_path, table_names, colunas_para_explorar=None, known_row_counts=None): + """Explora tabelas de um arquivo SQLite numa conexão read-only própria.""" + conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) + try: + return _explorar_tabelas(conn, table_names, colunas_para_explorar, known_row_counts) + finally: + conn.close() + + @pytest.fixture def sample_conn(sample_db): """Retorna uma conexão read-only ao banco de exemplo.""" @@ -237,11 +256,54 @@ def test_nonexistent_table_skipped(self, sample_db): assert "products" in results assert "nonexistent" not in results - def test_nonexistent_db_returns_empty(self): - results = explore_tables("/tmp/nonexistent_db.db", ["products"]) + def test_nonexistent_table_with_known_row_count_skipped(self, sample_db): + # Com a contagem vinda do cache não há COUNT(*) para falhar; a tabela + # sem colunas não pode entrar no resultado (o cache a marcaria completa). + results = explore_tables(sample_db, ["nonexistent"], known_row_counts={"nonexistent": 5}) assert results == {} +# --------------------------------------------------------------------------- +# Amostragem das estatísticas numéricas +# --------------------------------------------------------------------------- + + +def _tabela_numerica(valores): + conn = sqlite3.connect(":memory:") + conn.execute("CREATE TABLE t (v INTEGER)") + conn.executemany("INSERT INTO t VALUES (?)", [(v,) for v in valores]) + return conn + + +class TestAmostraNumerica: + def test_mediana_usa_a_amostra_em_tabela_grande(self): + # 20 mil valores em ordem decrescente: a amostra são as 10 mil + # primeiras linhas (20000..10001), e a mediana tem que estar nela. + stats = explore_table(_tabela_numerica(range(20_000, 0, -1)), "t").columns["v"] + + assert (stats.min, stats.max) == (10_001, 20_000) + assert stats.median == 15_000.5 + assert stats.mean == 15_000.5 + + def test_nulos_nao_puxam_a_mediana_para_fora_da_amostra(self): + # A amostra tem 9999 nulos e um 1; os 1000 vêm depois dela. + conn = _tabela_numerica([None] * 9_999 + [1] + [1_000] * 10_000) + stats = explore_table(conn, "t").columns["v"] + + assert (stats.mean, stats.min, stats.max, stats.median) == (1, 1, 1, 1) + assert stats.std_dev == 0 + assert stats.null_rate == 0.9999 + + @pytest.mark.parametrize("valores, mediana", [([1, 2, 3, 4], 2.5), ([3, 1, 2], 2), ([7], 7)]) + def test_mediana_par_e_impar(self, valores, mediana): + assert explore_table(_tabela_numerica(valores), "t").columns["v"].median == mediana + + def test_valores_de_exemplo_sao_reprodutiveis(self, sample_conn): + a = explore_table(sample_conn, "products") + b = explore_table(sample_conn, "products") + assert a == b + + # --------------------------------------------------------------------------- # Testes de formatação para prompt # --------------------------------------------------------------------------- @@ -307,104 +369,57 @@ def test_no_tables(self): class TestNodoDataExploration: - def test_returns_exploration_context(self, sample_db): + def test_returns_exploration_context(self, sample_engine): estado = { - "db_path": sample_db, "contexto_rag_schema": ( "Tabela: products\n- id: INTEGER\n\n" "Tabela: orders\n- id: INTEGER\n" ), } - result = nos_nodo_data_exploration(estado) + result = nos_nodo_data_exploration(estado, engine=sample_engine) assert "contexto_data_exploration" in result assert "products" in result["contexto_data_exploration"] assert "orders" in result["contexto_data_exploration"] - def test_missing_rag_context_returns_empty(self, sample_db): - estado = {"db_path": sample_db, "contexto_rag_schema": ""} - result = nos_nodo_data_exploration(estado) - assert result == {} - - def test_missing_db_path_returns_empty(self): - estado = {"db_path": "", "contexto_rag_schema": "Tabela: products\n"} - result = nos_nodo_data_exploration(estado) + def test_missing_rag_context_returns_empty(self, sample_engine): + estado = {"contexto_rag_schema": ""} + result = nos_nodo_data_exploration(estado, engine=sample_engine) assert result == {} - def test_exploration_output_fits_prompt(self, sample_db): + def test_exploration_output_fits_prompt(self, sample_engine): """O output deve ser compacto o suficiente para caber num prompt LLM.""" - estado = { - "db_path": sample_db, - "contexto_rag_schema": "Tabela: products\n- id: INTEGER\n", - } - result = nos_nodo_data_exploration(estado) + estado = {"contexto_rag_schema": "Tabela: products\n- id: INTEGER\n"} + result = nos_nodo_data_exploration(estado, engine=sample_engine) text = result.get("contexto_data_exploration", "") # Não deveria exceder ~2000 chars para uma tabela com 7 colunas assert len(text) < 5000 - def test_exploration_disabled(self, sample_db): - estado = { - "db_path": sample_db, - "contexto_rag_schema": "Tabela: products\n- id: INTEGER\n", - } - result = nos_nodo_data_exploration(estado, use_data_exploration=False) + def test_exploration_disabled(self, sample_engine): + estado = {"contexto_rag_schema": "Tabela: products\n- id: INTEGER\n"} + result = nos_nodo_data_exploration(estado, engine=sample_engine, use_data_exploration=False) assert result == {"contexto_data_exploration": ""} - def test_exploration_with_colunas_para_explorar(self, sample_db): + def test_exploration_with_colunas_para_explorar(self, sample_engine): estado = { - "db_path": sample_db, "contexto_rag_schema": "Tabela: products\n- id: INTEGER\n", "colunas_para_explorar": { "products": ["price"] } } - result = nos_nodo_data_exploration(estado, use_data_exploration=True) + result = nos_nodo_data_exploration(estado, engine=sample_engine, use_data_exploration=True) text = result.get("contexto_data_exploration", "") assert "price" in text # Because we only requested "price", name or category should not be in the exploration context assert "name" not in text assert "category" not in text - # --- Bancos que não são um arquivo SQLite local: o nó deve PULAR --------- - # Cenário real: o usuário roda com --db-url mas --db-path sobra com um .db - # antigo que EXISTE. Sem o guard, o nó exploraria esse arquivo sem relação - # com o banco de verdade. - - @pytest.mark.parametrize( - "campos_do_banco", - [ - {"db_url": "mysql+pymysql://u:p@localhost:3306/banco"}, - {"db_url": "postgresql://u:p@localhost:5432/banco"}, - {"db_url": "sqlite:///outro_arquivo.db"}, - ], - ) - def test_skips_when_backend_is_not_local_sqlite(self, sample_db, campos_do_banco): - # sample_db é um .db REAL e explorável: se o guard falhasse, o nó o exploraria. - estado = { - "db_path": sample_db, - "contexto_rag_schema": "Tabela: products\n- id: INTEGER\n", - **campos_do_banco, - } - result = nos_nodo_data_exploration(estado) - assert result == {} - - def test_skips_for_duckdb_extension(self, sample_db, tmp_path): - # .duckdb é detectado pela extensão do db_path; o nó não sabe abrir DuckDB. - arquivo = tmp_path / "dados.duckdb" - arquivo.write_bytes(Path(sample_db).read_bytes()) - estado = { - "db_path": str(arquivo), - "contexto_rag_schema": "Tabela: products\n- id: INTEGER\n", - } - assert nos_nodo_data_exploration(estado) == {} + def test_skips_unsupported_dialect(self): + # Só SQLite e PostgreSQL são suportados: com outro dialeto o nó pula sem conectar. + from sqlalchemy import create_engine - def test_still_explores_local_sqlite_with_empty_db_url(self, sample_db): - estado = { - "db_path": sample_db, - "db_url": "", # vazio/None não conta como db_url preenchido - "contexto_rag_schema": "Tabela: products\n- id: INTEGER\n", - } - result = nos_nodo_data_exploration(estado) - assert "products" in result["contexto_data_exploration"] + engine = create_engine("mysql+pymysql://u:p@localhost:3306/banco") + estado = {"contexto_rag_schema": "Tabela: products\n- id: INTEGER\n"} + assert nos_nodo_data_exploration(estado, engine=engine) == {"contexto_data_exploration": ""} class TestCacheDataExploration: @@ -417,23 +432,28 @@ def espiao(self, monkeypatch): chamadas = [] original = de.explore_table - def _espiao(conn, table_name, columns_to_explore=None, row_count=None): + def _espiao(conn, table_name, columns_to_explore=None, row_count=None, dialeto="sqlite"): chamadas.append((table_name, columns_to_explore)) - return original(conn, table_name, columns_to_explore, row_count=row_count) + return original(conn, table_name, columns_to_explore, row_count=row_count, dialeto=dialeto) monkeypatch.setattr(de, "explore_table", _espiao) return chamadas @staticmethod def _rodar(sample_db, tabelas, cache=None, colunas=None): + from tests.conftest import criar_engine_sqlite + estado = { - "db_path": sample_db, "contexto_rag_schema": "".join(f"Tabela: {t}\n- id: INTEGER\n" for t in tabelas), "cache_data_exploration": cache or {}, } if colunas is not None: estado["colunas_para_explorar"] = colunas - return nos_nodo_data_exploration(estado) + engine = criar_engine_sqlite(sample_db) + try: + return nos_nodo_data_exploration(estado, engine=engine) + finally: + engine.dispose() @pytest.mark.parametrize("colunas", [None, {"products": ["price", "category"]}]) def test_texto_igual_ao_formatador_sem_cache(self, sample_db, colunas): @@ -500,7 +520,7 @@ def test_nao_altera_cache_recebido_e_e_serializavel(self, sample_db): def test_estado_inicial_zera_cache(self): from text_to_insight.runtime import construir_estado_inicial - assert construir_estado_inicial("pergunta", db_path="x.db")["cache_data_exploration"] == {} + assert construir_estado_inicial("pergunta")["cache_data_exploration"] == {} def test_nao_reexecuta_count_quando_linhas_no_cache(self, sample_db, monkeypatch): import sqlite3 @@ -509,9 +529,9 @@ def test_nao_reexecuta_count_quando_linhas_no_cache(self, sample_db, monkeypatch row_counts_recebidos = [] original = de.explore_table - def _espiao_row_count(conn, table_name, columns_to_explore=None, row_count=None): + def _espiao_row_count(conn, table_name, columns_to_explore=None, row_count=None, dialeto="sqlite"): row_counts_recebidos.append((table_name, row_count)) - return original(conn, table_name, columns_to_explore, row_count=row_count) + return original(conn, table_name, columns_to_explore, row_count=row_count, dialeto=dialeto) monkeypatch.setattr(de, "explore_table", _espiao_row_count) diff --git a/tests/test_data_exploration_postgres.py b/tests/test_data_exploration_postgres.py new file mode 100644 index 0000000..ba52b38 --- /dev/null +++ b/tests/test_data_exploration_postgres.py @@ -0,0 +1,399 @@ +""" +Data exploration em PostgreSQL. + +Os testes que precisam de um banco real usam a fixture `pg_engine` e são +pulados se TEXT_TO_INSIGHT_TEST_PG_URL não estiver definida (a CI sobe um +serviço PostgreSQL e define a variável). +""" + +import os + +import pytest +from sqlalchemy import create_engine, text + +import text_to_insight.nodes.data_exploration as de +from text_to_insight.nodes.data_exploration import ( + _classify_column_type, + _extract_table_names_from_rag_context, + _q, + nos_nodo_data_exploration, +) + + +def _rag(*tabelas: str) -> str: + return "".join(f"Tabela: {t}\n- coluna: TIPO\n\n" for t in tabelas) + + +def _explorar(engine, tabela, colunas=None): + """Explora uma tabela pelo mesmo caminho do nó (conexão, transação, devolução ao pool).""" + parcial = {tabela: colunas} if colunas else {} + return de._explorar_no_banco(engine, "postgresql", [tabela], parcial, {})[tabela] + + +class _CursorAlterado: + """Cursor que troca as consultas para as quais `trocar(sql)` devolve outra SQL.""" + + def __init__(self, cursor, trocar): + self._cursor = cursor + self._trocar = trocar + + def execute(self, sql, *args): + return self._cursor.execute(self._trocar(sql) or sql, *args) + + def __getattr__(self, nome): + return getattr(self._cursor, nome) + + +class _ConexaoAlterada: + """Conexão do pool cujos cursores passam por `_CursorAlterado`.""" + + def __init__(self, conn, trocar): + self._conn = conn + self._trocar = trocar + + def cursor(self): + return _CursorAlterado(self._conn.cursor(), self._trocar) + + def __getattr__(self, nome): + return getattr(self._conn, nome) + + +def _engine_pg(**kwargs): + url = os.environ["TEXT_TO_INSIGHT_TEST_PG_URL"] + return create_engine(url, **kwargs) + + +@pytest.fixture +def pg_banco(pg_engine): + """Tabelas de exemplo com tipos nativos do PostgreSQL.""" + with pg_engine.begin() as conn: + conn.execute(text("CREATE TYPE humor AS ENUM ('feliz', 'triste', 'neutro')")) + conn.execute(text(""" + CREATE TABLE produtos ( + id serial PRIMARY KEY, + preco numeric(10, 2), + categoria text, + ativo boolean, + criado_em timestamptz, + prazo interval, + humor humor, + tags text[], + extra json, + "Nome Exibido" varchar(40) + ) + """)) + conn.execute(text(""" + INSERT INTO produtos (preco, categoria, ativo, criado_em, prazo, humor, tags, extra, "Nome Exibido") + SELECT g * 1.5, + CASE WHEN g % 10 = 0 THEN NULL ELSE 'cat_' || (g % 3) END, + g % 4 = 0, + TIMESTAMPTZ '2024-01-01 00:00:00+00' + make_interval(days => g), + make_interval(hours => g % 48), + (ARRAY['feliz', 'triste', 'neutro'])[1 + g % 3]::humor, + ARRAY['t' || (g % 2)], + json_build_object('g', g), + 'Produto ' || g + FROM generate_series(1, 200) g + """)) + conn.execute(text('CREATE TABLE "Tabela Com Espaço" ("Coluna ""Aspas""" int)')) + conn.execute(text('INSERT INTO "Tabela Com Espaço" VALUES (1), (2), (NULL)')) + return pg_engine + + +# --------------------------------------------------------------------------- +# Sem banco +# --------------------------------------------------------------------------- + +class TestHelpersSemBanco: + def test_nomes_de_tabela_com_espaco(self): + contexto = "Tabela: orders\n- id: INT\n\nTabela: Tabela Com Espaço \n- x: INT\n" + assert _extract_table_names_from_rag_context(contexto) == ["orders", "Tabela Com Espaço"] + + def test_identificador_escapa_aspas(self): + assert _q('Coluna "Aspas"') == '"Coluna ""Aspas"""' + + @pytest.mark.parametrize("tipo, categoria", [ + ("interval", "date"), + ("timestamp with time zone", "date"), + ("double precision", "numeric"), + ("numeric", "numeric"), + ("character varying", "categorical"), + ("USER-DEFINED", "categorical"), + ("ARRAY", "categorical"), + ("boolean", "boolean"), + ]) + def test_classifica_tipos_do_postgres(self, tipo, categoria): + assert _classify_column_type(tipo) == categoria + + +# --------------------------------------------------------------------------- +# Com PostgreSQL real +# --------------------------------------------------------------------------- + +class TestExploracaoPostgres: + def test_estatisticas_por_tipo(self, pg_banco): + resultado = _explorar(pg_banco, "produtos") + colunas = resultado.columns + + assert resultado.row_count_estimate == 200 + preco = colunas["preco"] + assert preco.dtype == "numeric" + assert (preco.min, preco.max) == (1.5, 300.0) + assert preco.min <= preco.median <= preco.max + assert colunas["categoria"].null_rate == 0.1 + assert colunas["categoria"].cardinality == 3 + assert (colunas["ativo"].true_count, colunas["ativo"].false_count) == (50, 150) + assert colunas["criado_em"].dtype == "date" + # o texto depende do fuso da sessão; só a ordem é garantida + assert colunas["criado_em"].min < colunas["criado_em"].max + assert len(colunas["criado_em"].sample_values) == 3 + assert colunas["prazo"].dtype == "date" + assert colunas["humor"].cardinality == 3 + assert colunas["tags"].cardinality == 2 + assert colunas["Nome Exibido"].cardinality == 200 + + def test_no_injeta_estatisticas_no_prompt(self, pg_banco): + r = nos_nodo_data_exploration({"contexto_rag_schema": _rag("produtos")}, engine=pg_banco) + + texto = r["contexto_data_exploration"] + assert "Tabela: produtos (~200 linhas)" in texto + assert "preco [numeric]" in texto and "ativo [boolean]" in texto + + def test_coluna_sem_suporte_e_pulada_sem_derrubar_as_outras(self, pg_banco): + # GROUP BY em json falha ("could not identify an equality operator"); + # sem o rollback, todas as consultas seguintes falhariam também. + r = nos_nodo_data_exploration({"contexto_rag_schema": _rag("produtos")}, engine=pg_banco) + colunas = r["cache_data_exploration"]["produtos"]["colunas"] + + assert "extra" not in colunas + assert "Nome Exibido" in colunas # vem depois de `extra` na tabela + + def test_tabela_inexistente_nao_derruba_as_outras(self, pg_banco): + r = nos_nodo_data_exploration({"contexto_rag_schema": _rag("nao_existe", "produtos")}, engine=pg_banco) + + assert "Tabela: produtos" in r["contexto_data_exploration"] + assert "nao_existe" not in r["cache_data_exploration"] + + def test_nomes_com_espaco_e_aspas(self, pg_banco): + r = nos_nodo_data_exploration({"contexto_rag_schema": _rag("Tabela Com Espaço")}, engine=pg_banco) + assert 'Coluna "Aspas"' in r["cache_data_exploration"]["Tabela Com Espaço"]["colunas"] + + coluna = _explorar(pg_banco, "Tabela Com Espaço").columns['Coluna "Aspas"'] + assert coluna.null_rate == round(1 / 3, 4) + + def test_estatisticas_estaveis_entre_execucoes(self, pg_banco): + # Todas as colunas, inclusive os valores de exemplo das categóricas e datas. + estado = {"contexto_rag_schema": _rag("produtos")} + a = nos_nodo_data_exploration(estado, engine=pg_banco)["cache_data_exploration"] + b = nos_nodo_data_exploration(estado, engine=pg_banco)["cache_data_exploration"] + assert a == b + + def test_conexao_volta_limpa_para_o_pool(self, pg_banco): + with pg_banco.connect() as conn: + antes = {g: conn.execute(text(f"SHOW {g}")).scalar() + for g in ("statement_timeout", "transaction_read_only", "max_parallel_workers_per_gather")} + + nos_nodo_data_exploration({"contexto_rag_schema": _rag("produtos")}, engine=pg_banco) + + with pg_banco.connect() as conn: + depois = {g: conn.execute(text(f"SHOW {g}")).scalar() for g in antes} + # e a conexão continua podendo escrever (não ficou presa em read-only) + conn.execute(text("CREATE TEMP TABLE escrita_ok (a int)")) + conn.rollback() + assert depois == antes + + def test_sessao_de_exploracao_e_somente_leitura(self, pg_banco): + conn = pg_banco.raw_connection() + try: + de._preparar_sessao_postgres(conn) + cur = conn.cursor() + with pytest.raises(Exception, match="read-only"): + cur.execute("CREATE TABLE nao_pode (a int)") + finally: + conn.rollback() + conn.close() + + def test_tabela_grande_usa_estimativa_do_catalogo(self, pg_banco, monkeypatch): + # Depois do ANALYZE o catálogo estima 200 linhas; as 100 inseridas em + # seguida só aparecem num COUNT(*) exato. + with pg_banco.begin() as conn: + conn.execute(text("ANALYZE produtos")) + conn.execute(text("INSERT INTO produtos (preco) SELECT g FROM generate_series(1, 100) g")) + estado = {"contexto_rag_schema": _rag("produtos"), "colunas_para_explorar": {"produtos": ["preco"]}} + + monkeypatch.setattr(de, "LIMIAR_ESTIMATIVA_LINHAS", 100) + estimado = nos_nodo_data_exploration(estado, engine=pg_banco)["cache_data_exploration"]["produtos"]["linhas"] + monkeypatch.setattr(de, "LIMIAR_ESTIMATIVA_LINHAS", 10_000) + exato = nos_nodo_data_exploration(estado, engine=pg_banco)["cache_data_exploration"]["produtos"]["linhas"] + + assert (estimado, exato) == (200, 300) + + @pytest.mark.parametrize("consulta", ["variancia", "mediana"]) + def test_erro_numa_consulta_opcional_nao_derruba_a_coluna_seguinte(self, pg_banco, consulta): + # Variância e mediana podem falhar sem perder a coluna; no PostgreSQL o + # erro aborta a transação, que precisa voltar ao savepoint antes da + # próxima coluna. + def trocar(sql): + if consulta == "variancia" and sql.startswith('SELECT AVG(("preco"'): + return "SELECT 1/0" + if consulta == "mediana" and 'ORDER BY "preco"' in sql: + return "SELECT 1/0" + return None + + conn = _ConexaoAlterada(pg_banco.raw_connection(), trocar) + try: + de._preparar_sessao_postgres(conn) + colunas = de.explore_table(conn, "produtos", ["preco", "categoria"], dialeto="postgresql").columns + finally: + conn.rollback() + conn.close() + + assert colunas["preco"].mean == 150.75 + assert (colunas["preco"].std_dev is None) == (consulta == "variancia") + assert (colunas["preco"].median is None) == (consulta == "mediana") + assert colunas["categoria"].cardinality == 3 + + def test_numeric_fora_do_alcance_do_float(self, pg_banco): + with pg_banco.begin() as conn: + conn.execute(text("CREATE TABLE enormes (enorme numeric, depois int)")) + conn.execute(text("INSERT INTO enormes VALUES (1e400, 1), (2e400, 3)")) + + colunas = _explorar(pg_banco, "enormes").columns + + assert colunas["enorme"].mean is None and colunas["enorme"].max is None + assert (colunas["depois"].mean, colunas["depois"].median) == (2, 2) + + def test_conexao_perdida_mantem_as_tabelas_ja_exploradas(self, pg_banco, monkeypatch): + with pg_banco.begin() as conn: + conn.execute(text("CREATE TABLE depois_da_queda (a int)")) + + def trocar(sql): + if '"Tabela Com Espaço"' in sql: + return "SELECT pg_terminate_backend(pg_backend_pid())" + return None + + original = pg_banco.raw_connection + monkeypatch.setattr(pg_banco, "raw_connection", lambda: _ConexaoAlterada(original(), trocar)) + r = nos_nodo_data_exploration( + {"contexto_rag_schema": _rag("produtos", "Tabela Com Espaço", "depois_da_queda")}, engine=pg_banco + ) + monkeypatch.undo() + + assert list(r["cache_data_exploration"]) == ["produtos"] + # A conexão morta foi descartada pelo pool; a engine continua utilizável. + with pg_banco.connect() as conn: + assert conn.execute(text("SELECT 1")).scalar() == 1 + + def test_tabela_nunca_analisada_conta_ate_o_limite(self, pg_banco, monkeypatch): + # Sem ANALYZE, reltuples é -1: a contagem roda, mas para no limite. + with pg_banco.begin() as conn: + conn.execute(text("CREATE TABLE sem_analyze AS SELECT g AS a FROM generate_series(1, 300) g")) + assert conn.execute(text("SELECT reltuples FROM pg_class WHERE relname = 'sem_analyze'")).scalar() < 0 + monkeypatch.setattr(de, "LIMIAR_ESTIMATIVA_LINHAS", 100) + + assert _explorar(pg_banco, "sem_analyze").row_count_estimate == 100 + + +class TestEngineAutocommit: + @pytest.fixture + def engine_autocommit(self, pg_banco): + from tests.conftest import PG_SCHEMA_TESTES + + engine = _engine_pg( + isolation_level="AUTOCOMMIT", + pool_size=1, + max_overflow=0, + connect_args={"options": f"-c search_path={PG_SCHEMA_TESTES}"}, + ) + yield engine + engine.dispose() + + def test_exploracao_tem_transacao_somente_leitura_e_timeout(self, engine_autocommit, monkeypatch): + vistos = {} + original = de._STAT_DISPATCHER["numeric"] + + def espiao(cursor, *args, **kwargs): + for guc in ("transaction_read_only", "statement_timeout"): + cursor.execute(f"SHOW {guc}") + vistos[guc] = cursor.fetchone()[0] + return original(cursor, *args, **kwargs) + + monkeypatch.setitem(de._STAT_DISPATCHER, "numeric", espiao) + r = nos_nodo_data_exploration( + {"contexto_rag_schema": _rag("produtos"), "colunas_para_explorar": {"produtos": ["preco"]}}, + engine=engine_autocommit, + ) + + assert "preco" in r["cache_data_exploration"]["produtos"]["colunas"] + assert vistos == {"transaction_read_only": "on", "statement_timeout": "15s"} + + def test_conexao_volta_ao_pool_em_autocommit(self, engine_autocommit): + nos_nodo_data_exploration({"contexto_rag_schema": _rag("produtos")}, engine=engine_autocommit) + + with engine_autocommit.connect() as conn: + assert conn.connection.driver_connection.autocommit is True + # autocommit de verdade: a escrita vale sem commit explícito + conn.execute(text("CREATE TABLE criada_em_autocommit (a int)")) + with engine_autocommit.connect() as conn: + assert conn.execute(text("SELECT to_regclass('criada_em_autocommit') IS NOT NULL")).scalar() + + +class TestSearchPath: + """A exploração enxerga as mesmas tabelas que o SQLAlchemy lista no nó de schema.""" + + SEGUNDO = "tti_testes_segundo" + + @pytest.fixture + def engine_dois_schemas(self, pg_engine): + from sqlalchemy import inspect + + from tests.conftest import PG_SCHEMA_TESTES + + with pg_engine.begin() as conn: + conn.execute(text(f"DROP SCHEMA IF EXISTS {self.SEGUNDO} CASCADE")) + conn.execute(text(f"CREATE SCHEMA {self.SEGUNDO}")) + conn.execute(text(f"CREATE TABLE {self.SEGUNDO}.so_no_segundo (a int, b text)")) + conn.execute(text(f"INSERT INTO {self.SEGUNDO}.so_no_segundo SELECT g, 'v' || g FROM generate_series(1, 300) g")) + conn.execute(text(f"ANALYZE {self.SEGUNDO}.so_no_segundo")) + # homônimas: vale a do primeiro schema do search_path + conn.execute(text(f"CREATE TABLE {PG_SCHEMA_TESTES}.homonima (x int)")) + conn.execute(text(f"INSERT INTO {PG_SCHEMA_TESTES}.homonima VALUES (1)")) + conn.execute(text(f"CREATE TABLE {self.SEGUNDO}.homonima (y text)")) + conn.execute(text(f"INSERT INTO {self.SEGUNDO}.homonima VALUES ('a'), ('b')")) + engine = _engine_pg(connect_args={"options": f"-c search_path={PG_SCHEMA_TESTES},{self.SEGUNDO}"}) + assert {"so_no_segundo", "homonima"} <= set(inspect(engine).get_table_names()) + yield engine + engine.dispose() + with pg_engine.begin() as conn: + conn.execute(text(f"DROP SCHEMA IF EXISTS {self.SEGUNDO} CASCADE")) + + def test_tabela_no_segundo_schema(self, engine_dois_schemas): + r = nos_nodo_data_exploration({"contexto_rag_schema": _rag("so_no_segundo")}, engine=engine_dois_schemas) + tabela = r["cache_data_exploration"]["so_no_segundo"] + + assert set(tabela["colunas"]) == {"a", "b"} + assert tabela["linhas"] == 300 + + def test_estimativa_do_catalogo_no_segundo_schema(self, engine_dois_schemas, monkeypatch): + with engine_dois_schemas.begin() as conn: + conn.execute(text(f"INSERT INTO {self.SEGUNDO}.so_no_segundo SELECT g, 'w' FROM generate_series(1, 50) g")) + monkeypatch.setattr(de, "LIMIAR_ESTIMATIVA_LINHAS", 100) + + assert _explorar(engine_dois_schemas, "so_no_segundo").row_count_estimate == 300 # do ANALYZE, não 350 + + def test_tabelas_homonimas_usam_a_primeira_do_search_path(self, engine_dois_schemas): + resultado = _explorar(engine_dois_schemas, "homonima") + + assert list(resultado.columns) == ["x"] + assert resultado.row_count_estimate == 1 + + +def test_falha_de_conexao_nao_derruba_o_fluxo(): + """Se o banco nem conecta, o nó segue sem estatísticas em vez de levantar exceção.""" + from sqlalchemy import create_engine + + engine = create_engine("postgresql+psycopg2://u:p@127.0.0.1:1/nao_conecta", connect_args={"connect_timeout": 1}) + r = nos_nodo_data_exploration({"contexto_rag_schema": _rag("produtos")}, engine=engine) + + assert r["contexto_data_exploration"] == "" + assert r["cache_data_exploration"] == {} diff --git a/tests/test_exec_python.py b/tests/test_exec_python.py new file mode 100644 index 0000000..4cf2dec --- /dev/null +++ b/tests/test_exec_python.py @@ -0,0 +1,65 @@ +from text_to_insight.execucao_python import executar_python_isolado +from pathlib import Path + + +def test_script_simples(): + + resultado = executar_python_isolado('print("ola")') + assert resultado ["ok"] is True + assert "ola" in resultado["saida_terminal"] + assert resultado ["erro_execucao"] == "" + + +def test_script_errado(): + resultado = executar_python_isolado('raise ValueError("deu ruim")') + assert resultado ["ok"] is False + assert "deu ruim" in resultado["erro_execucao"] + assert resultado["saida_terminal"] == "" + +def test_timeout(): + resultado = executar_python_isolado('while True: pass', timeout_s=2) + assert resultado["ok"] is False + assert "timeout" in resultado["erro_execucao"].lower() + +def test_arquivo_chega_script(tmp_path): + origem = tmp_path / "dados dados.txt" + origem.write_text("conteudo de teste", encoding="utf-8") + + script = 'print(open("entrada.txt", encoding="utf-8").read())' + resultado = executar_python_isolado( + script, arquivos_entrada={"entrada.txt": origem} + ) + + assert resultado["ok"] is True + assert "conteudo de teste" in resultado["saida_terminal"] + +def test_copiar_arquivo_de_saida(tmp_path): + script = 'open("saida.txt", "w", encoding="utf-8").write("resultado ok")' + destino = tmp_path / "resultado.txt" + resultado = executar_python_isolado(script, arquivos_saida={"saida.txt": destino}) + assert resultado["ok"] is True + assert destino.exists() is True + destino.read_text(encoding="utf-8") == resultado["ok"] + + + +def test_saida_esperada_nao_gerada(tmp_path): + script = 'pass' + resultado = executar_python_isolado(script, arquivos_saida={"grafico.png": tmp_path / "g.png"}) + assert resultado["ok"] is False + assert "grafico.png" in resultado["erro_execucao"] + +def test_pasta_tmp_some(): + script = 'import os; print(os.getcwd())' + resultado = executar_python_isolado(script) + pasta_usada = Path(resultado["saida_terminal"]) + assert resultado["ok"] is True + assert pasta_usada.exists() is False + +def test_script_ve_variaveis_do_ambiente(monkeypatch): + monkeypatch.setenv("CHAVE_FALSA", "segredo123") + resultado = executar_python_isolado('import os; print(os.environ.get("CHAVE_FALSA"))' + ) + + assert resultado["ok"] is True, resultado["erro_execucao"] + assert "segredo123" not in resultado["saida_terminal"] \ No newline at end of file diff --git a/tests/test_integracao.py b/tests/test_integracao.py index 8701952..8c25368 100644 --- a/tests/test_integracao.py +++ b/tests/test_integracao.py @@ -15,16 +15,15 @@ sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) -DB_PATH = os.path.join(os.path.dirname(__file__), "..", "data", "olist_relational.db") load_dotenv() @pytest.fixture -def grafo(llm_profile): +def grafo(llm_profile, olist_engine): """Retorna o grafo compilado com o provider de teste configurado no ambiente.""" from text_to_insight.graph import Graph - return Graph(llm_profile.api_key, llm_profile.model_name, hitl=True) + return Graph(llm_profile.api_key, llm_profile.model_name, db_engine=olist_engine, hitl=True) @pytest.fixture(autouse=True) @@ -46,7 +45,6 @@ def _estado_inicial(pergunta: str) -> dict: "erro_execucao": "", "status": "iniciado", "tentativas_loop": 0, - "db_path": DB_PATH, } @@ -155,10 +153,10 @@ def _fake_get_model(model, api_key): def _fake_planejador(estado, llm=None, hitl=True): return {"status": "pronto_codificacao"} - def _fake_agente_codigo(estado, llm=None, use_cot=True): + def _fake_agente_codigo(estado, llm=None, use_cot=True, engine=None): return {"sql_gerada": "SELECT 1", "status": "sql_gerada", "tentativas_loop": 1} - def _fake_sandbox(estado): + def _fake_sandbox(estado, engine=None): return { "status": "exec_ok", "linhas_resultado_preview": [{"valor": 1}, {"valor": 2}], @@ -196,7 +194,7 @@ def _fake_roteador_grafico(estado, llm=None): monkeypatch.setattr(graph_module, "roteador_sandbox", _fake_roteador_sandbox) monkeypatch.setattr(graph_module, "roteador_grafico", _fake_roteador_grafico) - return graph_module.Graph(api_key="fake", model="fake", hitl=False, enable_graphs=enable_graphs) + return graph_module.Graph(api_key="fake", model="fake", db_engine=object(), hitl=False, enable_graphs=enable_graphs) def test_grafo_com_graficos_gera_csv_e_png(monkeypatch, tmp_path): @@ -206,7 +204,6 @@ def test_grafo_com_graficos_gera_csv_e_png(monkeypatch, tmp_path): estado = { "pergunta_original": "Teste", "pergunta_atual": "Teste", - "db_path": "fake.db", } resultado = grafo.grafo_text_to_insight.invoke(estado, config) @@ -228,7 +225,6 @@ def test_grafo_sem_graficos_bypassa(monkeypatch, tmp_path): estado = { "pergunta_original": "Teste", "pergunta_atual": "Teste", - "db_path": "fake.db", } resultado = grafo.grafo_text_to_insight.invoke(estado, config) diff --git a/tests/test_main_engine_integracao.py b/tests/test_main_engine_integracao.py index 48bfdf8..3344db8 100644 --- a/tests/test_main_engine_integracao.py +++ b/tests/test_main_engine_integracao.py @@ -10,6 +10,8 @@ import main as main_entry from text_to_insight.InsightEngine import InsightEngine +DB_OLIST = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data", "olist_relational.db") + class _FakeCompiledGraph: def __init__(self): @@ -93,19 +95,19 @@ def _patch_integracao(monkeypatch): def test_integracao_main_engine_sucesso(monkeypatch): _patch_integracao(monkeypatch) - resultado = main_entry.main(["--hitl", "on", "Quantos pedidos existem?"]) + resultado = main_entry.main(["--db-path", DB_OLIST, "--hitl", "on", "Quantos pedidos existem?"]) assert resultado["status"] == "aprovado" assert resultado["sql_gerada"] == "SELECT 1 AS total" -def test_integracao_main_engine_hitl_on_com_retomada(monkeypatch): +def test_integracao_main_engine_hitl_on_com_retomada(monkeypatch, olist_engine): _patch_integracao(monkeypatch) engine = InsightEngine( api_key="fake-key", model="gemini-2.5-flash", - db_path="data/olist_relational.db", + db_engine=olist_engine, hitl=True, show_output=False, ) @@ -121,7 +123,60 @@ def test_integracao_main_engine_hitl_on_com_retomada(monkeypatch): def test_integracao_main_engine_hitl_off_bloqueado(monkeypatch): _patch_integracao(monkeypatch) - resultado = main_entry.main(["--hitl", "off", "consulta com hitl"]) + resultado = main_entry.main(["--db-path", DB_OLIST, "--hitl", "off", "consulta com hitl"]) assert resultado["status"] == "bloqueado_hitl" assert "intervenção humana" in resultado["erro_execucao"].lower() + + +# ============================================================ +# CLI: é o CLI (chamador) quem cria a Engine, não a biblioteca +# ============================================================ + +def test_cli_sem_banco_falha_com_mensagem(monkeypatch): + import pytest + from text_to_insight import cli + + monkeypatch.delenv("DATABASE_URL", raising=False) + with pytest.raises(SystemExit, match="--db-path"): + cli._criar_engine(None, None) + + +def test_cli_db_path_inexistente_falha_sem_criar_arquivo(tmp_path): + import pytest + from text_to_insight import cli + + caminho = tmp_path / "nao_existe.db" + with pytest.raises(SystemExit, match="não encontrado"): + cli._criar_engine(str(caminho), None) + assert not caminho.exists() + + +def test_cli_db_path_abre_sqlite_somente_leitura(): + import pytest + from sqlalchemy import text + from sqlalchemy.exc import OperationalError + from text_to_insight import cli + + engine = cli._criar_engine(DB_OLIST, None) + try: + assert engine.dialect.name == "sqlite" + with engine.connect() as conn: + assert conn.execute(text("SELECT COUNT(*) FROM orders")).scalar() > 0 + with pytest.raises(OperationalError): + conn.execute(text("CREATE TABLE x (a INT)")) + finally: + engine.dispose() + + +def test_cli_db_url_tem_prioridade_e_usa_driver_dos_extras(): + from text_to_insight import cli + + assert cli._normalizar_db_url("postgresql://u:p@h/db") == "postgresql+psycopg2://u:p@h/db" + assert cli._normalizar_db_url("mysql://u:p@h/db") == "mysql+pymysql://u:p@h/db" + + engine = cli._criar_engine(DB_OLIST, "sqlite://") + try: + assert str(engine.url) == "sqlite://" + finally: + engine.dispose() diff --git a/tests/test_model_selection.py b/tests/test_model_selection.py index 43e5dd6..85de476 100644 --- a/tests/test_model_selection.py +++ b/tests/test_model_selection.py @@ -180,7 +180,11 @@ def test_cli_flags_invalidas_sao_rejeitadas(argv): cli._parse_args(argv) -def test_cli_repassa_model_kwargs_para_engine(monkeypatch): +def test_cli_repassa_model_kwargs_para_engine(monkeypatch, tmp_path): + import sqlite3 + + banco = tmp_path / "vazio.db" + sqlite3.connect(banco).close() capturado = {} class _FakeEngine: @@ -194,7 +198,7 @@ def run(self, **kwargs): monkeypatch.setattr(cli, "exibir_resultado_console", lambda r: None) monkeypatch.setenv("OPENAI_API_KEY", "fake-key") - cli.main(["--hitl", "off", "--temperature", "0.3", "--max-tokens", "100", "pergunta"]) + cli.main(["--db-path", str(banco), "--hitl", "off", "--temperature", "0.3", "--max-tokens", "100", "pergunta"]) assert capturado["model_kwargs"] == {"temperature": 0.3, "max_tokens": 100} @@ -208,7 +212,7 @@ def _fake_get_model(model, api_key, **kwargs): return object() monkeypatch.setattr(graph_module, "get_model", _fake_get_model) - graph_module.Graph(api_key="k", model="gpt-x", hitl=False, model_kwargs={"temperature": 0}) + graph_module.Graph(api_key="k", model="gpt-x", db_engine=object(), hitl=False, model_kwargs={"temperature": 0}) assert chamadas == [("gpt-x", "k", {"temperature": 0})] @@ -224,7 +228,9 @@ def __init__(self, **kwargs): capturado.update(kwargs) monkeypatch.setattr(engine_module, "Graph", _FakeGraph) + from sqlalchemy import create_engine + engine_module.InsightEngine( - api_key="k", model="gpt-x", db_path="x.db", model_kwargs={"max_tokens": 10} + api_key="k", model="gpt-x", db_engine=create_engine("sqlite://"), model_kwargs={"max_tokens": 10} ) assert capturado["model_kwargs"] == {"max_tokens": 10} diff --git a/tests/test_nodes.py b/tests/test_nodes.py index defd25a..4becaa2 100644 --- a/tests/test_nodes.py +++ b/tests/test_nodes.py @@ -12,8 +12,8 @@ import sys import time import csv -import subprocess from pathlib import Path +from unittest.mock import MagicMock import pytest from dotenv import load_dotenv @@ -25,8 +25,14 @@ def _obter_schema_real() -> str: """Helper: extrai schema real do olist DB (sem API, só SQLite).""" + from tests.conftest import criar_engine_sqlite from text_to_insight.nodes.schema import nos_nodo_esquema - resultado = nos_nodo_esquema({"db_path": DB_PATH, "pergunta_atual": "teste"}) + + engine = criar_engine_sqlite(DB_PATH) + try: + resultado = nos_nodo_esquema({"pergunta_atual": "teste"}, engine=engine) + finally: + engine.dispose() return resultado["contexto_schema"] @@ -50,6 +56,40 @@ def test_planner_sem_schema(llm): assert resultado["status"] == "aguardando_schema" +@pytest.mark.parametrize( + ("erro", "status_esperado"), + [ + ("", "pronto_codificacao"), + ("no such column: users.name", "revisando_estrategia"), + ], +) +def test_planner_sem_hitl_decide_sem_llm(erro, status_esperado): + """Sem HITL, decide pelo erro e não chama o LLM nem consome tokens.""" + from text_to_insight.nodes.planner import nos_nodo_planejador + + mock_llm = MagicMock() + mock_llm.invoke.side_effect = AssertionError("LLM não deveria ser chamado") + + resultado = nos_nodo_planejador( + { + "pergunta_atual": "Quantos usuários existem?", + "contexto_schema": "Tabela: users\n- id: INTEGER", + "status": "exec_erro" if erro else "schema_obtido", + "erro_execucao": erro, + }, + llm=mock_llm, + hitl=False, + ) + + assert resultado["status"] == status_esperado + assert resultado["espera_humana"] is False + assert resultado["tokens_input"] == 0 + assert resultado["tokens_output"] == 0 + assert resultado["tokens_total"] == 0 + assert resultado["tokens_by_node"] == {} + mock_llm.invoke.assert_not_called() + + # ============================================================ # PLANNER — com API # ============================================================ @@ -179,16 +219,15 @@ def test_code_agent_com_feedback_regenera(llm): # EXECUTOR — com DB real (sem API) # ============================================================ -def test_executor_com_sql_real(): +def test_executor_com_sql_real(olist_engine): """Executor executa SQL gerada manualmente contra olist DB.""" from text_to_insight.nodes.sandbox import nos_nodo_sandbox estado = { "sql_gerada": "SELECT COUNT(*) as total_pedidos FROM orders", - "db_path": DB_PATH, "pergunta_atual": "Quantos pedidos existem?", } - resultado = nos_nodo_sandbox(estado) + resultado = nos_nodo_sandbox(estado, engine=olist_engine) assert resultado["status"] == "exec_ok" assert resultado["total_linhas_resultado"] >= 1 @@ -204,7 +243,7 @@ def test_executor_com_sql_real(): @pytest.mark.vcr @pytest.mark.timeout(90) -def test_cadeia_code_agent_executor(llm): +def test_cadeia_code_agent_executor(llm, olist_engine): """Code Agent gera SQL, Executor executa — testa a conexão entre os dois.""" from text_to_insight.nodes.code_agent.code_agent import nos_nodo_agente_codigo from text_to_insight.nodes.sandbox import nos_nodo_sandbox @@ -228,10 +267,9 @@ def test_cadeia_code_agent_executor(llm): # Passo 2: Executor executa a SQL gerada estado_exec = { "sql_gerada": resultado_code["sql_gerada"], - "db_path": DB_PATH, "pergunta_atual": "Quantos clientes existem no banco?", } - resultado_exec = nos_nodo_sandbox(estado_exec) + resultado_exec = nos_nodo_sandbox(estado_exec, engine=olist_engine) print(f" → Status execução: {resultado_exec['status']}") print(f" → Preview: {resultado_exec.get('linhas_resultado_preview', [])}") @@ -264,10 +302,10 @@ def test_extrair_codigo_python_sem_markdown(): def test_construir_script_inclui_csv_e_saida(): from text_to_insight.nodes import graph_generator as gg - # Validate that the script includes the CSV load, plotting code, and output path. - script = gg._construir_script("/tmp/dados.csv", "/tmp/saida.png", "plt.plot([1],[2])") - assert "pd.read_csv(\"/tmp/dados.csv\")" in script - assert "plt.savefig(\"/tmp/saida.png\"" in script + # Validate that the script includes the CSV load, plotting code. + script = gg._construir_script("plt.plot([1],[2])") + assert 'pd.read_csv("dados.csv")' in script + assert 'plt.savefig("grafico.png"' in script assert "plt.plot([1],[2])" in script assert "matplotlib.use('Agg')" in script @@ -410,77 +448,22 @@ def test_roteador_grafico_decisao_nao(): assert roteador_grafico(estado, llm) == "resposta" assert llm.called is True - -# ============================================================ -# GRAFICOS — executador de script (subprocesso) -# ============================================================ - -def test_executar_script_sucesso(): - from text_to_insight.nodes import graph_generator as gg - - # Minimal script that signals success via GRAPH_OK. - ok, saida = gg._executar_script("print('GRAPH_OK')") - assert ok is True - assert "GRAPH_OK" in saida - - -def test_executar_script_timeout(monkeypatch): - from text_to_insight.nodes import graph_generator as gg - - # Simulate a subprocess timeout to validate the error path. - def _fake_run(*args, **kwargs): - raise subprocess.TimeoutExpired(cmd=args[0], timeout=30) - - monkeypatch.setattr(gg.subprocess, "run", _fake_run) - ok, saida = gg._executar_script("print('GRAPH_OK')") - - assert ok is False - assert "Timeout" in saida - - -def test_executar_script_falha_retorno(monkeypatch): +def test_grafico_real_gera_png(tmp_path): from text_to_insight.nodes import graph_generator as gg - - # Simulate a non-zero return code and stderr output. - def _fake_run(*args, **kwargs): - return subprocess.CompletedProcess(args=args[0], returncode=1, stdout="", stderr="erro") - - monkeypatch.setattr(gg.subprocess, "run", _fake_run) - ok, saida = gg._executar_script("print('GRAPH_OK')") - - assert ok is False - assert "erro" in saida - - -def test_executar_script_limpa_temporario(monkeypatch, tmp_path): - from text_to_insight.nodes import graph_generator as gg - - temp_path = tmp_path / "temp_script.py" - - class _TempFile: - def __init__(self, path: Path): - self.name = str(path) - self._fh = open(self.name, "w", encoding="utf-8") - - def write(self, data: str) -> None: - self._fh.write(data) - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc, tb): - self._fh.close() - - def _fake_named_tempfile(*args, **kwargs): - # Use a deterministic temp path to verify cleanup. - return _TempFile(temp_path) - - def _fake_run(*args, **kwargs): - return subprocess.CompletedProcess(args=args[0], returncode=0, stdout="GRAPH_OK", stderr="") - - monkeypatch.setattr(gg.tempfile, "NamedTemporaryFile", _fake_named_tempfile) - monkeypatch.setattr(gg.subprocess, "run", _fake_run) - - ok, _ = gg._executar_script("print('GRAPH_OK')") - assert ok is True - assert temp_path.exists() is False + from text_to_insight.execucao_python import executar_python_isolado + + csv = tmp_path / "resultado da query.csv" + csv.write_text("x,y\n1,2\n2,4\n3,6\n", encoding="utf-8") + destino = tmp_path / "saida.png" + + script = gg._construir_script("plt.plot(df['x'], df['y'])") + resultado = executar_python_isolado( + script, + arquivos_entrada={gg.NOME_CSV: csv}, + arquivos_saida={gg.NOME_GRAFICO: destino}, + timeout_s=30, + ) + + assert resultado["ok"] is True, resultado["erro_execucao"] + assert destino.exists() + assert destino.read_bytes().startswith(b"\x89PNG") diff --git a/tests/test_spider2_eval.py b/tests/test_spider2_eval.py index 64a4e72..4648ae6 100644 --- a/tests/test_spider2_eval.py +++ b/tests/test_spider2_eval.py @@ -272,12 +272,10 @@ def test_dialect_and_criteria_filtering(mock_spider2_env: Path) -> None: # ============================================================================== def test_cli_argument_parsing_defaults(monkeypatch: pytest.MonkeyPatch) -> None: - """Verifies default values for CLI flags, ensuring schemacrawler defaults to off.""" + """Verifies default values for CLI flags.""" monkeypatch.setattr("sys.argv", ["test_spider2_eval.py"]) args = parse_arguments() - assert args.schemacrawler == "off" - assert args.no_schemacrawler is False assert args.infer_fks == "off" assert args.with_graphs == "off" assert args.rag == "on" @@ -301,7 +299,6 @@ def test_cli_argument_parsing_unified_flags(monkeypatch: pytest.MonkeyPatch) -> "test_spider2_eval.py", "--temperature", "0.2", "--max-tokens", "1024", - "--schemacrawler", "on", "--infer-fks", "--with-graphs", "--use-evidence", "off", @@ -313,7 +310,6 @@ def test_cli_argument_parsing_unified_flags(monkeypatch: pytest.MonkeyPatch) -> assert args.temperature == 0.2 assert args.max_tokens == 1024 - assert args.schemacrawler == "on" assert args.infer_fks == "on" assert args.with_graphs == "on" assert args.use_evidence == "off" @@ -329,11 +325,11 @@ def test_cli_argument_parsing_dialect_options(monkeypatch: pytest.MonkeyPatch) - assert args.dialect == dialect_val -def test_cli_argument_parsing_no_schemacrawler_alias(monkeypatch: pytest.MonkeyPatch) -> None: - """Verifies the --no-schemacrawler deprecated alias.""" - monkeypatch.setattr("sys.argv", ["test_spider2_eval.py", "--no-schemacrawler"]) - args = parse_arguments() - assert args.no_schemacrawler is True +def test_cli_argument_parsing_rejeita_schemacrawler(monkeypatch: pytest.MonkeyPatch) -> None: + """SchemaCrawler foi removido da biblioteca: a flag antiga não existe mais.""" + monkeypatch.setattr("sys.argv", ["test_spider2_eval.py", "--schemacrawler", "on"]) + with pytest.raises(SystemExit): + parse_arguments() def test_validate_api_key_env_valid() -> None: @@ -627,7 +623,6 @@ def test_spider_execution_logger_lifecycle(tmp_path: Path) -> None: "timeout": 30, "use_rag": True, "use_cot": True, - "schemacrawler": False, "with_graphs": False, "model_kwargs": {"temperature": 0.0, "api_key": "should_be_redacted"}, } @@ -641,7 +636,7 @@ def test_spider_execution_logger_lifecycle(tmp_path: Path) -> None: assert "Model: gpt-4o-mini" in content assert "Provider: openai" in content assert "Dialect: sqlite" in content - assert "SchemaCrawler: OFF" in content + assert "SchemaCrawler" not in content assert "should_be_redacted" not in content assert "***REDACTED***" in content diff --git a/tests/test_token_tracking.py b/tests/test_token_tracking.py index b2143a4..1bf9825 100644 --- a/tests/test_token_tracking.py +++ b/tests/test_token_tracking.py @@ -247,7 +247,7 @@ def test_planner_early_return_and_llm_call(): } -def test_rag_enrichment_batch_token_accumulation(): +def test_rag_enrichment_batch_token_accumulation(tmp_path): """Enrichment node processes batches and aggregates token usage across all batches.""" schema_6_tables = "\n".join([f"Tabela: table_{i}\n- col_{i}: int" for i in range(6)]) mock_llm = MagicMock() @@ -267,9 +267,9 @@ def test_rag_enrichment_batch_token_accumulation(): ] res = nos_nodo_enrich( - {"contexto_schema": schema_6_tables, "db_url": "sqlite://"}, + {"contexto_schema": schema_6_tables}, llm=mock_llm, - engine=object(), # prevents disk cache write + cache_dir=tmp_path, ) assert res["tem_descricao"] is True @@ -360,12 +360,14 @@ def test_code_agent_and_sandbox_attempt_tracking(tmp_path): conn.close() # Sandbox execution with success + from tests.conftest import criar_engine_sqlite + + db_engine = criar_engine_sqlite(str(db_file)) sandbox_input = { **estado, **code_res, - "db_path": str(db_file), } - sandbox_res = nos_nodo_sandbox(sandbox_input) + sandbox_res = nos_nodo_sandbox(sandbox_input, engine=db_engine) assert sandbox_res["status"] == "exec_ok" assert len(sandbox_res["historico_tentativas"]) == 1 attempt = sandbox_res["historico_tentativas"][0] @@ -379,7 +381,8 @@ def test_code_agent_and_sandbox_attempt_tracking(tmp_path): **sandbox_input, "sql_gerada": "SELECT * FROM nonexistent_table;", } - sandbox_err_res = nos_nodo_sandbox(sandbox_input_err) + sandbox_err_res = nos_nodo_sandbox(sandbox_input_err, engine=db_engine) + db_engine.dispose() assert sandbox_err_res["status"] == "exec_erro" err_attempt = sandbox_err_res["historico_tentativas"][0] assert err_attempt["tokens_input"] == 150 @@ -414,7 +417,7 @@ def test_graph_router_token_sink_and_graph_adapter(monkeypatch): "text_to_insight.graph.get_model", lambda *args, **kwargs: mock_llm, ) - g = Graph(api_key="mock", model="gemini-2.0-flash", enable_graphs=True) + g = Graph(api_key="mock", model="gemini-2.0-flash", db_engine=object(), enable_graphs=True) compiled_nodes = g.grafo_text_to_insight.get_graph().nodes assert "graph_router" in compiled_nodes @@ -432,18 +435,20 @@ def test_graph_generator_tokens(monkeypatch, tmp_path): dummy_csv = tmp_path / "data.csv" dummy_csv.write_text("a,b\n1,2\n", encoding="utf-8") - dummy_png = tmp_path / "graph.png" - dummy_png.write_text("png", encoding="utf-8") - mock_llm = MagicMock() mock_llm.invoke.return_value = AIMessage( content="```python\nimport matplotlib.pyplot as plt\nplt.plot([1, 2])\n```", usage_metadata={"input_tokens": 60, "output_tokens": 30, "total_tokens": 90}, ) + def fake_executar_python(script, *, arquivos_entrada, arquivos_saida, timeout_s): + for destino in arquivos_saida.values(): + destino.write_bytes(b"png") + return {"ok": True, "erro_execucao": ""} + monkeypatch.setattr( - "text_to_insight.nodes.graph_generator._executar_script", - lambda script: (True, "OK"), + "text_to_insight.nodes.graph_generator.executar_python_isolado", + fake_executar_python, ) monkeypatch.setattr( "text_to_insight.nodes.graph_generator.GRAPHS_DIR", @@ -458,10 +463,6 @@ def test_graph_generator_tokens(monkeypatch, tmp_path): "total_linhas_resultado": 10, } - # Mock Path.exists to report output_path exists - orig_exists = tmp_path.exists - monkeypatch.setattr("pathlib.Path.exists", lambda self: True) - res = nos_nodo_gerador_grafico(estado, llm=mock_llm) assert res["grafico_gerado"] is True assert res["tokens_by_node"] == { diff --git a/text_to_insight/InsightEngine.py b/text_to_insight/InsightEngine.py index c6bde06..84a0c08 100644 --- a/text_to_insight/InsightEngine.py +++ b/text_to_insight/InsightEngine.py @@ -1,5 +1,6 @@ from __future__ import annotations +from pathlib import Path from typing import Any, Callable from .graph import Graph @@ -20,7 +21,7 @@ def __init__( self, api_key: str, model: str, - db_path: str, + db_engine: Any, hitl: bool = False, show_output: bool = False, enable_graphs: bool = True, @@ -30,19 +31,26 @@ def __init__( use_rag: bool = True, enrich_rag: bool = False, inferir_fks_virtuais: bool = False, - usar_schemacrawler: bool = False, - db_url: str = "", model_kwargs: dict | None = None, - db_engine: Any = None, + cache_dir: str | Path | None = None, ): """ - `db_engine`, se informado, deve ser uma Engine do SQLAlchemy já - construída pelo chamador (que também é responsável por descartá-la - com `.dispose()` quando terminar). Quando presente, tem prioridade - sobre `db_url`/`db_path`: a engine nunca é - copiada para o estado do grafo — evita credenciais em texto puro no - checkpoint do LangGraph — e o dialeto é lido diretamente dela. + `db_engine` é uma Engine do SQLAlchemy construída pelo chamador, que + também é responsável por descartá-la com `.dispose()` quando + terminar. A biblioteca nunca abre conexões por conta própria: todo + acesso ao banco passa por essa engine. Ela nunca é copiada para o + estado do grafo (nada sobre a conexão vai para o checkpoint do + LangGraph) e o dialeto é lido diretamente dela. + + `cache_dir` é a pasta onde ficam o schema enriquecido (enrich_rag) e + o índice do ChromaDB. Se omitida, usa a pasta de cache do usuário + (ex.: `~/.cache/text-to-insight` no Linux). """ + if db_engine is None or not hasattr(db_engine, "dialect"): + raise TypeError( + "`db_engine` deve ser uma Engine do SQLAlchemy, ex.: " + "create_engine(\"sqlite:///meu_banco.db\")." + ) self._hitl_ativado = hitl # `show_output` controla se a engine imprime o resultado final no terminal. # Em cenários com CLI, normalmente deixamos False para evitar saída duplicada. @@ -50,13 +58,11 @@ def __init__( self._enable_graphs = enable_graphs self._enrich_rag = enrich_rag self._inferir_fks_virtuais = inferir_fks_virtuais - self._usar_schemacrawler = usar_schemacrawler - self._db_url = db_url self._db_engine = db_engine + self._cache_dir = cache_dir self._model = model # Parâmetros repassados ao construtor do LLM (ex.: temperature, max_tokens). self._model_kwargs = dict(model_kwargs or {}) - self._db_path = db_path self._use_cot = use_cot self._use_data_exploration = use_data_exploration self._use_exploration_selector = use_exploration_selector @@ -74,6 +80,7 @@ def __init__( enrich_rag=self._enrich_rag, model_kwargs=self._model_kwargs, db_engine=self._db_engine, + cache_dir=self._cache_dir, ) print(f"[CONFIG] HITL: {'ATIVADO' if self._hitl_ativado else 'DESATIVADO'}") @@ -85,7 +92,7 @@ def __init__( print(f"[CONFIG] RAG: {'ATIVADO' if self._use_rag else 'DESATIVADO'}") print(f"[CONFIG] ENRICH-RAG: {'ATIVADO' if self._enrich_rag else 'DESATIVADO'}") print(f"[CONFIG] INFERIR-FKS-VIRTUAIS: {'ATIVADO' if self._inferir_fks_virtuais else 'DESATIVADO'}") - print(f"[CONFIG] USAR-SCHEMACRAWLER: {'ATIVADO' if self._usar_schemacrawler else 'DESATIVADO'}") + print(f"[CONFIG] BANCO: {self._db_engine.dialect.name}") print(f"[CONFIG] MODEL_KWARGS: {self._model_kwargs or 'PADRÃO DO PROVEDOR'}") def _config(self, thread_id: str) -> dict[str, Any]: @@ -163,10 +170,7 @@ def get_insight( ) # Caso 2: chamada nova (primeira execução para essa pergunta). elif query: - estado_execucao = construir_estado_inicial( - query, self._db_path, self._inferir_fks_virtuais, self._usar_schemacrawler, - db_url=self._db_url, - ) + estado_execucao = construir_estado_inicial(query, self._inferir_fks_virtuais) pergunta_exibicao = query # Caso 3: a thread já está pausada, mas ainda sem resposta do usuário. elif snapshot.next: diff --git a/text_to_insight/cache.py b/text_to_insight/cache.py new file mode 100644 index 0000000..752822b --- /dev/null +++ b/text_to_insight/cache.py @@ -0,0 +1,62 @@ +""" +Onde a biblioteca guarda arquivos que sobrevivem entre execuções. + +Tudo fica numa pasta de cache por usuário (via `platformdirs`, ex.: +`~/Library/Caches/text-to-insight` no macOS, `~/.cache/text-to-insight` no +Linux), nunca dentro da pasta do pacote instalado (que pode não ter permissão +de escrita) nem ao lado do banco do usuário. Quem usa a biblioteca pode +escolher outra pasta com `InsightEngine(cache_dir=...)`. + +Conteúdo da pasta: +- `schemas/_enriched.txt`: schema enriquecido pelo LLM (enrich_rag), + indexado pelo hash do texto do schema. Funciona para qualquer banco, e um + schema que mudou gera um hash novo (o cache antigo simplesmente deixa de + ser usado). +- `chroma_db/`: índice vetorial do ChromaDB usado pelo RAG e pelo seletor + de colunas. +""" +from __future__ import annotations + +import hashlib +from pathlib import Path + +from platformdirs import user_cache_dir + +NOME_APP = "text-to-insight" + + +def resolver_cache_dir(cache_dir: str | Path | None = None) -> Path: + """Pasta de cache escolhida pelo chamador, ou a pasta padrão do usuário.""" + return Path(cache_dir) if cache_dir else Path(user_cache_dir(NOME_APP)) + + +def caminho_schema_enriquecido(cache_dir: str | Path | None, contexto_schema: str) -> Path: + """Arquivo de cache do schema enriquecido correspondente a `contexto_schema`.""" + hash_schema = hashlib.sha256(contexto_schema.encode("utf-8")).hexdigest()[:32] + return resolver_cache_dir(cache_dir) / "schemas" / f"{hash_schema}_enriched.txt" + + +def ler_schema_enriquecido(cache_dir: str | Path | None, contexto_schema: str) -> str | None: + """Devolve o schema enriquecido em cache para este schema, se existir.""" + caminho = caminho_schema_enriquecido(cache_dir, contexto_schema) + try: + return caminho.read_text(encoding="utf-8") + except (FileNotFoundError, OSError): + return None + + +def salvar_schema_enriquecido(cache_dir: str | Path | None, contexto_schema: str, enriquecido: str) -> Path | None: + """Grava o schema enriquecido. Falha de escrita só desativa o cache, não a execução.""" + caminho = caminho_schema_enriquecido(cache_dir, contexto_schema) + try: + caminho.parent.mkdir(parents=True, exist_ok=True) + caminho.write_text(enriquecido, encoding="utf-8") + except OSError as e: + print(f"[CACHE] Não foi possível gravar o schema enriquecido em {caminho}: {e}") + return None + return caminho + + +def diretorio_chroma(cache_dir: str | Path | None = None) -> Path: + """Pasta do ChromaDB persistente (RAG e seletor de colunas).""" + return resolver_cache_dir(cache_dir) / "chroma_db" diff --git a/text_to_insight/cli.py b/text_to_insight/cli.py index 073bdfb..0f090ba 100644 --- a/text_to_insight/cli.py +++ b/text_to_insight/cli.py @@ -39,9 +39,50 @@ def _montar_model_kwargs(args: argparse.Namespace) -> dict[str, Any]: return {chave: valor for chave, valor in candidatos.items() if valor is not None} +def _normalizar_db_url(db_url: str) -> str: + """ + "postgresql://" e "mysql://" sem driver explícito usam os drivers dos + extras do pacote (psycopg2 e pymysql). Sem isso, o SQLAlchemy tenta o + driver padrão dele (ex: psycopg v3), que pode não estar instalado. + """ + if db_url.startswith("postgresql://"): + return "postgresql+psycopg2://" + db_url[len("postgresql://"):] + if db_url.startswith("mysql://"): + return "mysql+pymysql://" + db_url[len("mysql://"):] + return db_url + + +def _criar_engine(db_path: str | None, db_url: str | None, timeout_segundos: int = 15): + """ + Cria a Engine SQLAlchemy que o CLI passa para a InsightEngine. + + A biblioteca não abre conexões; quem abre é o chamador, e aqui o + chamador é o CLI. `--db-url` tem prioridade sobre `--db-path`. Um + arquivo SQLite é aberto em modo somente leitura. + """ + from sqlalchemy import create_engine + from sqlalchemy.engine import make_url + + if db_url: + dialeto = make_url(db_url).get_backend_name() + connect_args: dict[str, Any] = {} + if dialeto == "postgresql": + connect_args = {"connect_timeout": timeout_segundos} + elif dialeto == "mysql": + connect_args = {"connect_timeout": timeout_segundos, "read_timeout": timeout_segundos} + return create_engine(_normalizar_db_url(db_url), connect_args=connect_args) + + if not db_path: + raise SystemExit("Informe o banco com --db-path (arquivo SQLite) ou --db-url / DATABASE_URL.") + caminho = Path(db_path).expanduser().resolve() + if not caminho.exists(): + raise SystemExit(f"Arquivo de banco não encontrado: {caminho}") + return create_engine(f"sqlite:///file:{caminho}?mode=ro&uri=true") + + def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser( - description="Executa o pipeline Text-to-Insight para responder perguntas sobre o banco SQLite." + description="Executa o pipeline Text-to-Insight para responder perguntas sobre um banco de dados." ) parser.add_argument( "--hitl", @@ -61,12 +102,6 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: default="off", help="Ativa/desativa a inferência virtual de chaves estrangeiras. Padrão: off.", ) - parser.add_argument( - "--use-schemacrawler", - choices=["on", "off"], - default="off", - help="Ativa/desativa o uso do SchemaCrawler. Se off, usa PRAGMA SQLite. Padrão: off.", - ) parser.add_argument( "--thread-id", default="sessao_usuario_1", @@ -74,16 +109,17 @@ def _parse_args(argv: list[str] | None = None) -> argparse.Namespace: ) parser.add_argument( "--db-path", - default="data/olist_relational.db", - help="Caminho para o banco SQLite.", + default=None, + help="Caminho para um arquivo SQLite (aberto somente leitura).", ) parser.add_argument( "--db-url", default=os.getenv("DATABASE_URL"), help=( "URL unica de conexao (ex: postgresql://usuario:senha@host:5432/banco). " - "Se informado, o dialeto e detectado automaticamente pelo SQLAlchemy. " - "Tambem pode vir da variavel de ambiente DATABASE_URL." + "Tem prioridade sobre --db-path. Tambem pode vir da variavel de " + "ambiente DATABASE_URL. PostgreSQL e MySQL exigem os extras " + "text-to-insight[postgres] / text-to-insight[mysql]." ), ) parser.add_argument( @@ -155,7 +191,6 @@ def main(argv: list[str] | None = None) -> dict[str, Any]: print(f"[CONFIG] HITL: {'ATIVADO' if hitl_ativado else 'DESATIVADO'}") enrich_rag_ativado = args.enrich_rag == "on" inferir_fks_ativado = args.infer_fks == "on" - use_schemacrawler_ativado = args.use_schemacrawler == "on" api_key = os.getenv(args.api_key_env) if not api_key: @@ -164,23 +199,16 @@ def main(argv: list[str] | None = None) -> dict[str, Any]: "Configure a chave da API antes de executar." ) - # Se --db-url foi informado, o CLI constrói e é dono da Engine SQLAlchemy - # (inclusive do dispose() no final) e a repassa pronta para a InsightEngine, - # em vez de deixar a credencial/URL crua viajar dentro do estado do grafo. - db_engine = None - if args.db_url: - from text_to_insight.nodes.code_agent.code_sql import _criar_engine_de_url - - db_engine = _criar_engine_de_url(db_url=args.db_url) + # O CLI constrói e é dono da Engine SQLAlchemy (inclusive do dispose() no + # final) e a repassa pronta para a InsightEngine. + db_engine = _criar_engine(args.db_path, args.db_url) engine = InsightEngine( api_key=api_key, model=args.model, - db_path=args.db_path, db_engine=db_engine, hitl=hitl_ativado, enrich_rag=enrich_rag_ativado, inferir_fks_virtuais=inferir_fks_ativado, - usar_schemacrawler=use_schemacrawler_ativado, show_output=False, use_cot=cot_ativado, use_data_exploration=data_exploration_ativado, @@ -207,8 +235,7 @@ def main(argv: list[str] | None = None) -> dict[str, Any]: return resultado finally: # Quem criou a engine (o CLI, neste caso) é quem a descarta. - if db_engine is not None: - db_engine.dispose() + db_engine.dispose() if __name__ == "__main__": diff --git a/text_to_insight/execucao_python.py b/text_to_insight/execucao_python.py new file mode 100644 index 0000000..9215029 --- /dev/null +++ b/text_to_insight/execucao_python.py @@ -0,0 +1,83 @@ +""" + +Executar isoladamente scripts de python gerados pela biblioteca + +O script roda num subprocesso dentro de uma pasta temporária e própria +A devolução do resultado continua seguindo o padrão de formato do executor + +""" +from __future__ import annotations + +import os +import subprocess +import sys +import tempfile +import shutil +from pathlib import Path +from typing import Any + +NOME_SCRIPT = "script.py" + + +def _resultado(ok: bool, erro: str, saida: str) -> dict[str, Any]: + """Monta dicionário de retorno""" + return {"ok": ok, "erro_execucao": erro, "saida_terminal": saida} + +def _ambiente_minimo(pasta: Path) -> dict[str, str]: + """ + Monta do zero as variáveis de ambiente do processo filho (allowlist). + Nada do ambiente do processo pai é herdado além do que está aqui. + """ + ambiente = { + "PATH": os.environ.get("PATH", ""), + "MPLCONFIGDIR": str(pasta), + } + if os.name == "nt": + # Pelo que sabemos, o Python no Windows pode falhar ao iniciar sem + # SYSTEMROOT. Não testado em Windows. + ambiente["SYSTEMROOT"] = os.environ.get("SYSTEMROOT", "") + return ambiente + +def executar_python_isolado( + script: str, + arquivos_entrada: dict[str, Path] | None = None, + arquivos_saida: dict[str, Path] | None = None, + timeout_s: float = 30.0 + ) -> dict[str, Any]: + """ + Executa `script` num subprocesso, com uma pasta temporária como + diretório de trabalho. A pasta é apagada ao final. + """ + if arquivos_entrada is None: + arquivos_entrada = {} + if arquivos_saida is None: + arquivos_saida = {} + with tempfile.TemporaryDirectory(prefix="t2i_exec_") as pasta_str: + pasta = Path(pasta_str) + (pasta / NOME_SCRIPT).write_text(script, encoding="utf-8") + for nome, origem in arquivos_entrada.items(): + shutil.copy(origem, pasta / nome) + try: + processo = subprocess.run( + [sys.executable, NOME_SCRIPT], + cwd=pasta, + env = _ambiente_minimo(pasta), + capture_output=True, + text=True, + timeout=timeout_s, + ) + except subprocess.TimeoutExpired: + return _resultado(False, f"Timeout: o script excedeu o limite de {timeout_s}s", "") + + stdout = processo.stdout.strip() + stderr = processo.stderr.strip() + + if processo.returncode != 0: + erro = stderr or stdout or f"Processo terminou com código {processo.returncode}." + return _resultado(False, erro, stdout) + for nome, destino in arquivos_saida.items(): + if((pasta / nome).exists() != True): + return _resultado(False, f"O script não gerou o arquivo {nome} esperado", stdout) + destino.parent.mkdir(parents = True, exist_ok = True) + shutil.copy(pasta / nome, destino) + return _resultado(True, "", stdout) \ No newline at end of file diff --git a/text_to_insight/graph.py b/text_to_insight/graph.py index 9e6e3aa..6185ab1 100644 --- a/text_to_insight/graph.py +++ b/text_to_insight/graph.py @@ -3,7 +3,7 @@ Fluxo MVP: 1. Planejador: Decide estratégia (LLM) -2. Esquema: Obtém contexto do banco (SQLite introspection) +2. Esquema: Obtém contexto do banco (introspecção via SQLAlchemy) 3. Agente de Código: Gera SQL (LLM) 4. Executor: Executa SQL no banco real 5. Salvar CSV: Exporta resultado para CSV @@ -40,7 +40,7 @@ def nos_nodo_espera_humana(estado: EstadoTextToInsight): return estado class Graph: - def __init__(self, api_key: str, model: str, hitl: bool = True, enable_graphs: bool = True, use_cot: bool = True, use_data_exploration: bool = True, use_exploration_selector: str = "off", use_rag: bool = True, enrich_rag: bool = False, model_kwargs: dict | None = None, db_engine=None): + def __init__(self, api_key: str, model: str, db_engine, hitl: bool = True, enable_graphs: bool = True, use_cot: bool = True, use_data_exploration: bool = True, use_exploration_selector: str = "off", use_rag: bool = True, enrich_rag: bool = False, model_kwargs: dict | None = None, cache_dir=None): self.llm = get_model(model, api_key, **(model_kwargs or {})) self.memory = MemorySaver() self.enable_graphs = enable_graphs @@ -49,11 +49,13 @@ def __init__(self, api_key: str, model: str, hitl: bool = True, enable_graphs: b self.use_exploration_selector = use_exploration_selector self.use_rag = use_rag self.enrich_rag = enrich_rag - # Engine SQLAlchemy opcional, injetada pelo chamador (dono do ciclo de - # vida da conexao). Nunca entra no estado do grafo: e passada via - # closure/partial diretamente para os nos que precisam dela, então - # nunca e persistida pelo checkpointer (MemorySaver). + # Engine SQLAlchemy injetada pelo chamador (dono do ciclo de vida da + # conexao). Nunca entra no estado do grafo: e passada via partial + # diretamente para os nos que precisam dela, então nunca e persistida + # pelo checkpointer (MemorySaver). self.db_engine = db_engine + # Pasta de cache (schema enriquecido e ChromaDB); None = padrão do usuário. + self.cache_dir = cache_dir self.grafo_text_to_insight = self._compilar_grafo(hitl, enrich_rag) def _construir_grafo_text_to_insight(self, hitl: bool, enrich_rag: bool) -> StateGraph: @@ -62,22 +64,18 @@ def _construir_grafo_text_to_insight(self, hitl: bool, enrich_rag: bool) -> Stat """ construtor_grafo = StateGraph(EstadoTextToInsight) - # Só passamos `engine=...` para os nós que aceitam esse kwarg quando o - # chamador de fato injetou uma Engine SQLAlchemy. Isso mantém - # compatibilidade com testes/mocks que substituem esses nós por - # funções fake sem esse parâmetro, e evita amarrar todo mundo à nova - # API quando ninguém está usando `db_engine`. - engine_kwargs = {"engine": self.db_engine} if self.db_engine is not None else {} + engine = self.db_engine + cache_dir = self.cache_dir # 1. ADICIONAR NÓS construtor_grafo.add_node("planejador", partial(nos_nodo_planejador, llm=self.llm, hitl=hitl)) construtor_grafo.add_node("espera_humana", nos_nodo_espera_humana) - construtor_grafo.add_node("esquema", partial(nos_nodo_esquema, **engine_kwargs)) - construtor_grafo.add_node("retriever", partial(nos_nodo_retriever, use_rag=self.use_rag)) - construtor_grafo.add_node("exploration_selector", partial(nos_nodo_exploration_selector, llm=self.llm, exploration_selector_mode=self.use_exploration_selector)) - construtor_grafo.add_node("data_exploration", partial(nos_nodo_data_exploration, use_data_exploration=self.use_data_exploration, **engine_kwargs)) - construtor_grafo.add_node("agente_codigo", partial(nos_nodo_agente_codigo, llm=self.llm, use_cot=self.use_cot, **engine_kwargs)) - construtor_grafo.add_node("sandbox", partial(nos_nodo_sandbox, **engine_kwargs)) + construtor_grafo.add_node("esquema", partial(nos_nodo_esquema, engine=engine, enrich_rag=enrich_rag, cache_dir=cache_dir)) + construtor_grafo.add_node("retriever", partial(nos_nodo_retriever, use_rag=self.use_rag, cache_dir=cache_dir)) + construtor_grafo.add_node("exploration_selector", partial(nos_nodo_exploration_selector, llm=self.llm, exploration_selector_mode=self.use_exploration_selector, cache_dir=cache_dir)) + construtor_grafo.add_node("data_exploration", partial(nos_nodo_data_exploration, engine=engine, use_data_exploration=self.use_data_exploration)) + construtor_grafo.add_node("agente_codigo", partial(nos_nodo_agente_codigo, llm=self.llm, use_cot=self.use_cot, engine=engine)) + construtor_grafo.add_node("sandbox", partial(nos_nodo_sandbox, engine=engine)) construtor_grafo.add_node("salvar_csv", nos_nodo_salvar_csv) construtor_grafo.add_node("gerador_grafico", partial(nos_nodo_gerador_grafico, llm=self.llm)) construtor_grafo.add_node("resposta", partial(nos_nodo_resposta, llm=self.llm)) @@ -87,7 +85,7 @@ def _construir_grafo_text_to_insight(self, hitl: bool, enrich_rag: bool) -> Stat construtor_grafo.add_edge("espera_humana", "planejador") path = 'retriever' if enrich_rag: - construtor_grafo.add_node("enriquecimento_rag", partial(nos_nodo_enrich, llm=self.llm, **engine_kwargs)) + construtor_grafo.add_node("enriquecimento_rag", partial(nos_nodo_enrich, llm=self.llm, cache_dir=cache_dir)) construtor_grafo.add_edge("enriquecimento_rag", "retriever") path = 'enriquecimento_rag' diff --git a/text_to_insight/nodes/code_agent/code_agent.py b/text_to_insight/nodes/code_agent/code_agent.py index 6762b30..b1c95f8 100644 --- a/text_to_insight/nodes/code_agent/code_agent.py +++ b/text_to_insight/nodes/code_agent/code_agent.py @@ -41,33 +41,13 @@ } -def _resolver_info_dialeto(estado: EstadoTextToInsight, engine=None) -> tuple[str, str]: - """Resolve (nome_exibicao, nota_sintaxe) do dialeto configurado no estado. - - Ordem de resolução: - 1. `engine.dialect.name`, se uma Engine SQLAlchemy foi injetada pelo - chamador (caso mais confiável: vem direto da conexão, sem adivinhar). - 2. `db_url`, cujo dialeto é lido do prefixo da URL (sem conectar). - 3. 'sqlite' como default, preservando o comportamento anterior quando - nada é informado (compatibilidade retroativa). +def _resolver_info_dialeto(engine=None) -> tuple[str, str]: + """Resolve (nome_exibicao, nota_sintaxe) do dialeto da Engine injetada. + + O dialeto vem de `engine.dialect.name`. Sem engine (ex.: testes que + chamam o nó isolado), usa SQLite como padrão. """ - if engine is not None: - dialeto = engine.dialect.name - nome = _NOME_DIALETO.get(dialeto, _NOME_DIALETO["sqlite"]) - nota = _NOTA_DIALETO.get(dialeto, _NOTA_DIALETO["sqlite"]) - return nome, nota - - dialeto = "" - db_url = (estado.get("db_url") or "").strip() - if db_url: - try: - from sqlalchemy.engine import make_url - - dialeto = make_url(db_url).get_backend_name() - except Exception: - dialeto = "" - - dialeto = dialeto or "sqlite" + dialeto = engine.dialect.name if engine is not None else "sqlite" nome = _NOME_DIALETO.get(dialeto, _NOME_DIALETO["sqlite"]) nota = _NOTA_DIALETO.get(dialeto, _NOTA_DIALETO["sqlite"]) return nome, nota @@ -173,9 +153,9 @@ def nos_nodo_agente_codigo(estado: EstadoTextToInsight, llm: BaseChatModel, use_ """ Nó Agente de Código: usa Gemini para gerar SQL a partir da pergunta + schema. - `engine`, se informado, é a Engine SQLAlchemy injetada pelo chamador — - usada apenas para resolver o dialeto (via `engine.dialect.name`) e ajustar - a sintaxe do prompt, sem depender de `db_url` no estado. + `engine` é a Engine SQLAlchemy injetada pelo chamador — usada apenas + para resolver o dialeto (via `engine.dialect.name`) e ajustar a sintaxe + do prompt. """ pergunta = ( estado.get("pergunta_atual", "") @@ -192,7 +172,7 @@ def nos_nodo_agente_codigo(estado: EstadoTextToInsight, llm: BaseChatModel, use_ print(f"[AGENTE_CODIGO] Gerando SQL (tentativa {tentativas + 1})...") historico_section = _formatar_historico_tentativas(historico) - dialeto_nome, nota_dialeto = _resolver_info_dialeto(estado, engine=engine) + dialeto_nome, nota_dialeto = _resolver_info_dialeto(engine) template = PROMPT_TEMPLATE_COT if use_cot else PROMPT_TEMPLATE_NO_COT diff --git a/text_to_insight/nodes/code_agent/code_sql.py b/text_to_insight/nodes/code_agent/code_sql.py index 9c204c6..dc6e077 100644 --- a/text_to_insight/nodes/code_agent/code_sql.py +++ b/text_to_insight/nodes/code_agent/code_sql.py @@ -8,8 +8,7 @@ from __future__ import annotations import re -import sqlite3 -from pathlib import Path +import time from typing import Any # Expressão regular para detectar comandos SQL potencialmente perigosos. @@ -76,99 +75,6 @@ def validar_sql_segura(sql: str) -> tuple[bool, str]: return True, "" -import time - -def executar_sql_sqlite( - db_path: str, - sql: str, - limite_preview: int = 5, - timeout_segundos: float = 15.0, -) -> dict[str, Any]: - """ - Executa SQL validada em SQLite modo read-only e retorna resultado estruturado. - Possui um timeout embutido para evitar queries infinitas (ex: cross joins enormes). - """ - ok, erro_validacao = validar_sql_segura(sql) - if not ok: - return { - "ok": False, - "erro_execucao": erro_validacao, - "linhas_resultado_preview": [], - "linhas_resultado_completo": [], - "total_linhas_resultado": 0, - "saida_terminal": f"[SANDBOX] SQL invalida: {erro_validacao}", - } - - caminho = Path(db_path) - if not caminho.exists(): - msg = f"Arquivo de banco nao encontrado: {db_path}" - return { - "ok": False, - "erro_execucao": msg, - "linhas_resultado_preview": [], - "linhas_resultado_completo": [], - "total_linhas_resultado": 0, - "saida_terminal": f"[SANDBOX] {msg}", - } - - try: - conn = sqlite3.connect(f"file:{caminho}?mode=ro", uri=True) - conn.row_factory = sqlite3.Row - - # Define um handler para monitorar o tempo de execução e abortar se passar do limite - start_time = time.time() - def _progress_handler(): - if time.time() - start_time > timeout_segundos: - return 1 # abortar query - return 0 - - # Invoca a cada 1000 instruções da máquina virtual do SQLite - conn.set_progress_handler(_progress_handler, 1000) - - try: - cur = conn.cursor() - cur.execute(sql) - rows = cur.fetchall() - total = len(rows) - preview_rows = [dict(r) for r in rows[:limite_preview]] - all_rows = [dict(r) for r in rows] - - return { - "ok": True, - "erro_execucao": "", - "linhas_resultado_preview": preview_rows, - "linhas_resultado_completo": all_rows, - "total_linhas_resultado": total, - "saida_terminal": ( - f"[SANDBOX] Execucao OK | linhas_total={total} " - f"| preview={min(total, limite_preview)}" - ), - } - finally: - conn.close() - except sqlite3.OperationalError as e: - erro_msg = str(e) - if "interrupted" in erro_msg.lower(): - erro_msg = f"Query abortada por timeout (> {timeout_segundos}s)." - return { - "ok": False, - "erro_execucao": f"Falha ao executar SQL: {erro_msg}", - "linhas_resultado_preview": [], - "linhas_resultado_completo": [], - "total_linhas_resultado": 0, - "saida_terminal": f"[SANDBOX] Erro de execucao: {erro_msg}", - } - except Exception as e: - return { - "ok": False, - "erro_execucao": f"Falha ao executar SQL: {e}", - "linhas_resultado_preview": [], - "linhas_resultado_completo": [], - "total_linhas_resultado": 0, - "saida_terminal": f"[SANDBOX] Erro de execucao: {e}", - } - - def _erro_execucao(msg: str) -> dict[str, Any]: """Monta a estrutura de retorno padrao para uma falha de execucao.""" return { @@ -181,35 +87,6 @@ def _erro_execucao(msg: str) -> dict[str, Any]: } -def _normalizar_db_url(db_url: str) -> str: - """ - Garante que "postgresql://" e "mysql://" sem driver explicito usem os - drivers que este projeto de fato instala (psycopg2 e pymysql). Sem isso, - o SQLAlchemy tenta o driver padrao dele (ex: psycopg v3 para postgres), - que nao esta instalado aqui, e a conexao falha com "No module named ...". - """ - if db_url.startswith("postgresql://"): - return "postgresql+psycopg2://" + db_url[len("postgresql://"):] - if db_url.startswith("mysql://"): - return "mysql+pymysql://" + db_url[len("mysql://"):] - return db_url - -def _criar_engine_de_url(db_url: str, timeout_segundos=15.0): - """ Cria uma engine com timeout de conexão pra evitar problema de - runtime com URL""" - from sqlalchemy import create_engine - from sqlalchemy.engine import make_url - url =_normalizar_db_url(db_url=db_url) - dialeto = make_url(db_url).get_backend_name() - segundos = max(1, int(timeout_segundos)) - connect_args = {} - if dialeto == "postgresql": - connect_args = {"connect_timeout": segundos} - elif dialeto == "mysql": - connect_args = {"connect_timeout": segundos, "read_timeout": segundos} - return create_engine(url, connect_args=connect_args) - - def executar_sql_via_engine( engine: Any, sql: str, @@ -218,12 +95,10 @@ def executar_sql_via_engine( ) -> dict[str, Any]: """ Executa SQL usando uma Engine SQLAlchemy ja construida pelo chamador - (o dialeto e lido de `engine.dialect.name`, sem precisar de - `db_url` no estado do grafo). + (o dialeto e lido de `engine.dialect.name`). - Ao contrario de `executar_sql_via_url`, esta funcao NAO cria nem - descarta (`dispose`) a engine: o ciclo de vida da conexao e - responsabilidade de quem a construiu, nao desta biblioteca. + Esta funcao NAO cria nem descarta (`dispose`) a engine: o ciclo de vida + da conexao e responsabilidade de quem a construiu, nao desta biblioteca. """ ok, erro_validacao = validar_sql_segura(sql) if not ok: @@ -261,7 +136,10 @@ def _progress_handler(): dbapi_conn.set_progress_handler(_progress_handler, 1000) - resultado = conn.execute(text(sql)) + # exec_driver_sql manda a SQL direto ao driver; text() trataria + # ":palavra" dentro de literais como parâmetro de bind. + #resultado = conn.exec_driver_sql(sql) + resultado = conn.execution_options(no_parameters=True).exec_driver_sql(sql) rows = [dict(linha) for linha in resultado.mappings().all()] finally: if dbapi_conn is not None: @@ -289,28 +167,3 @@ def _progress_handler(): ), } - -def executar_sql_via_url( - db_url: str, - sql: str, - limite_preview: int = 5, - timeout_segundos: float = 15.0, -) -> dict[str, Any]: - """ - Executa SQL usando uma unica URL de conexao (SQLAlchemy detecta o - dialeto sozinho a partir do prefixo da URL: sqlite:///, postgresql://, - mysql+pymysql://, etc). - - Cria e descarta a engine internamente. Se o chamador ja possui uma - Engine (e quer controlar seu ciclo de vida/pool), use - `executar_sql_via_engine` em vez desta funcao. - """ - try: - engine = _criar_engine_de_url(db_url, timeout_segundos) - except Exception as e: - return _erro_execucao(f"URL de conexao invalida: {e}") - - try: - return executar_sql_via_engine(engine, sql, limite_preview, timeout_segundos) - finally: - engine.dispose() \ No newline at end of file diff --git a/text_to_insight/nodes/data_exploration.py b/text_to_insight/nodes/data_exploration.py index 3f89952..94f10ec 100644 --- a/text_to_insight/nodes/data_exploration.py +++ b/text_to_insight/nodes/data_exploration.py @@ -12,15 +12,16 @@ import hashlib import json +import math import random import re -import sqlite3 +from contextlib import contextmanager from pathlib import Path from typing import Any from pydantic import BaseModel, Field -from ..retriever.engine import get_chroma_client +from ..cache import diretorio_chroma from ..state import EstadoTextToInsight from ..token_tracking import build_token_usage_update from ..utils import extrair_tokens @@ -85,12 +86,12 @@ class TableExplorationResult(BaseModel): r"(int|integer|real|float|numeric|decimal|double|number|smallint|bigint|tinyint|mediumint)", re.IGNORECASE, ) -_DATE_TYPES = re.compile(r"(date|datetime|timestamp|time)", re.IGNORECASE) +_DATE_TYPES = re.compile(r"(date|datetime|timestamp|time|interval)", re.IGNORECASE) _BOOL_TYPES = re.compile(r"(bool|boolean)", re.IGNORECASE) def _classify_column_type(declared_type: str) -> str: - """Classifica o tipo declarado SQLite em uma das 4 categorias.""" + """Classifica o tipo declarado (SQLite ou PostgreSQL) em uma das 4 categorias.""" if not declared_type: # SQLite permite colunas sem tipo; tratamos como categórica por segurança return "categorical" @@ -110,15 +111,150 @@ def _classify_column_type(declared_type: str) -> str: # Limite de amostragem para tabelas grandes SAMPLE_LIMIT = 10_000 +# Dialetos em que a exploração sabe rodar (SQL das estatísticas + introspecção). +DIALETOS_SUPORTADOS = {"sqlite", "postgresql"} + +# Timeout por consulta de exploração no PostgreSQL. Uma coluna/tabela que +# estoure o tempo é pulada; as demais continuam. +TIMEOUT_EXPLORACAO_SEGUNDOS = 15 + +# No PostgreSQL, tabelas com estimativa do catálogo a partir deste número de +# linhas não são contadas: a contagem exata varreria a tabela inteira, e as +# estatísticas já usam no máximo SAMPLE_LIMIT linhas. Abaixo disso (inclusive +# estimativa -1, de tabela nunca analisada, ou 0, de view/tabela particionada) +# a contagem para em LIMIAR_ESTIMATIVA_LINHAS + 1 linhas. +LIMIAR_ESTIMATIVA_LINHAS = 100_000 + + +class ExploracaoInterrompida(Exception): + """A conexão deixou de responder no meio da exploração; não adianta seguir.""" + + +def _q(identificador: str) -> str: + """Identificador entre aspas duplas (SQLite e PostgreSQL), escapando aspas internas.""" + return '"' + identificador.replace('"', '""') + '"' + + +def _amostra(safe_col: str, safe_tbl: str) -> str: + """A amostra de uma coluna: as primeiras SAMPLE_LIMIT linhas da tabela, nulos incluídos.""" + return f"(SELECT {safe_col} FROM {safe_tbl} LIMIT {SAMPLE_LIMIT}) AS _amostra" + + +def _preparar_sessao_postgres(conn: Any) -> None: + """ + Abre a transação da exploração como somente leitura e com timeout. + + SET TRANSACTION e SET LOCAL valem só para a transação corrente, que é + desfeita ao final: nada disso fica na conexão quando ela volta para o + pool do chamador. A conexão não pode estar em autocommit (ver + `_explorar_no_banco`), senão os comandos não têm efeito. + """ + cursor = conn.cursor() + try: + cursor.execute("SET TRANSACTION READ ONLY") + cursor.execute(f"SET LOCAL statement_timeout = {int(TIMEOUT_EXPLORACAO_SEGUNDOS * 1000)}") + # Sem ORDER BY, "LIMIT n" só devolve sempre as mesmas linhas se a varredura + # for sequencial, sem workers paralelos e começando do início da tabela. + # Assim todas as estatísticas de uma coluna olham para a mesma amostra. + cursor.execute("SET LOCAL max_parallel_workers_per_gather = 0") + cursor.execute("SET LOCAL synchronize_seqscans = off") + finally: + cursor.close() + + +@contextmanager +def _isolar_erros(cursor: Any, dialeto: str, savepoint: str): + """ + Roda o bloco de modo que um erro de SQL não comprometa as consultas seguintes. + + No PostgreSQL um erro aborta a transação inteira; o bloco roda num + SAVEPOINT e, se falhar, a transação volta para ele. O erro é relançado + para quem chamou decidir o que fazer. Se nem o SAVEPOINT ou o ROLLBACK TO + SAVEPOINT funcionam, a conexão está perdida e levanta ExploracaoInterrompida. + """ + if dialeto != "postgresql": + yield + return + try: + cursor.execute(f"SAVEPOINT {savepoint}") + except Exception as erro: + raise ExploracaoInterrompida(str(erro)) from erro + try: + yield + except Exception: + try: + cursor.execute(f"ROLLBACK TO SAVEPOINT {savepoint}") + except Exception as erro_rollback: + raise ExploracaoInterrompida(str(erro_rollback)) from erro_rollback + raise + cursor.execute(f"RELEASE SAVEPOINT {savepoint}") + + +def _resolver_relacao_postgres(cursor: Any, table: str) -> tuple[str, int]: + """ + Schema e estimativa de linhas da relação que `table` (sem schema) alcança. + + Usa a mesma resolução pelo search_path que o SQLAlchemy usa para listar + tabelas no nó de schema e que as consultas de estatística usam ao citar + a tabela sem schema; com tabelas homônimas, vale a primeira do search_path. + """ + cursor.execute( + "SELECT n.nspname, c.reltuples::bigint FROM pg_class c " + "JOIN pg_namespace n ON n.oid = c.relnamespace " + "WHERE c.oid = to_regclass(%s)", + (_q(table),), + ) + linha = cursor.fetchone() + if linha is None: + raise LookupError(f"tabela {table!r} não encontrada no search_path") + return linha[0], int(linha[1]) + + +def _listar_colunas(cursor: Any, table: str, schema_pg: str | None = None) -> list[tuple[str, str]]: + """(nome, tipo declarado) de cada coluna, na ordem da tabela. `schema_pg` só no PostgreSQL.""" + if schema_pg is not None: + cursor.execute( + "SELECT column_name, data_type FROM information_schema.columns " + "WHERE table_schema = %s AND table_name = %s " + "ORDER BY ordinal_position", + (schema_pg, table), + ) + return [(nome, tipo or "") for nome, tipo in cursor.fetchall()] + + cursor.execute(f"PRAGMA table_info({_q(table)})") + # table_info retorna: cid, name, type, notnull, dflt_value, pk + return [(info[1], info[2] or "") for info in cursor.fetchall()] + + +def _contar_linhas(cursor: Any, table: str, estimativa_pg: int | None = None) -> int: + """ + Total de linhas. `estimativa_pg` (reltuples do PostgreSQL) evita varrer + tabelas grandes; ver LIMIAR_ESTIMATIVA_LINHAS. + """ + if estimativa_pg is None: + cursor.execute(f"SELECT COUNT(*) FROM {_q(table)}") + return cursor.fetchone()[0] + + if estimativa_pg >= LIMIAR_ESTIMATIVA_LINHAS: + return estimativa_pg + cursor.execute( + f"SELECT COUNT(*) FROM (SELECT 1 FROM {_q(table)} LIMIT {LIMIAR_ESTIMATIVA_LINHAS + 1}) AS _contagem" + ) + # Passou do limite: a estimativa estava desatualizada; o limite é o melhor piso conhecido. + return min(cursor.fetchone()[0], LIMIAR_ESTIMATIVA_LINHAS) + def _safe_float(val: Any) -> float | None: - """Tenta converter um valor para float de forma segura.""" + """Converte para float; None se não der ou se o valor não for finito.""" if val is None or val == "": return None try: - return float(val) + f_val = float(val) except (ValueError, TypeError): return None + # numeric do PostgreSQL vai além do float (ex.: 1e400 vira inf), e NaN + # também é um numeric válido; nenhum dos dois serve como estatística. + return f_val if math.isfinite(f_val) else None def _safe_round(val: Any, ndigits: int = 4) -> float | None: @@ -130,57 +266,62 @@ def _safe_round(val: Any, ndigits: int = 4) -> float | None: def _compute_numeric_stats( - cursor: sqlite3.Cursor, table: str, column: str, total_rows: int, + cursor: Any, table: str, column: str, total_rows: int, dialeto: str = "sqlite", ) -> NumericColumnStats: - """Calcula estatísticas numéricas usando SQL aggregates + amostragem para mediana.""" - safe_col = f'"{column}"' - safe_tbl = f'"{table}"' + """ + Média, mediana, desvio padrão, mínimo, máximo e taxa de nulos, todos + calculados sobre a mesma amostra (ver `_amostra`). + """ + safe_col = _q(column) + amostra = _amostra(safe_col, _q(table)) cursor.execute( f"SELECT AVG({safe_col}), MIN({safe_col}), MAX({safe_col}), " - f"COUNT(*) - COUNT({safe_col}) " - f"FROM (SELECT {safe_col} FROM {safe_tbl} LIMIT {SAMPLE_LIMIT})" + f"COUNT(*) - COUNT({safe_col}), COUNT({safe_col}) " + f"FROM {amostra}" ) - row = cursor.fetchone() - avg_val, min_val, max_val, null_count = row + avg_val, min_val, max_val, null_count, non_null_count = cursor.fetchone() sample_size = min(total_rows, SAMPLE_LIMIT) null_rate = round(null_count / sample_size, 4) if sample_size > 0 else 0.0 - # std_dev via SQL (population std dev na amostra) + # Desvio padrão populacional e mediana são opcionais: se a consulta falhar, + # a coluna fica com as estatísticas acima. std_dev = None avg_float = _safe_float(avg_val) if avg_float is not None: try: - cursor.execute( - f"SELECT AVG(({safe_col} - {avg_float}) * ({safe_col} - {avg_float})) " - f"FROM (SELECT {safe_col} FROM {safe_tbl} WHERE {safe_col} IS NOT NULL LIMIT {SAMPLE_LIMIT})" - ) - variance = cursor.fetchone()[0] - var_float = _safe_float(variance) + with _isolar_erros(cursor, dialeto, "_tti_consulta"): + cursor.execute( + f"SELECT AVG(({safe_col} - {avg_float}) * ({safe_col} - {avg_float})) " + f"FROM {amostra} WHERE {safe_col} IS NOT NULL" + ) + var_float = _safe_float(cursor.fetchone()[0]) if var_float is not None and var_float >= 0: std_dev = round(var_float ** 0.5, 4) + except ExploracaoInterrompida: + raise except Exception: std_dev = None - # mediana aproximada via ORDER BY + LIMIT/OFFSET na amostra median_val = None - try: - cursor.execute( - f"SELECT COUNT(*) FROM (SELECT {safe_col} FROM {safe_tbl} WHERE {safe_col} IS NOT NULL LIMIT {SAMPLE_LIMIT})" - ) - non_null_count = cursor.fetchone()[0] - if non_null_count > 0: - mid = non_null_count // 2 - cursor.execute( - f"SELECT {safe_col} FROM {safe_tbl} WHERE {safe_col} IS NOT NULL " - f"ORDER BY {safe_col} LIMIT 1 OFFSET {mid}" - ) - median_row = cursor.fetchone() - if median_row: - median_val = median_row[0] - except Exception: - median_val = None + if non_null_count: + # Com quantidade par de valores, a mediana é a média dos dois centrais. + meio = (non_null_count - 1) // 2 + centrais = 1 if non_null_count % 2 else 2 + try: + with _isolar_erros(cursor, dialeto, "_tti_consulta"): + cursor.execute( + f"SELECT {safe_col} FROM {amostra} WHERE {safe_col} IS NOT NULL " + f"ORDER BY {safe_col} LIMIT {centrais} OFFSET {meio}" + ) + valores = [_safe_float(r[0]) for r in cursor.fetchall()] + if valores and None not in valores: + median_val = sum(valores) / len(valores) + except ExploracaoInterrompida: + raise + except Exception: + median_val = None return NumericColumnStats( mean=_safe_round(avg_val, 4), @@ -192,17 +333,37 @@ def _compute_numeric_stats( ) +def _valores_de_exemplo(cursor: Any, table: str, column: str, tamanho_pool: int) -> list[str]: + """ + Até 3 valores distintos da amostra, para o LLM ver formato e grafia. + + O DISTINCT roda só sobre a amostra (numa coluna com poucos valores, um + DISTINCT ... LIMIT na tabela inteira a varreria toda atrás de valores que + não existem), e o sorteio usa uma semente fixa por coluna, para que a + mesma amostra dê sempre os mesmos exemplos. + """ + safe_col = _q(column) + cursor.execute( + f"SELECT DISTINCT {safe_col} FROM {_amostra(safe_col, _q(table))} " + f"WHERE {safe_col} IS NOT NULL LIMIT {tamanho_pool}" + ) + pool = sorted(str(r[0]) for r in cursor.fetchall()) + if not pool: + return [] + return random.Random(f"{table}.{column}").sample(pool, min(3, len(pool))) + + def _compute_categorical_stats( - cursor: sqlite3.Cursor, table: str, column: str, total_rows: int, + cursor: Any, table: str, column: str, total_rows: int, dialeto: str = "sqlite", ) -> CategoricalColumnStats: """Calcula top-5, cardinalidade e amostras para colunas categóricas.""" - safe_col = f'"{column}"' - safe_tbl = f'"{table}"' + safe_col = _q(column) + safe_tbl = _q(table) # Top 5 valores mais frequentes cursor.execute( f"SELECT {safe_col}, COUNT(*) as cnt " - f"FROM (SELECT {safe_col} FROM {safe_tbl} LIMIT {SAMPLE_LIMIT}) " + f"FROM {_amostra(safe_col, safe_tbl)} " f"WHERE {safe_col} IS NOT NULL " f"GROUP BY {safe_col} ORDER BY cnt DESC LIMIT 5" ) @@ -211,7 +372,7 @@ def _compute_categorical_stats( # Cardinalidade cursor.execute( f"SELECT COUNT(DISTINCT {safe_col}) " - f"FROM (SELECT {safe_col} FROM {safe_tbl} LIMIT {SAMPLE_LIMIT})" + f"FROM {_amostra(safe_col, safe_tbl)}" ) cardinality = cursor.fetchone()[0] or 0 @@ -219,20 +380,12 @@ def _compute_categorical_stats( sample_size = min(total_rows, SAMPLE_LIMIT) cursor.execute( f"SELECT COUNT(*) - COUNT({safe_col}) " - f"FROM (SELECT {safe_col} FROM {safe_tbl} LIMIT {SAMPLE_LIMIT})" + f"FROM {_amostra(safe_col, safe_tbl)}" ) null_count = cursor.fetchone()[0] null_rate = round(null_count / sample_size, 4) if sample_size > 0 else 0.0 - # 3 amostras aleatórias (via random offset para evitar viés de posição) - sample_values: list[str] = [] - cursor.execute( - f"SELECT DISTINCT {safe_col} FROM {safe_tbl} " - f"WHERE {safe_col} IS NOT NULL LIMIT 50" - ) - distinct_pool = [str(r[0]) for r in cursor.fetchall()] - if distinct_pool: - sample_values = random.sample(distinct_pool, min(3, len(distinct_pool))) + sample_values = _valores_de_exemplo(cursor, table, column, tamanho_pool=50) return CategoricalColumnStats( top_values=top_values, @@ -243,16 +396,16 @@ def _compute_categorical_stats( def _compute_date_stats( - cursor: sqlite3.Cursor, table: str, column: str, total_rows: int, + cursor: Any, table: str, column: str, total_rows: int, dialeto: str = "sqlite", ) -> DateColumnStats: """Calcula min, max e amostras para colunas de data.""" - safe_col = f'"{column}"' - safe_tbl = f'"{table}"' + safe_col = _q(column) + safe_tbl = _q(table) cursor.execute( f"SELECT MIN({safe_col}), MAX({safe_col}), " f"COUNT(*) - COUNT({safe_col}) " - f"FROM (SELECT {safe_col} FROM {safe_tbl} LIMIT {SAMPLE_LIMIT})" + f"FROM {_amostra(safe_col, safe_tbl)}" ) row = cursor.fetchone() min_val, max_val, null_count = row @@ -261,14 +414,7 @@ def _compute_date_stats( null_rate = round(null_count / sample_size, 4) if sample_size > 0 else 0.0 # 3 amostras para inferir formato - sample_values: list[str] = [] - cursor.execute( - f"SELECT DISTINCT {safe_col} FROM {safe_tbl} " - f"WHERE {safe_col} IS NOT NULL LIMIT 30" - ) - pool = [str(r[0]) for r in cursor.fetchall()] - if pool: - sample_values = random.sample(pool, min(3, len(pool))) + sample_values = _valores_de_exemplo(cursor, table, column, tamanho_pool=30) return DateColumnStats( min=str(min_val) if min_val is not None else None, @@ -279,18 +425,25 @@ def _compute_date_stats( def _compute_boolean_stats( - cursor: sqlite3.Cursor, table: str, column: str, total_rows: int, + cursor: Any, table: str, column: str, total_rows: int, dialeto: str = "sqlite", ) -> BooleanColumnStats: """Calcula contagens true/false para colunas booleanas.""" - safe_col = f'"{column}"' - safe_tbl = f'"{table}"' + safe_col = _q(column) + safe_tbl = _q(table) + if dialeto == "postgresql": + # boolean nativo: comparar com 1/0 é erro de tipo no PostgreSQL. + cond_true = f"{safe_col} IS TRUE" + cond_false = f"{safe_col} IS FALSE" + else: + cond_true = f"{safe_col} = 1 OR LOWER(CAST({safe_col} AS TEXT)) = 'true'" + cond_false = f"{safe_col} = 0 OR LOWER(CAST({safe_col} AS TEXT)) = 'false'" cursor.execute( f"SELECT " - f"SUM(CASE WHEN {safe_col} = 1 OR LOWER(CAST({safe_col} AS TEXT)) = 'true' THEN 1 ELSE 0 END), " - f"SUM(CASE WHEN {safe_col} = 0 OR LOWER(CAST({safe_col} AS TEXT)) = 'false' THEN 1 ELSE 0 END), " + f"SUM(CASE WHEN {cond_true} THEN 1 ELSE 0 END), " + f"SUM(CASE WHEN {cond_false} THEN 1 ELSE 0 END), " f"COUNT(*) - COUNT({safe_col}) " - f"FROM (SELECT {safe_col} FROM {safe_tbl} LIMIT {SAMPLE_LIMIT})" + f"FROM {_amostra(safe_col, safe_tbl)}" ) row = cursor.fetchone() true_count, false_count, null_count = row @@ -318,55 +471,72 @@ def _compute_boolean_stats( def explore_table( - conn: sqlite3.Connection, + conn: Any, table_name: str, columns_to_explore: list[str] | None = None, row_count: int | None = None, + dialeto: str = "sqlite", ) -> TableExplorationResult: """ - Calcula estatísticas por coluna para uma tabela SQLite. + Calcula estatísticas por coluna para uma tabela (SQLite ou PostgreSQL). Args: - conn: Conexão SQLite (preferencialmente read-only). + conn: Conexão DB-API (preferencialmente read-only). No PostgreSQL, a + conexão não pode estar em autocommit e a transação já deve ter sido + preparada com `_preparar_sessao_postgres` (ver `_explorar_no_banco`). table_name: Nome da tabela a explorar. columns_to_explore: Lista opcional de colunas a explorar. Se omitida (ou None), explora todas. row_count: Contagem de linhas já conhecida (ex: vinda do cache) para evitar SELECT COUNT(*). + dialeto: "sqlite" ou "postgresql". Returns: TableExplorationResult com stats por coluna. """ cursor = conn.cursor() + try: + # Um erro na introspecção desfaz só o que esta tabela fez; quem chama segue para a próxima. + with _isolar_erros(cursor, dialeto, "_tti_tabela"): + return _explorar_colunas(cursor, table_name, columns_to_explore, row_count, dialeto) + finally: + cursor.close() + + +def _explorar_colunas( + cursor: Any, + table_name: str, + columns_to_explore: list[str] | None, + row_count: int | None, + dialeto: str, +) -> TableExplorationResult: + schema_pg = estimativa_pg = None + if dialeto == "postgresql": + schema_pg, estimativa_pg = _resolver_relacao_postgres(cursor, table_name) # Contagem total de linhas (reaproveita do cache se já conhecida) - safe_tbl = f'"{table_name}"' - if row_count is None: - cursor.execute(f"SELECT COUNT(*) FROM {safe_tbl}") - total_rows = cursor.fetchone()[0] - else: - total_rows = row_count + total_rows = row_count if row_count is not None else _contar_linhas(cursor, table_name, estimativa_pg) - # Introspect colunas - cursor.execute(f"PRAGMA table_info({safe_tbl})") - columns_info = cursor.fetchall() - # table_info retorna: cid, name, type, notnull, dflt_value, pk + columns_info = _listar_colunas(cursor, table_name, schema_pg) + if not columns_info: + # Tabela que não existe (ou sem colunas visíveis): não entra no + # resultado, senão o cache a marcaria como explorada. + raise LookupError(f"nenhuma coluna encontrada para a tabela {table_name!r}") result = TableExplorationResult( table_name=table_name, row_count_estimate=total_rows, ) - for col_info in columns_info: - col_name = col_info[1] + for col_name, col_type_raw in columns_info: if columns_to_explore is not None and col_name not in columns_to_explore: continue - col_type_raw = col_info[2] or "" - category = _classify_column_type(col_type_raw) - - compute_fn = _STAT_DISPATCHER[category] + compute_fn = _STAT_DISPATCHER[_classify_column_type(col_type_raw)] try: - stats = compute_fn(cursor, table_name, col_name, total_rows) + with _isolar_erros(cursor, dialeto, "_tti_coluna"): + stats = compute_fn(cursor, table_name, col_name, total_rows, dialeto=dialeto) + except ExploracaoInterrompida: + raise except Exception as e: - # Se falhar em uma coluna, log e segue para as demais + # Se falhar em uma coluna (tipo sem suporte, timeout...), log e segue para as demais print(f"[DATA_EXPLORATION] Erro ao computar stats para {table_name}.{col_name}: {e}") continue @@ -375,50 +545,27 @@ def explore_table( return result -def explore_tables( - db_path: str, - table_names: list[str], - colunas_para_explorar: dict[str, list[str]] | None = None, - known_row_counts: dict[str, int] | None = None, -) -> dict[str, TableExplorationResult]: - """ - Explora múltiplas tabelas e retorna dict indexado por nome de tabela. - - Args: - db_path: Caminho para o arquivo SQLite. - table_names: Lista de nomes de tabelas a explorar. - colunas_para_explorar: Dicionário opcional mapeando tabela para lista de colunas a explorar. - known_row_counts: Dicionário opcional mapeando tabela para contagem de linhas já conhecida. - - Returns: - Dict[table_name, TableExplorationResult] - """ - caminho = Path(db_path) - if not caminho.exists(): - print(f"[DATA_EXPLORATION] Banco não encontrado: {db_path}") - return {} - - conn = sqlite3.connect(f"file:{caminho}?mode=ro", uri=True) - try: - return _explorar_tabelas(conn, table_names, colunas_para_explorar, known_row_counts) - finally: - conn.close() - - def _explorar_tabelas( conn: Any, table_names: list[str], colunas_para_explorar: dict[str, list[str]] | None, known_row_counts: dict[str, int] | None = None, + dialeto: str = "sqlite", ) -> dict[str, TableExplorationResult]: results: dict[str, TableExplorationResult] = {} for table_name in table_names: + cols_to_explore = None + if colunas_para_explorar and table_name in colunas_para_explorar: + cols_to_explore = colunas_para_explorar[table_name] + row_count = known_row_counts.get(table_name) if known_row_counts else None try: - cols_to_explore = None - if colunas_para_explorar and table_name in colunas_para_explorar: - cols_to_explore = colunas_para_explorar[table_name] - row_count = known_row_counts.get(table_name) if known_row_counts else None - results[table_name] = explore_table(conn, table_name, cols_to_explore, row_count=row_count) + results[table_name] = explore_table( + conn, table_name, cols_to_explore, row_count=row_count, dialeto=dialeto + ) + except ExploracaoInterrompida as e: + # Conexão perdida: as tabelas já exploradas continuam valendo. + print(f"[DATA_EXPLORATION] Conexão perdida em '{table_name}' ({e}) — parando a exploração.") + break except Exception as e: print(f"[DATA_EXPLORATION] Erro ao explorar tabela '{table_name}': {e}") continue @@ -589,40 +736,62 @@ def _extract_table_names_from_rag_context(contexto_rag: str) -> list[str]: """ Extrai nomes de tabelas do texto formatado pelo retriever RAG. - O retriever formata cada tabela como 'Tabela: ', então - extraímos todos os nomes com regex. + O retriever formata cada tabela como 'Tabela: ' numa linha + própria. O nome vai até o fim da linha, para aceitar nomes com espaço + ou outros caracteres (possíveis com identificadores entre aspas). """ - return re.findall(r"Tabela:\s*(\w+)", contexto_rag) + return [nome.strip() for nome in re.findall(r"^\s*Tabela:[ \t]*(.+?)[ \t]*$", contexto_rag, re.MULTILINE)] # --------------------------------------------------------------------------- # Nó do grafo LangGraph # --------------------------------------------------------------------------- -def _backend_suporta_exploracao(estado: EstadoTextToInsight, db_path: str) -> bool: - """ - Este nó só sabe explorar um arquivo SQLite local (abre `db_path` com - sqlite3). Para qualquer outro banco ele não consegue explorar — e, pior, - se `db_path` sobrou preenchido com um valor antigo (o default do CLI - aponta para um .db do projeto), ele exploraria esse arquivo sem relação - nenhuma com o banco de verdade, devolvendo estatísticas erradas pra IA. - - Retorna False quando: - - `db_url` está preenchido (o banco real vem da URL, não do db_path); - - ou o dialeto deduzido pela extensão do db_path não é sqlite (ex: .duckdb). +def _explorar_no_banco( + engine: Any, + dialeto: str, + alvos: list[str], + explorar_parcial: dict[str, list[str]], + known_row_counts: dict[str, int], +) -> dict[str, TableExplorationResult]: """ - if (estado.get("db_url") or "").strip(): - return False + Explora as tabelas numa conexão do pool do chamador e a devolve como recebeu. - from .schema import _detectar_dialeto + No PostgreSQL tudo roda numa única transação somente leitura, desfeita + ao final. Se a engine do chamador usa autocommit (isolation_level= + "AUTOCOMMIT"), ele é desligado durante a exploração, porque sem uma + transação o READ ONLY e os SET LOCAL não teriam efeito, e religado antes + de devolver a conexão. + """ + conn = engine.raw_connection() + if dialeto != "postgresql": + try: + return _explorar_tabelas(conn, alvos, explorar_parcial, known_row_counts, dialeto=dialeto) + finally: + conn.close() - return _detectar_dialeto(db_path) == "sqlite" + driver = conn.driver_connection + autocommit_original = bool(getattr(driver, "autocommit", False)) + try: + if autocommit_original: + driver.autocommit = False + _preparar_sessao_postgres(conn) + return _explorar_tabelas(conn, alvos, explorar_parcial, known_row_counts, dialeto=dialeto) + finally: + try: + conn.rollback() # encerra a transação read-only + if autocommit_original: + driver.autocommit = True + except Exception: + # Não dá para garantir o estado da conexão: o pool a descarta. + conn.invalidate() + conn.close() def nos_nodo_data_exploration( estado: EstadoTextToInsight, + engine: Any, use_data_exploration: bool = True, - engine: Any = None, ) -> dict: """ Nó Data Exploration: calcula estatísticas por coluna para as tabelas @@ -631,31 +800,24 @@ def nos_nodo_data_exploration( Roda após o retriever e antes do planejador, injetando as estatísticas no campo `contexto_data_exploration` do estado. - Com `engine` injetada, explora o banco dela (e nunca o `db_path` do estado). - As estatísticas usam SQL específico do SQLite (PRAGMA), então para outros - dialetos a exploração é pulada. + Explora o banco da Engine SQLAlchemy injetada pelo chamador. Suporta + SQLite e PostgreSQL; para outros dialetos a exploração é pulada. No + PostgreSQL, a exploração roda numa transação somente leitura, com + timeout por consulta, que é desfeita ao final. """ if not use_data_exploration: print("[DATA_EXPLORATION] Data exploration desativada via toggle.") return {"contexto_data_exploration": ""} - if engine is not None and engine.dialect.name != "sqlite": - print(f"[DATA_EXPLORATION] Exploração só suporta SQLite (engine: {engine.dialect.name}) — pulando.") + dialeto = engine.dialect.name + if dialeto not in DIALETOS_SUPORTADOS: + print(f"[DATA_EXPLORATION] Exploração não suporta o dialeto '{dialeto}' — pulando.") return {"contexto_data_exploration": ""} schema_alvo = estado.get("contexto_rag_schema") or estado.get("contexto_schema", "") - db_path = estado.get("db_path", "").strip() - - if not schema_alvo or (engine is None and not db_path): - print("[DATA_EXPLORATION] Sem schema ou db_path — pulando exploração.") - return {} - if engine is None and not _backend_suporta_exploracao(estado, db_path): - print( - "[DATA_EXPLORATION] O banco configurado não é um arquivo SQLite local " - "(db_url/extensão do db_path) — exploração ainda não " - "suportada para esse banco, pulando." - ) + if not schema_alvo: + print("[DATA_EXPLORATION] Sem schema — pulando exploração.") return {} # Extrair nomes de tabelas do contexto de schema (RAG ou completo) @@ -676,14 +838,13 @@ def nos_nodo_data_exploration( if alvos: known_row_counts = {t: cache[t]["linhas"] for t in alvos if t in cache} - if engine is not None: - conn = engine.raw_connection() - try: - exploration_results = _explorar_tabelas(conn, alvos, explorar_parcial, known_row_counts) - finally: - conn.close() - else: - exploration_results = explore_tables(db_path, alvos, explorar_parcial, known_row_counts) + try: + exploration_results = _explorar_no_banco(engine, dialeto, alvos, explorar_parcial, known_row_counts) + except Exception as e: + # A exploração é um complemento do prompt: se o banco falhar aqui + # (conexão caiu, permissão...), o fluxo segue sem estatísticas novas. + print(f"[DATA_EXPLORATION] Exploração interrompida ({e}) — seguindo sem estatísticas novas.") + exploration_results = {} cache = _atualizar_cache(cache, exploration_results, set(explorar_tudo)) # Formatar para injeção no prompt @@ -833,6 +994,7 @@ def _parse_columns_from_rag_context(contexto_rag: str) -> list[dict[str, str]]: def _exploration_selector_rag( estado: EstadoTextToInsight, top_k: int = 15, + cache_dir: str | Path | None = None, ) -> dict: """ Seleção de colunas via RAG: indexa cada coluna do schema recuperado @@ -869,8 +1031,7 @@ def _exploration_selector_rag( context_hash = hashlib.md5(contexto_rag.encode("utf-8")).hexdigest() collection_name = f"cols_{context_hash}" - #chroma_dir = Path(__file__).resolve().parent.parent / "retriever" / "chroma_db" - chroma_client = get_chroma_client() + chroma_client = chromadb.PersistentClient(path=str(diretorio_chroma(cache_dir))) collection = chroma_client.get_or_create_collection(name=collection_name) # Indexar se necessário @@ -911,6 +1072,7 @@ def nos_nodo_exploration_selector( estado: EstadoTextToInsight, llm: Any, exploration_selector_mode: str = "off", + cache_dir: str | Path | None = None, ) -> dict: """ Nó que decide quais colunas de cada tabela devem ser exploradas. @@ -926,7 +1088,7 @@ def nos_nodo_exploration_selector( return {"colunas_para_explorar": {}} if mode == "rag": - return _exploration_selector_rag(estado) + return _exploration_selector_rag(estado, cache_dir=cache_dir) if mode == "llm": return _exploration_selector_llm(estado, llm) diff --git a/text_to_insight/nodes/enrich_schema.py b/text_to_insight/nodes/enrich_schema.py index 9097d60..0d49c3d 100644 --- a/text_to_insight/nodes/enrich_schema.py +++ b/text_to_insight/nodes/enrich_schema.py @@ -1,14 +1,15 @@ import re import json from pathlib import Path -from langchain_google_genai import ChatGoogleGenerativeAI +from typing import Any + +from ..cache import salvar_schema_enriquecido from ..state import EstadoTextToInsight from ..token_tracking import build_batch_token_usage_update -def nos_nodo_enrich(estado: EstadoTextToInsight, llm: ChatGoogleGenerativeAI, engine=None) -> dict: +def nos_nodo_enrich(estado: EstadoTextToInsight, llm: Any, cache_dir: str | Path | None = None) -> dict: print("[SCHEMA-ENRICHMENT] Iniciando enriquecimento do schema (Modo Seguro JSON)...") - db_path = Path(estado.get("db_path", "").strip()) raw_schema = estado.get("contexto_schema", "").strip() @@ -75,27 +76,11 @@ def nos_nodo_enrich(estado: EstadoTextToInsight, llm: ChatGoogleGenerativeAI, en contexto_enriquecido = "\n".join(linhas_enriquecidas) - # Nome de cache inclui dialeto para consistência com schema.py. - # Detecta o dialeto pelo sufixo do arquivo; fallback para 'sqlite'. - _EXTENSAO_PARA_DIALETO = { - ".db": "sqlite", - ".sqlite": "sqlite", - ".sqlite3": "sqlite", - ".duckdb": "duckdb", - } - # O cache é indexado pelo db_path. Se o schema veio de outra fonte - # (engine injetada ou db_url), gravar aqui sobrescreveria o cache do - # arquivo SQLite local com o schema de um banco diferente. - if engine is not None or estado.get("db_url"): - print("[SCHEMA-ENRICHMENT] Schema não veio de db_path — cache não será gravado.") - else: - dialeto = _EXTENSAO_PARA_DIALETO.get(db_path.suffix.lower(), "sqlite") - cache_path = db_path.with_name(f"{db_path.stem}_{dialeto}_enriched_schema.txt") - - with open(cache_path, "w", encoding="utf-8") as f: - f.write(contexto_enriquecido) - - print(f"[SCHEMA-ENRICHMENT] Schema enriquecido salvo em {cache_path.name}.") + # O cache é indexado pelo hash do schema original (o mesmo texto que o nó + # de schema produz), então a próxima execução sobre este banco o encontra. + cache_path = salvar_schema_enriquecido(cache_dir, estado.get("contexto_schema", ""), contexto_enriquecido) + if cache_path is not None: + print(f"[SCHEMA-ENRICHMENT] Schema enriquecido salvo em {cache_path}.") return { "tem_descricao": True, diff --git a/text_to_insight/nodes/graph_generator.py b/text_to_insight/nodes/graph_generator.py index 53edd79..621165b 100644 --- a/text_to_insight/nodes/graph_generator.py +++ b/text_to_insight/nodes/graph_generator.py @@ -7,9 +7,6 @@ """ import re -import subprocess -import sys -import tempfile from datetime import datetime from pathlib import Path @@ -18,10 +15,14 @@ from ..state import EstadoTextToInsight from ..token_tracking import build_token_usage_update from ..utils import extrair_tokens +from ..execucao_python import executar_python_isolado # Diretório padrão para salvar os gráficos gerados GRAPHS_DIR = Path(__file__).parent.parent.parent / "graphs" +NOME_CSV = "dados.csv" +NOME_GRAFICO = "grafico.png" + PROMPT_GRAPH_GENERATOR = """Você é um especialista em visualização de dados com Python e matplotlib. Sua tarefa: gerar APENAS o bloco de código Python que cria um gráfico matplotlib @@ -67,55 +68,23 @@ def _extrair_codigo_python(texto: str) -> str: return texto.strip() -def _construir_script(csv_path: str, output_path: str, codigo_visualizacao: str) -> str: +def _construir_script(codigo_visualizacao: str) -> str: """Monta o script Python completo que será executado.""" return f'''import pandas as pd import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt -df = pd.read_csv("{csv_path}") +df = pd.read_csv("{NOME_CSV}") {codigo_visualizacao} plt.tight_layout() -plt.savefig("{output_path}", dpi=150, bbox_inches='tight') +plt.savefig("{NOME_GRAFICO}", dpi=150, bbox_inches='tight') plt.close() -print("GRAPH_OK") ''' -def _executar_script(script: str) -> tuple[bool, str]: - """Executa o script Python em um subprocesso e retorna (sucesso, saída/erro).""" - with tempfile.NamedTemporaryFile( - mode="w", suffix=".py", delete=False, encoding="utf-8" - ) as tmp: - tmp.write(script) - tmp_path = tmp.name - - try: - resultado = subprocess.run( - [sys.executable, tmp_path], - capture_output=True, - text=True, - timeout=30, - ) - stdout = resultado.stdout.strip() - stderr = resultado.stderr.strip() - - if resultado.returncode == 0 and "GRAPH_OK" in stdout: - return True, stdout - else: - erro = stderr if stderr else stdout - return False, erro - except subprocess.TimeoutExpired: - return False, "Timeout: o script de geração do gráfico excedeu 30 segundos." - except Exception as e: - return False, f"Erro ao executar script: {e}" - finally: - Path(tmp_path).unlink(missing_ok=True) - - def nos_nodo_gerador_grafico(estado: EstadoTextToInsight, llm: ChatGoogleGenerativeAI) -> dict: """ Nó Gerador de Gráficos: usa o LLM para gerar código matplotlib e o executa. @@ -157,15 +126,15 @@ def nos_nodo_gerador_grafico(estado: EstadoTextToInsight, llm: ChatGoogleGenerat output_path = str((GRAPHS_DIR / f"grafico_{timestamp}.png").resolve()) # Montar e executar o script completo - script = _construir_script(csv_path, output_path, codigo_visualizacao) + script = _construir_script(codigo_visualizacao) print(script) print(f"[GERADOR_GRAFICO] Executando script...") - sucesso, saida = _executar_script(script) + resultado = executar_python_isolado(script, arquivos_entrada={NOME_CSV: Path(csv_path)}, arquivos_saida={NOME_GRAFICO: Path(output_path)}, timeout_s=30) token_update = build_token_usage_update("graph_generator", resposta) - if sucesso and Path(output_path).exists(): + if resultado["ok"] and Path(output_path).exists(): print(f"[GERADOR_GRAFICO] ✓ Gráfico salvo em: {output_path}") return { "grafico_gerado": True, @@ -173,7 +142,7 @@ def nos_nodo_gerador_grafico(estado: EstadoTextToInsight, llm: ChatGoogleGenerat **token_update, } else: - print(f"[GERADOR_GRAFICO] ✗ Falha na geração do gráfico: {saida[:200]}") + print(f"[GERADOR_GRAFICO] ✗ Falha na geração do gráfico: {resultado['erro_execucao'][:200]}") return { "grafico_gerado": False, "caminho_grafico": "", diff --git a/text_to_insight/nodes/retriever.py b/text_to_insight/nodes/retriever.py index 5b57bf6..f88b777 100644 --- a/text_to_insight/nodes/retriever.py +++ b/text_to_insight/nodes/retriever.py @@ -6,6 +6,8 @@ formata o resultado como texto e adiciona ao campo contexto_rag_schema. """ +from pathlib import Path + from ..state import EstadoTextToInsight from ..retriever.engine import SchemaGraphRAG @@ -18,7 +20,11 @@ def _formatar_contexto_rag(retrieved, relations=None) -> str: ) -def nos_nodo_retriever(estado: EstadoTextToInsight, use_rag: bool = True) -> dict: +def nos_nodo_retriever( + estado: EstadoTextToInsight, + use_rag: bool = True, + cache_dir: str | Path | None = None, +) -> dict: pergunta = ( estado.get("pergunta_atual", "") or estado.get("pergunta_original", "") @@ -51,7 +57,7 @@ def nos_nodo_retriever(estado: EstadoTextToInsight, use_rag: bool = True) -> dic tentativas = estado.get("tentativas_loop", 0) top_k_dinamico = 8 + (tentativas * 4) # aumenta o top_k a cada tentativa de loop, para tentar recuperar mais tabelas se necessário - rag = SchemaGraphRAG(schema={"contexto_schema": schema_full}) + rag = SchemaGraphRAG(schema={"contexto_schema": schema_full}, cache_dir=cache_dir) print(f"[RETRIEVER] Recuperando top_k={top_k_dinamico} tabelas (loop atual: {tentativas})...") retrieved, relations = rag.retrieve(pergunta, top_k=top_k_dinamico) diff --git a/text_to_insight/nodes/sandbox.py b/text_to_insight/nodes/sandbox.py index a5afa3b..81485dd 100644 --- a/text_to_insight/nodes/sandbox.py +++ b/text_to_insight/nodes/sandbox.py @@ -8,17 +8,14 @@ from typing import Any from ..state import EstadoTextToInsight -from .code_agent.code_sql import executar_sql_sqlite, executar_sql_via_engine, executar_sql_via_url +from .code_agent.code_sql import executar_sql_via_engine -def nos_nodo_sandbox(estado: EstadoTextToInsight, engine: Any = None) -> dict: +def nos_nodo_sandbox(estado: EstadoTextToInsight, engine: Any) -> dict: """ - Nó Executor: executa a SQL gerada contra o banco real (SQLite, PostgreSQL ou MySQL). - - Se uma Engine SQLAlchemy foi injetada pelo chamador (`engine`), executa - diretamente nela via `executar_sql_via_engine` — nada de db_path/db_url precisa estar no estado (nem, portanto, no checkpoint do - grafo). Agora, a lógica utiliza uma engine, se ela existir. Caso não exista, verifica - se existe url. Novamente, se não existir, roda SQlite por padrão com db_path. + Nó Executor: executa a SQL gerada na Engine SQLAlchemy injetada pelo + chamador (SQLite, PostgreSQL, MySQL...). A engine nunca entra no estado, + então nada sobre a conexão vai para o checkpoint do grafo. """ sql = estado.get("sql_gerada", "").strip() @@ -30,20 +27,8 @@ def nos_nodo_sandbox(estado: EstadoTextToInsight, engine: Any = None) -> dict: "status": "exec_erro", } - if engine is not None: - print(f"[EXECUTOR] Executando SQL contra banco via engine ({engine.dialect.name})...") - resultado = executar_sql_via_engine(engine, sql) - else: - db_path = estado.get("db_path", "") - db_url = estado.get("db_url", "").strip() - - alvo = "banco via db_url (dialeto auto-detectado)" if db_url else db_path - print(f"[EXECUTOR] Executando SQL contra {alvo}...") - - if db_url: - resultado = executar_sql_via_url(db_url, sql) - else: - resultado = executar_sql_sqlite(db_path=db_path, sql=sql) + print(f"[EXECUTOR] Executando SQL contra banco via engine ({engine.dialect.name})...") + resultado = executar_sql_via_engine(engine, sql) attempt_tokens = estado.get("last_attempt_tokens") or {} diff --git a/text_to_insight/nodes/schema.py b/text_to_insight/nodes/schema.py index 6b0f63c..b4ea534 100644 --- a/text_to_insight/nodes/schema.py +++ b/text_to_insight/nodes/schema.py @@ -2,400 +2,23 @@ Nó Schema (Esquema) do grafo de agentes Text-to-Insight. O nó de schema é responsável por: -- Recuperar metadados e contexto do banco de dados -- Fornecer informações estruturais (tabelas, colunas, tipos) -- Enriquecer o estado com informações necessárias para a geração de código - -Suporta dois modos de introspecção: -1. Schema Crawler CLI (multi-dialeto: SQLite, DuckDB, PostgreSQL...) - Ativado quando SCHEMACRAWLER_BIN está configurado no estado. -2. PRAGMA SQLite nativo (fallback garantido para SQLite) +- Recuperar metadados do banco (tabelas, colunas, tipos, PKs e FKs) pela + Engine SQLAlchemy recebida do chamador; +- Opcionalmente inferir FKs virtuais quando o banco não as declara; +- Reaproveitar o schema enriquecido pelo LLM (enrich_rag) que estiver no + cache em disco (ver `text_to_insight/cache.py`). + +A biblioteca nunca abre conexões por conta própria: o banco é sempre a +Engine que o chamador passou para a InsightEngine. """ from pathlib import Path from typing import Any import re -import sqlite3 -import subprocess +from ..cache import ler_schema_enriquecido from ..state import EstadoTextToInsight -# --------------------------------------------------------------------------- -# Dialetos suportados pelo Schema Crawler -# Cada entrada define como montar os args de conexão para o dialeto. -# --------------------------------------------------------------------------- -_SC_DIALETOS = { - "sqlite": { - "args": lambda db: [ - "--server=sqlite", - f"--database={db}", - "--user=", - "--password=", - ] - }, - "duckdb": { - "args": lambda db: [ - f"--url=jdbc:duckdb:{db}", - "--user=", - "--password=", - ] - }, - -} - -_EXTENSAO_PARA_DIALETO = { - ".db": "sqlite", - ".sqlite": "sqlite", - ".sqlite3": "sqlite", - ".duckdb": "duckdb", -} - -# apenas dialetos de sqlite e duckdb são detectados por extensão. Para PostgreSQL e outros bancos remotos, a entrada é por url ou engine. - - -def _detectar_dialeto(db_path: str) -> str: - """Detecta dialeto pelo sufixo do arquivo. Fallback: sqlite.""" - ext = Path(db_path).suffix.lower() - return _EXTENSAO_PARA_DIALETO.get(ext, "sqlite") - - -# --------------------------------------------------------------------------- -# Parser do output TEXTO do Schema Crawler -# Converte para o formato canônico do pipeline: -# -# Tabela: nome -# - coluna: TIPO (PK, NOT NULL) -# - coluna2: TIPO -# Foreign keys: -# - col_origem -> tabela_ref.col_destino [cardinalidade] -# Indexes: -# - nome_idx [unique]: col1, col2 -# --------------------------------------------------------------------------- - -def _parsear_texto_schemacrawler(sc_text: str) -> str: - """ - Faz parse do output --output-format=text do Schema Crawler e - converte para o formato canônico que o enrich_schema.py e o - SchemaGraphRAG esperam. - - Extrai, para cada tabela: - - Colunas com tipo - - Quais colunas são PK (via seção 'Primary Key') - - Foreign keys com direção e cardinalidade - - Índices com tipo (unique / regular) - - Args: - sc_text: stdout do comando schemacrawler.sh --output-format=text - - Returns: - str: Schema no formato canônico do pipeline - """ - linhas = sc_text.splitlines() - partes = ["=== SCHEMA (SCHEMA CRAWLER) ===", ""] - - # --- Estruturas de estado do parser --- - tabela_atual: str | None = None - colunas: list[tuple[str, str]] = [] # [(nome, tipo), ...] - pks: set[str] = set() - fks_recebidas: list[str] = [] # linhas já formatadas - fks_emitidas: list[str] = [] - indexes: list[str] = [] - - # Seção corrente dentro de uma tabela - secao: str | None = None # "colunas" | "pk" | "fk" | "idx" | None - - def _flush_tabela(): - """Serializa a tabela acumulada no formato canônico.""" - if tabela_atual is None: - return - - partes.append(f"Tabela: {tabela_atual}") - - for nome, tipo in colunas: - flags = [] - if nome in pks: - flags.append("PK") - sufixo = f" ({', '.join(flags)})" if flags else "" - partes.append(f"- {nome}: {tipo}{sufixo}") - - # FKs emitidas (esta tabela -> outra) - todas_fks = fks_emitidas + fks_recebidas - if todas_fks: - partes.append(" Foreign keys:") - for fk in todas_fks: - partes.append(f" - {fk}") - - if indexes: - partes.append(" Indexes:") - for idx in indexes: - partes.append(f" - {idx}") - - partes.append("") - - # Regex para detectar início de tabela: - # "nome_tabela [table]" - re_tabela = re.compile(r"^(\w+)\s+\[table\]\s*$") - - # Regex para linha de coluna dentro da seção de colunas: - # " nome_coluna TIPO " (2+ espaços de indentação) - re_coluna = re.compile(r"^\s{2}(\w+)\s+(\w+)\s*$") - - # Regex para PK dentro da seção Primary Key: - # " nome_coluna " - re_pk = re.compile(r"^\s{2}(\w+)\s*$") - - # Regex para FK emitida: " col (0..many)--> outra_tabela.outra_col" - re_fk_emitida = re.compile( - r"^\s{2}(\w+)\s+\((\S+)\)-->\s+(\w+)\.(\w+)\s*$" - ) - # Regex para FK recebida: " col <--(0..many) outra_tabela.outra_col" - re_fk_recebida = re.compile( - r"^\s{2}(\w+)\s+<--\((\S+)\)\s+(\w+)\.(\w+)\s*$" - ) - - # Regex para linha de índice: "nome_idx [unique index]" ou "[index]" - re_idx_nome = re.compile(r"^(\S+)\s+\[(unique index|index)\]\s*$") - # Colunas do índice: " col1 unknown" - re_idx_col = re.compile(r"^\s{2}(\w+)\s+\S+\s*$") - - idx_nome_atual: str | None = None - idx_tipo_atual: str | None = None - idx_colunas: list[str] = [] - - def _flush_index(): - nonlocal idx_nome_atual, idx_tipo_atual, idx_colunas - if idx_nome_atual and idx_colunas: - tipo_label = "unique" if "unique" in (idx_tipo_atual or "") else "index" - indexes.append(f"{idx_nome_atual} [{tipo_label}]: {', '.join(idx_colunas)}") - idx_nome_atual = None - idx_tipo_atual = None - idx_colunas = [] - - for linha in linhas: - linha_stripped = linha.strip() - - # --- Separador de seções (linha de ===== ou -----) --- - if re.match(r"^[=\-]{10,}$", linha_stripped): - continue - - # --- Cabeçalhos de seção dentro de uma tabela --- - if linha_stripped == "Primary Key": - secao = "pk" - continue - if linha_stripped == "Foreign Keys": - secao = "fk" - continue - if linha_stripped == "Indexes": - _flush_index() - secao = "idx" - continue - - # --- Início de nova tabela --- - m_tabela = re_tabela.match(linha_stripped) - if m_tabela: - # Salva tabela anterior - _flush_index() - _flush_tabela() - # Reinicia estado - tabela_atual = m_tabela.group(1) - colunas = [] - pks = set() - fks_recebidas = [] - fks_emitidas = [] - indexes = [] - idx_nome_atual = None - idx_colunas = [] - secao = "colunas" - continue - - # --- Linhas vazias ou de metadados globais (antes de Tables) --- - if tabela_atual is None: - continue - - # --- Parser por seção --- - - if secao == "colunas": - m = re_coluna.match(linha) - if m: - colunas.append((m.group(1), m.group(2))) - - elif secao == "pk": - m = re_pk.match(linha) - if m: - pks.add(m.group(1)) - - elif secao == "fk": - m = re_fk_emitida.match(linha) - if m: - col, card, tab_ref, col_ref = m.groups() - fks_emitidas.append(f"{col} -> {tab_ref}.{col_ref} ({card})") - continue - m = re_fk_recebida.match(linha) - if m: - col, card, tab_ref, col_ref = m.groups() - fks_recebidas.append(f"{col} <- {tab_ref}.{col_ref} ({card})") - - elif secao == "idx": - # Nova entrada de índice - m = re_idx_nome.match(linha_stripped) - if m: - _flush_index() - idx_nome_atual = m.group(1) - idx_tipo_atual = m.group(2) - idx_colunas = [] - continue - # Coluna do índice atual - if idx_nome_atual: - m = re_idx_col.match(linha) - if m: - idx_colunas.append(m.group(1)) - - # Flush da última tabela - _flush_index() - _flush_tabela() - - return "\n".join(partes) - - -# --------------------------------------------------------------------------- -# Chamada ao Schema Crawler CLI -# --------------------------------------------------------------------------- - -def _rodar_schemacrawler( - db_path: str, - dialeto: str, - sc_bin: str, -) -> str: - """ - Executa o Schema Crawler via subprocess e retorna o texto do schema já - convertido para o formato canônico do pipeline. - - Args: - db_path: Caminho do banco de dados - dialeto: 'sqlite' | 'duckdb' | 'postgresql' - sc_bin: Caminho para schemacrawler.sh - - Returns: - str: Schema no formato canônico - """ - dialeto_config = _SC_DIALETOS.get(dialeto) - if not dialeto_config: - raise ValueError(f"Dialeto não suportado pelo Schema Crawler: {dialeto}") - - args_dialeto = dialeto_config["args"](db_path) - cmd = [ - sc_bin, - *args_dialeto, - "--info-level=detailed", - "--command=schema", - "--output-format=text", - "--no-info", - "-schemacrawler.format.hide_weakassociations=false", # mostra as FKs mesmo que não estejam mapeadas como FK no banco - "-schemacrawler.format.hide_weakassociation_names=false", # mostra o nome das FKs mesmo que sejam weak - ] - - print(f"[SCHEMA] Executando Schema Crawler ({dialeto})...") - result = subprocess.run( - cmd, - capture_output=True, - text=True, - timeout=90, - ) - - if result.returncode != 0: - raise RuntimeError( - f"Schema Crawler falhou (código {result.returncode}):\n" - f"{result.stderr[:800]}" - ) - - return _parsear_texto_schemacrawler(result.stdout) - - -# --------------------------------------------------------------------------- -# Introspecção SQLite nativa (fallback) -# --------------------------------------------------------------------------- - -def _formatar_schema_sqlite(conn: sqlite3.Connection) -> str: - """ - Constrói representação textual do schema via PRAGMA SQLite. - Formato compatível com enrich_schema.py e SchemaGraphRAG. - """ - cursor = conn.cursor() - cursor.execute( - """ - SELECT name FROM sqlite_master - WHERE type = 'table' AND name NOT LIKE 'sqlite_%' - ORDER BY name - """ - ) - tabelas = [row[0] for row in cursor.fetchall()] - - partes = ["=== SCHEMA SQLITE (INTROSPECCAO REAL) ===", ""] - - if not tabelas: - partes.append("Nenhuma tabela encontrada no banco.") - return "\n".join(partes) - - for tabela in tabelas: - partes.append(f"Tabela: {tabela}") - tabela_segura = tabela.replace("'", "''") - - cursor.execute(f"PRAGMA table_info('{tabela_segura}')") - colunas = cursor.fetchall() - if colunas: - for col in colunas: - _, nome, tipo, notnull, default, pk = col - flags = [] - if pk: - flags.append("PK") - if notnull: - flags.append("NOT NULL") - if default is not None: - flags.append(f"DEFAULT={default}") - sufixo = f" ({', '.join(flags)})" if flags else "" - partes.append(f"- {nome}: {tipo}{sufixo}") - else: - partes.append("- [sem colunas detectadas]") - - cursor.execute(f"PRAGMA foreign_key_list('{tabela_segura}')") - fks = cursor.fetchall() - if fks: - partes.append(" Foreign keys:") - for fk in fks: - _, _, tabela_ref, col_origem, col_destino, on_upd, on_del, _ = fk - partes.append( - f" - {col_origem} -> {tabela_ref}.{col_destino} " - f"(on_update={on_upd}, on_delete={on_del})" - ) - - partes.append("") - - return "\n".join(partes) - - - -# --------------------------------------------------------------------------- -# Introspecção PostgreSQL nativa (fallback sem Schema Crawler) -# --------------------------------------------------------------------------- - - -def _introspeccao_nativa(dialeto: str, caminho_db: Path) -> str: - """Abre conexão e roteia para o formatador de schema nativo do dialeto.""" - - if dialeto == "sqlite": - conn = sqlite3.connect(f"file:{caminho_db}?mode=ro", uri=True) - with conn: - return _formatar_schema_sqlite(conn) - - # duckdb e qualquer outro dialeto sem introspecção nativa: sem fallback - # seguro (abrir um arquivo .duckdb com o driver sqlite3 falha ou pode dar - # um resultado incorreto silenciosamente). - raise RuntimeError( - f"Dialeto '{dialeto}' não possui introspecção nativa disponível " - "(apenas sqlite). Configure schemacrawler_bin " - "para este dialeto." - ) - def _formatar_schema_sqlalchemy(engine) -> str: from sqlalchemy import inspect @@ -422,6 +45,8 @@ def _formatar_schema_sqlalchemy(engine) -> str: flags.append("PK") if not col.get("nullable", True): flags.append("NOT NULL") + if col.get("default") is not None: + flags.append(f"DEFAULT={col['default']}") sufixo = f" ({', '.join(flags)})" if flags else "" partes.append(f"- {col['name']}: {col['type']}{sufixo}") else: @@ -585,23 +210,24 @@ def _inferir_fks_virtuais(schema_canonico: str) -> str: # Nó do grafo # --------------------------------------------------------------------------- -def nos_nodo_esquema(estado: EstadoTextToInsight, engine: Any = None) -> dict: +def nos_nodo_esquema( + estado: EstadoTextToInsight, + engine: Any, + enrich_rag: bool = False, + cache_dir: str | Path | None = None, +) -> dict: """ - Nó Schema: busca metadados do banco de dados e popula contexto_schema. + Nó Schema: lê os metadados do banco pela Engine SQLAlchemy injetada e + popula `contexto_schema`. - Fluxo: - 1. Se uma Engine SQLAlchemy foi injetada pelo chamador (`engine`), usa ela - diretamente — o dialeto vem de `engine.dialect.name`, sem tocar em - db_path/db_url do estado. - 2. Caso contrário, valida db_path, verifica cache enriquecido, tenta - Schema Crawler e por fim PRAGMA SQLite nativo. - - O formato de saída é sempre compatível com enrich_schema.py e - SchemaGraphRAG, independentemente da fonte de introspecção. + O dialeto vem de `engine.dialect.name`. Com `enrich_rag` ligado, se este + schema já foi enriquecido antes, o texto enriquecido do cache é usado e + `tem_descricao` volta True, o que faz o grafo pular o enriquecimento. + Com `enrich_rag` desligado o cache não é lido, para que uma execução sem + enriquecimento nunca receba descrições geradas por uma execução anterior. Campos lidos do estado: - db_path (str): Caminho do banco de dados (obrigatório) - schemacrawler_bin (str): Path para schemacrawler.sh (opcional) + inferir_fks_virtuais (bool) Campos escritos no estado: contexto_schema (str) @@ -609,122 +235,30 @@ def nos_nodo_esquema(estado: EstadoTextToInsight, engine: Any = None) -> dict: status (str) tem_descricao (bool) """ - if engine is not None: - try: - contexto = _formatar_schema_sqlalchemy(engine) - except Exception as e: - msg = f"Falha ao ler schema via engine: {e}" - print(f"[SCHEMA] Erro: {msg}") - return {"contexto_schema": "", "erro_execucao": msg, "status": "exec_erro"} - - if estado.get("inferir_fks_virtuais", False): - print("[SCHEMA] Inferindo FKs virtuais.") - contexto = _inferir_fks_virtuais(contexto) - - return { - "contexto_schema": contexto, - "erro_execucao": "", - "status": "schema_obtido", - "tem_descricao": False, - } - - db_url = estado.get("db_url", "").strip() - if db_url: - from .code_agent.code_sql import _criar_engine_de_url - - try: - engine = _criar_engine_de_url(db_url) - try: - contexto = _formatar_schema_sqlalchemy(engine) - finally: - engine.dispose() - except Exception as e: - msg = f"Falha ao ler schema via db_url: {e}" - print(f"[SCHEMA] Erro: {msg}") - return {"contexto_schema": "", "erro_execucao": msg, "status": "exec_erro"} - - if estado.get("inferir_fks_virtuais", False): - print("[SCHEMA] Inferindo FKs virtuais.") - contexto = _inferir_fks_virtuais(contexto) + try: + contexto = _formatar_schema_sqlalchemy(engine) + except Exception as e: + msg = f"Falha ao ler schema via engine: {e}" + print(f"[SCHEMA] Erro: {msg}") + return {"contexto_schema": "", "erro_execucao": msg, "status": "exec_erro"} + + if estado.get("inferir_fks_virtuais", False): + print("[SCHEMA] Inferindo FKs virtuais.") + contexto = _inferir_fks_virtuais(contexto) + enriquecido = ler_schema_enriquecido(cache_dir, contexto) if enrich_rag else None + if enriquecido is not None: + print("[SCHEMA] Schema enriquecido encontrado no cache.") return { - "contexto_schema": contexto, + "contexto_schema": enriquecido, "erro_execucao": "", "status": "schema_obtido", - "tem_descricao": False, + "tem_descricao": True, } - db_path = estado.get("db_path", "").strip() - sc_bin = estado.get("schemacrawler_bin", "").strip() - usar_schemacrawler = estado.get("usar_schemacrawler", False) - inferir_fks_virtuais = estado.get("inferir_fks_virtuais", False) - dialeto = _detectar_dialeto(db_path) - - # --- Validação --- - caminho_db: Path | None = None - - if dialeto in ("sqlite", "duckdb"): - if not db_path: - msg = "db_path não informado no estado." - print(f"[SCHEMA] Erro: {msg}") - return {"contexto_schema": "", "erro_execucao": msg, "status": "exec_erro"} - caminho_db = Path(db_path) - if not caminho_db.exists(): - msg = f"Arquivo de banco não encontrado: {db_path}" - print(f"[SCHEMA] Erro: {msg}") - return {"contexto_schema": "", "erro_execucao": msg, "status": "exec_erro"} - - # --- Cache enriquecido (apenas bancos locais por enquanto) --- - if caminho_db is not None: - cache_path = caminho_db.with_name(f"{caminho_db.stem}_{dialeto}_enriched_schema.txt") - cache_legado = caminho_db.with_name(f"{caminho_db.stem}_enriched_schema.txt") - - for cache in (cache_path, cache_legado): - if cache.exists(): - print(f"[SCHEMA] Cache enriquecido encontrado: {cache.name}") - return { - "contexto_schema": cache.read_text(encoding="utf-8"), - "erro_execucao": "", - "status": "schema_obtido", - "tem_descricao": True, - } - - # --- Introspecção --- - contexto: str - - sc_disponivel = bool(sc_bin) and Path(sc_bin).exists() - - if usar_schemacrawler and sc_disponivel: - try: - contexto = _rodar_schemacrawler(db_path, dialeto, sc_bin) - print("[SCHEMA] Schema Crawler: introspecção concluída.") - except Exception as e: - print(f"[SCHEMA] Schema Crawler falhou ({e}). Tentando fallback nativo...") - try: - contexto = _introspeccao_nativa(dialeto, caminho_db) - except Exception as e2: - msg = f"Falha na introspecção nativa (dialeto '{dialeto}'): {e2}" - print(f"[SCHEMA] Erro: {msg}") - return {"contexto_schema": "", "erro_execucao": msg, "status": "exec_erro"} - else: - if not usar_schemacrawler: - print(f"[SCHEMA] usar_schemacrawler desativado — usando introspecção nativa ({dialeto}).") - else: - print(f"[SCHEMA] schemacrawler_bin não configurado — usando introspecção nativa ({dialeto}).") - try: - contexto = _introspeccao_nativa(dialeto, caminho_db) - except Exception as e: - msg = f"Falha na introspecção nativa (dialeto '{dialeto}'): {e}" - print(f"[SCHEMA] Erro: {msg}") - return {"contexto_schema": "", "erro_execucao": msg, "status": "exec_erro"} - - # --- Heurística de FKs virtuais --- - if inferir_fks_virtuais: - print("[SCHEMA] Inferindo FKs virtuais.") - contexto = _inferir_fks_virtuais(contexto) return { "contexto_schema": contexto, "erro_execucao": "", "status": "schema_obtido", "tem_descricao": False, - } \ No newline at end of file + } diff --git a/text_to_insight/retriever/engine.py b/text_to_insight/retriever/engine.py index 96303be..1c4e4f6 100644 --- a/text_to_insight/retriever/engine.py +++ b/text_to_insight/retriever/engine.py @@ -4,25 +4,19 @@ from .rag_logic import RAGRetriever from pathlib import Path import chromadb + +from ..cache import diretorio_chroma #aqui vamos ter a integração da lógica do grafo com a lógica do RAG #a ideia é que o RAG seja responsável por recuperar as informações relevantes para responder às perguntas, usando o grafo como guia para navegar pelas relações entre os dados -BASE_DIR = Path(__file__).resolve().parent - -@lru_cache(maxsize=4) -def get_chroma_client(path: Path | str | None = None): - target = Path(path) if path else (BASE_DIR / "chroma_db") - target.mkdir(parents=True, exist_ok=True) - return chromadb.PersistentClient(path=str(target)) - class SchemaGraphRAG: - def __init__(self, schema: dict = None): + def __init__(self, schema: dict = None, cache_dir: str | Path | None = None): #definição do grafo após o get do schema if schema: schema_string = schema.get("contexto_schema", "") schema_hash = hashlib.md5(schema_string.encode('utf-8')).hexdigest() collection_name = f"schema_{schema_hash}" - chroma_client = get_chroma_client() + chroma_client = chromadb.PersistentClient(path=str(diretorio_chroma(cache_dir))) self.schema_graph = SchemaGraph(schema = schema_string) self.rag = RAGRetriever(chroma_client = chroma_client, document_schema = schema, collection_name =collection_name) diff --git a/text_to_insight/retriever/graph_logic.py b/text_to_insight/retriever/graph_logic.py index c19206b..7e692dd 100644 --- a/text_to_insight/retriever/graph_logic.py +++ b/text_to_insight/retriever/graph_logic.py @@ -39,7 +39,7 @@ def _add_schema(self, schema: str): parent_col=col_destino ) - #Se não houver FK, roda SchemaCrawler ou qualquer outra técnica (Isso aqui é discutível, provavelmente deveriamso passar o SC para um nó antes do RAG) + #Se não houver FK, a inferência de FKs virtuais (inferir_fks_virtuais) é que cria as arestas def get_schema(self, table_name: str) -> str | None: """ diff --git a/text_to_insight/runtime.py b/text_to_insight/runtime.py index 4a9c1ab..74acf7a 100644 --- a/text_to_insight/runtime.py +++ b/text_to_insight/runtime.py @@ -9,7 +9,6 @@ from typing import Any, Callable from dotenv import load_dotenv load_dotenv() -import os from tabulate import tabulate from .utils import salvar_metricas_csv @@ -43,10 +42,7 @@ def construir_estado_inicial( pergunta: str, - db_path: str, inferir_fks_virtuais: bool = False, - usar_schemacrawler: bool = False, - db_url: str = "", ) -> dict[str, Any]: """Cria o estado inicial padrão para uma execução do grafo.""" return { @@ -60,39 +56,16 @@ def construir_estado_inicial( "historico_conversa": [], "status": "iniciado", "tentativas_loop": 0, - "db_path": db_path, - "db_url": db_url, "espera_humana": False, "linhas_resultado_completo": [], "historico_tentativas": [], "cache_data_exploration": {}, "ultimo_prompt": "", - "schemacrawler_bin": os.getenv("SCHEMACRAWLER_BIN", ""), "inferir_fks_virtuais": inferir_fks_virtuais, - "usar_schemacrawler": usar_schemacrawler, "tokens_by_node": {}, } -_URL_SENHA_REGEX = re.compile(r"(://[^:/@\s]+:)[^@\s]+(@)") - - -def _redigir_credenciais(estado: dict[str, Any]) -> dict[str, Any]: - """ - Devolve uma copia rasa do estado com senha de `db_url` - mascaradas. Usar sempre antes de devolver o estado final ao chamador - (biblioteca) ou de persisti-lo fora do checkpointer do grafo — o estado - bruto guarda a senha em texto puro, e nao deve vazar pra fora do grafo. - """ - estado_seguro = dict(estado) - - db_url = estado_seguro.get("db_url") - if db_url: - estado_seguro["db_url"] = _URL_SENHA_REGEX.sub(r"\1***\2", db_url) - - return estado_seguro - - def _montar_saida_resultado_terminal(resultado: dict[str, Any]) -> str: """Monta o texto do bloco de resultado para exibição no terminal.""" linhas = resultado.get("linhas_resultado_completo", []) or [] @@ -423,7 +396,7 @@ def _resultado_aguardando_usuario(snapshot_values: dict[str, Any], thread_id: st def _resultado_hitl_bloqueado(snapshot_values: dict[str, Any]) -> dict[str, Any]: - resultado_final = _redigir_credenciais(snapshot_values) + resultado_final = dict(snapshot_values) resultado_final.update( { "status": HITL_BLOCKED_STATUS, @@ -501,7 +474,7 @@ def executar_fluxo( snapshot = grafo_app.get_state(config) if not snapshot.next: - resultado_final = _redigir_credenciais(snapshot.values) + resultado_final = dict(snapshot.values) salvar_metricas_csv(resultado_final, time.perf_counter() - lat_inicio) return resultado_final diff --git a/text_to_insight/state.py b/text_to_insight/state.py index 96c0d33..52afbbb 100644 --- a/text_to_insight/state.py +++ b/text_to_insight/state.py @@ -28,11 +28,11 @@ # Criação de classe mãe que será estendida para EstadoTextToInsight para que -# pergunta_original/pergunta_atual e db_path sejam obrigatorios +# pergunta_original/pergunta_atual sejam obrigatorios. O banco não fica no +# estado: a Engine SQLAlchemy do chamador é injetada direto nos nós. class EstadoEntrada(TypedDict): pergunta_original: str pergunta_atual: str - db_path: str class EstadoTextToInsight(EstadoEntrada, total = False): @@ -42,10 +42,9 @@ class EstadoTextToInsight(EstadoEntrada, total = False): Campos obrigatórios (via EstadoEntrada): - pergunta_original: pergunta inicial do usuario (imutavel apos o primeiro set). - pergunta_atual: pergunta corrente, fonte de verdade para o fluxo. - - db_path: caminho para o arquivo SQLite (.db). Campos opcionais (preenchidos progressivamente pelos nós): - - contexto_schema: schema textual extraído do SQLite. + - contexto_schema: schema textual extraído do banco. - sql_gerada: SQL produzida pelo agente de código. - linhas_resultado_preview: amostra de linhas retornadas (max 30). - total_linhas_resultado: total de linhas do resultado SQL. @@ -77,10 +76,7 @@ class EstadoTextToInsight(EstadoEntrada, total = False): resposta_natural: str historico_tentativas: Annotated[list[dict[str, str]], operator.add] linhas_resultado_completo: list[dict[str, Any]] - schemacrawler_bin : str | None - db_url: str inferir_fks_virtuais: bool - usar_schemacrawler: bool # Campos para geração de gráficos caminho_csv_resultado: str diff --git a/uv.lock b/uv.lock index 8056d8a..bc471bd 100644 --- a/uv.lock +++ b/uv.lock @@ -555,7 +555,7 @@ name = "coloredlogs" version = "15.0.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "humanfriendly" }, + { name = "humanfriendly", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/cc/c7/eed8f27100517e8c0e6b923d5f0845d0cb99763da6fdee00478f91db7325/coloredlogs-15.0.1.tar.gz", hash = "sha256:7c991aa71a4577af2f82600d8f8f3a89f936baeaf9b50a9c197da014e5bf16b0", size = 278520, upload-time = "2021-06-11T10:22:45.202Z" } wheels = [ @@ -570,7 +570,7 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/66/54/eb9bfc647b19f2009dd5c7f5ec51c4e6ca831725f1aea7a993034f483147/contourpy-1.3.2.tar.gz", hash = "sha256:b6945942715a034c671b7fc54f9588126b0b8bf23db2696e3ca8328f3ff0ab54", size = 13466130, upload-time = "2025-04-15T17:47:53.79Z" } wheels = [ @@ -651,7 +651,7 @@ resolution-markers = [ "python_full_version == '3.11.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" } wheels = [ @@ -973,7 +973,7 @@ name = "exceptiongroup" version = "1.3.1" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "typing-extensions" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/50/79/66800aadf48771f6b62f7eb014e352e5d06856655206165d775e675a02c9/exceptiongroup-1.3.1.tar.gz", hash = "sha256:8b412432c6055b0b7d14c310000ae93352ed6754f70fa8f7c34141f91c4e3219", size = 30371, upload-time = "2025-11-21T23:01:54.787Z" } wheels = [ @@ -1267,14 +1267,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/a7/4f/4af258e1ce388eb64be82d6466b7d0b3bc3eede154e14c3360a76a759b71/greenlet-3.5.6-cp310-cp310-macosx_11_0_universal2.whl", hash = "sha256:95e7c44d072db623a1aab04ce488cf9533294a77ed9d072cd503a3596f4106ac", size = 292967, upload-time = "2026-09-14T14:26:34.475Z" }, { url = "https://files.pythonhosted.org/packages/1d/05/dc0d54e90af2f192724936799cee990687792ff54a4638d3ae0e0a0145c0/greenlet-3.5.6-cp310-cp310-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b7d501d5eb5d4f67207df364752ad697465b834268744be7581c18d81d35d41d", size = 609284, upload-time = "2026-09-14T15:11:58.49Z" }, { url = "https://files.pythonhosted.org/packages/c1/51/826b4fe7bc39c3f910c95e889a981c827f72a611fc035f31816a256cf043/greenlet-3.5.6-cp310-cp310-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a364c1ea75dc51b83a17f52fe0c79cf8bc4ddf740403bebd4581c7666eea017d", size = 622648, upload-time = "2026-09-14T15:20:39.198Z" }, + { url = "https://files.pythonhosted.org/packages/55/3b/f2d36fc38934588dff6d6ec9288934c9611abac7a79c866c2002fc707698/greenlet-3.5.6-cp310-cp310-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5599b380c1f28efeb724e81569eac80cd92f99a85bd9775456caaf3225d40b11", size = 629557, upload-time = "2026-09-14T15:25:03.036Z" }, { url = "https://files.pythonhosted.org/packages/94/5c/092682ae7ca1aadd44aa36b0bc35c48c9ed55f9ffebb5794980b1e2ae74b/greenlet-3.5.6-cp310-cp310-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eed88b64a5e5da72d6a71cdc5aaeefaa5ced9b748f8d19f89800b339961dad39", size = 622813, upload-time = "2026-09-14T14:35:54.845Z" }, + { url = "https://files.pythonhosted.org/packages/d6/f6/4167f0e44e795840cbc219b2e5d8f576492192cd9e3e17e827db20287daa/greenlet-3.5.6-cp310-cp310-manylinux_2_39_riscv64.whl", hash = "sha256:5bbda3c70dd35d60671bc33b01916802707a052130d9e50cdb871d34594d35cb", size = 425482, upload-time = "2026-09-14T15:28:34.144Z" }, { url = "https://files.pythonhosted.org/packages/07/59/9c6b723a559b53bee0980a5dc57577d434891dd454f0fe54ed6e22d4e4ce/greenlet-3.5.6-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:874cea8bb1ec1ddccbacbd027856f6bf496f6bc18aba97a918c20e067edab236", size = 1585817, upload-time = "2026-09-14T15:10:03.922Z" }, { url = "https://files.pythonhosted.org/packages/de/d4/2bceaa305ff0ecf99511480da8f0a866eb2469a68da8715008a0d3e8f65f/greenlet-3.5.6-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:128813fc29f2336a21b4d06eedd5e16bcc7ea46f59e9ff1cb30ea70e48195d88", size = 1650177, upload-time = "2026-09-14T14:35:46.736Z" }, { url = "https://files.pythonhosted.org/packages/7a/33/c57855a6abada0c7bfb9c6c0f33df1fbed8e5224708478dbcdff6c5db490/greenlet-3.5.6-cp310-cp310-win_amd64.whl", hash = "sha256:dad3d233d441a022c1f7155f0fb9d5aff7b97c1ea8c7dfa02cce586b16ab2d0b", size = 322896, upload-time = "2026-09-14T14:24:52.308Z" }, { url = "https://files.pythonhosted.org/packages/f1/d7/41511ee2696f14be4200b524d9553dc4295e2bdeb20aa8962c3cb25e71c6/greenlet-3.5.6-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:a6a4b98a9132e0f45c9fc245a63894cfd8c45fb7a0d6bffc5eab3ec327cf7324", size = 294075, upload-time = "2026-09-14T14:25:16.922Z" }, { url = "https://files.pythonhosted.org/packages/f8/7b/b509624970909294cd064ff7346148ca9941c21bec9026d7873dd254e9fa/greenlet-3.5.6-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45bfd2b51e38aaa5f9849f114d9c7c1d75f69187c849b3549cd64c465283abfa", size = 613429, upload-time = "2026-09-14T15:12:00.454Z" }, { url = "https://files.pythonhosted.org/packages/2b/5c/d2eb503067f9ba20875ef8c87681f29a64f53bbbbe4059a5d7c53179d442/greenlet-3.5.6-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3c6dede9133e1da41d561bc3fb14e92b47e2ce39ae60edefaad145658ea7c5e2", size = 625405, upload-time = "2026-09-14T15:20:41.053Z" }, + { url = "https://files.pythonhosted.org/packages/1b/24/9b071d11c8bb9f5f38cccacc38fcc234d91997a4c395cc2bf43ecae89642/greenlet-3.5.6-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4fb8e59f68845d56c23c031dcd79c329f345e4a9d2ffac91c3d1ab366bdc457b", size = 633270, upload-time = "2026-09-14T15:25:04.864Z" }, { url = "https://files.pythonhosted.org/packages/ec/d3/63d4477ce31dff2fd802a9a20240f6606aac85977e0fb18443aae33de3f6/greenlet-3.5.6-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1c20ea32a73d17b9b60e3371240e17b0068120c98a5ec01a224a7dd8c89733ba", size = 624428, upload-time = "2026-09-14T14:35:56.895Z" }, + { url = "https://files.pythonhosted.org/packages/88/17/ac11883ecc9da19c681c8b763ee39e6f7dca2aa81874eb11a075d3cbeb00/greenlet-3.5.6-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:d701eab36200c36224833d07dbdb709adb7fd4253429548ddb5e547b8ed40586", size = 428068, upload-time = "2026-09-14T15:28:35.872Z" }, { url = "https://files.pythonhosted.org/packages/ad/aa/9cde4e00688eaa2a03b91d12e4681439a87e6aad860399e0847af6a014ca/greenlet-3.5.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5a0b2791239c99992a86c1b635b787fe2a877d9eaaa26f8891ce943832b585ae", size = 1588385, upload-time = "2026-09-14T15:10:05.386Z" }, { url = "https://files.pythonhosted.org/packages/5c/01/24632b5ec186b64e21e07a8f53ce5e15a7e9cb33eddee99a5fe16379afa5/greenlet-3.5.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:188bf333769b7145e2b0b4a7f09615ec550ed44d3a2a8395fb7b36f0e9901e13", size = 1653119, upload-time = "2026-09-14T14:35:48.275Z" }, { url = "https://files.pythonhosted.org/packages/ce/6c/019d2ef898f4b9ac845167f1c6f73229e9a4e2439362a5e2ce50205a19b0/greenlet-3.5.6-cp311-cp311-win_amd64.whl", hash = "sha256:a6b4ff33f7e011bbaa148238d131c4fd4f8afbab3c104ddfbdb2b12b74ff7016", size = 323317, upload-time = "2026-09-14T14:22:38.836Z" }, @@ -1282,7 +1286,9 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/72/18/3fc6d951466ae9a2a688edcddde3b2e388da0a8244e0caf7117bbeb0eb95/greenlet-3.5.6-cp312-cp312-macosx_11_0_universal2.whl", hash = "sha256:a5876d0a60355af98d535c47f6cd6eb0f8a432396dab26845d380b92f8412422", size = 295668, upload-time = "2026-09-14T14:22:33.241Z" }, { url = "https://files.pythonhosted.org/packages/27/89/366d2af5061eeefa5012f510d95a99c8620dcc457609838db4d538820318/greenlet-3.5.6-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e85880b538e59a59f55117b81f208a6660ad5ac328aad9305f812d9b8bc67a0f", size = 611700, upload-time = "2026-09-14T15:12:01.962Z" }, { url = "https://files.pythonhosted.org/packages/54/1c/07f133f865fd58ae593dd2bbec3144acaee9b04ffe2eb48c6e121747ceef/greenlet-3.5.6-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f0ba7c2a329d650628f4c8572fd1db29f0a59dd70a3e3e0710dcf18a35cce9d8", size = 624223, upload-time = "2026-09-14T15:20:42.459Z" }, + { url = "https://files.pythonhosted.org/packages/a7/f2/844dc823ff2752ad049caa6b59d57e4572f9c445934b02d3518f4c67197c/greenlet-3.5.6-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:ee7d9da3bf493909cf811a3f038840cb34fab5ae2956b8a263919f6e289ab188", size = 629529, upload-time = "2026-09-14T15:25:06.354Z" }, { url = "https://files.pythonhosted.org/packages/66/6a/1594f3869c57c149abdb380492529e04d4c0229b5e4d79572c5bd0aaa673/greenlet-3.5.6-cp312-cp312-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:975736b002ed080d124cf81a79cb7e05cb26d6b3f5c7a7b651c0fcce70353aa1", size = 621404, upload-time = "2026-09-14T14:35:59.027Z" }, + { url = "https://files.pythonhosted.org/packages/c0/42/b1f8dbc89a53b9e77859fc1ad1627d106fc361daa3ea4bdf43a91ebb4338/greenlet-3.5.6-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:71890d5247020c25c21a6b65202782bfc281d4e6e244842419d30e3492bb6dcc", size = 432385, upload-time = "2026-09-14T15:28:37.369Z" }, { url = "https://files.pythonhosted.org/packages/a2/f5/33e5c9e48178b9259fd000f8f45caa4a65036f65d3d0c06a602f570f025d/greenlet-3.5.6-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:0616b8f878098c5681fd8f0dc92d887551717402342a70f0abcbfea5f5ad8a44", size = 1584998, upload-time = "2026-09-14T15:10:06.653Z" }, { url = "https://files.pythonhosted.org/packages/ef/31/9b4e140bc24d0ad7927ebd651f5608b0acc2334d061748c3b6ad19085cfa/greenlet-3.5.6-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3dbb4596a6a4e5d47121a33ff20533a81e60f302d9e67b69909a8bc21a43f0a7", size = 1647568, upload-time = "2026-09-14T14:35:49.787Z" }, { url = "https://files.pythonhosted.org/packages/c3/71/d79f1791f824f8ff15c2978746640467ae932a2365e0201069f7f272395f/greenlet-3.5.6-cp312-cp312-win_amd64.whl", hash = "sha256:7ac4abb3877c43af320392c664774eef6fa2cc063c79a55fc02d844a3cbe7395", size = 324203, upload-time = "2026-09-14T14:22:54.504Z" }, @@ -1290,7 +1296,9 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/a1/e720a38852366c589e1a46cf570b886507ad2cf591050c203365638baab0/greenlet-3.5.6-cp313-cp313-macosx_11_0_universal2.whl", hash = "sha256:f96f0e30b5a95c7631b12bfe214cbc90ec8fe8cfa36920596c10514a65743519", size = 294627, upload-time = "2026-09-14T14:24:40.102Z" }, { url = "https://files.pythonhosted.org/packages/eb/c3/58187858df41354a11e6a55b421e7af9059798abdab3a384cc51b8567c38/greenlet-3.5.6-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c75116c9de79949de23006e2d9b35ee82874c594fcf5c0311b439acaa14b8441", size = 614356, upload-time = "2026-09-14T15:12:03.399Z" }, { url = "https://files.pythonhosted.org/packages/ce/b9/3a7e67d5f05c9760b1ad411fa52264bd69cc08e22a2ebfb4018b90628ced/greenlet-3.5.6-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:cad5782f93f7f738b62c6527b6f32a60694d924029f299a8b524758cfa53d815", size = 626756, upload-time = "2026-09-14T15:20:44.269Z" }, + { url = "https://files.pythonhosted.org/packages/c6/7c/40400455f5b5a65bb83e94fde66d1be9e5ec518638113f8083ace746c309/greenlet-3.5.6-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a93ee7c6e8fd0f8a83525a51bd777be57ee17787e91d805bd8d6faf9dcada18e", size = 632632, upload-time = "2026-09-14T15:25:07.813Z" }, { url = "https://files.pythonhosted.org/packages/85/cb/ab0c123c514ed4e94c0dc9ee2e86362633e6b998cfc05de7fc9ac2eb9690/greenlet-3.5.6-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f98e8215e172f567ce80eeaed9107fb4d32b6c44f26983d9b8334658136a205a", size = 623779, upload-time = "2026-09-14T14:36:01.104Z" }, + { url = "https://files.pythonhosted.org/packages/f9/67/1f35cff30a6c51c3f23b63d4afcc7313ab4f97490ba3676fa78178984b27/greenlet-3.5.6-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:7f731ebac68ea06d628658295cb2d217b10186329fcf9a3b6a149045059bf92e", size = 434933, upload-time = "2026-09-14T15:28:38.858Z" }, { url = "https://files.pythonhosted.org/packages/a5/26/fda8a5a06e7073333ccb038133c5893b9e0c4fe29d5992a17e83c241bc6e/greenlet-3.5.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:df19e2d0b1620039af5102563fbd96e8938c7f5c3f5828528d641d9fc585525e", size = 1584930, upload-time = "2026-09-14T15:10:08.234Z" }, { url = "https://files.pythonhosted.org/packages/2f/37/50f8813163148d6234e08b23dcad6a9e37f01d148c8ec976e4c44ea2d918/greenlet-3.5.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:06c0e933290fba8ffe53ead4ae1b8044b0e9754b75cebf381aa2bc3e50d82fac", size = 1647590, upload-time = "2026-09-14T14:35:51.173Z" }, { url = "https://files.pythonhosted.org/packages/86/da/b7669b09586365654083a62bd0724cf06cb74bd5085a15cdd161271f992f/greenlet-3.5.6-cp313-cp313-win_amd64.whl", hash = "sha256:5b602b4201b965a8354d74e232364a66ff243dd142e350d035f46169bb36e13d", size = 324086, upload-time = "2026-09-14T14:23:48.428Z" }, @@ -1298,7 +1306,9 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/66/c0/d254544ae2b8bdd311aef000fafc02828c2771b17d994b3075620ea7cc6e/greenlet-3.5.6-cp314-cp314-macosx_11_0_universal2.whl", hash = "sha256:8cddea1b8339451c2fb3388e138347b6126744f33b611bdb55b7357361cfef46", size = 295221, upload-time = "2026-09-14T14:25:11.583Z" }, { url = "https://files.pythonhosted.org/packages/18/18/eb54be16b9cc3971e09ca5b73334e1b8c804a4630d9addaaf218a4fe300f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c59acfa8eb73a1e0d484392dc002bdf001fd4ce73394e0132df3d1ab6093d7cb", size = 660992, upload-time = "2026-09-14T15:12:04.876Z" }, { url = "https://files.pythonhosted.org/packages/8f/b4/e193efe65671dcf294bc51fcc59efb52d154adf8612c4ea016da0d2c486c/greenlet-3.5.6-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a3b4a01c6da07ef9f80d4fe8933b994bc99747bcea3eab0330a9c34d3c12655b", size = 673428, upload-time = "2026-09-14T15:20:45.756Z" }, + { url = "https://files.pythonhosted.org/packages/fd/21/631bb45fafde1dca782152377c0676d182ec924820064047f533a3627b28/greenlet-3.5.6-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:dd0b83bed3405b586a3133629f1d1a5bc7bfd64822a3b7ab342bdc68e6dbc61b", size = 677688, upload-time = "2026-09-14T15:25:09.279Z" }, { url = "https://files.pythonhosted.org/packages/45/ac/28fa7a9e50f2859466214c4ac584d776db52c1604ad4dd158960a5af2a1f/greenlet-3.5.6-cp314-cp314-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9a09d59bef1db94f384b5bcc2d523694d338f3df6b757aeeaf7baca5d0c0be88", size = 670773, upload-time = "2026-09-14T14:36:02.577Z" }, + { url = "https://files.pythonhosted.org/packages/40/30/2b0a73e68e1e18e30b601d0d183cfdfc2beca4de5a6843c630f0fc9fb90c/greenlet-3.5.6-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:fdacf26402389bdd89857ad3c045a26fe8f3314f9a8b28226f82f88463a65b77", size = 480475, upload-time = "2026-09-14T15:28:40.741Z" }, { url = "https://files.pythonhosted.org/packages/c3/cd/fb7d6cdd86ff3427c1494854f0e35437eba05142be91f530f6da75e09e19/greenlet-3.5.6-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:8b7c73d1cef3d9ae963e9ff03f6222df43efbb9054ffd2f1969c935b7fc84c02", size = 1631900, upload-time = "2026-09-14T15:10:09.745Z" }, { url = "https://files.pythonhosted.org/packages/f6/40/143bdbb20a516628cb15074ae52ed17d850b450292609c7a6fccac6dbece/greenlet-3.5.6-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:8b27df301f56e3b3d2298095c8f7d6b68f2521f6b1693e901fa039bdbae34424", size = 1693740, upload-time = "2026-09-14T14:35:52.959Z" }, { url = "https://files.pythonhosted.org/packages/c9/9e/019642432e6ae283301df1361227d47610709d2dc69a38f95edef266d713/greenlet-3.5.6-cp314-cp314-win_amd64.whl", hash = "sha256:f8f0bd690e1a41294ac87905e8121c81a3761ec2583c768f13467428606c8c7a", size = 327473, upload-time = "2026-09-14T14:28:12.948Z" }, @@ -1306,14 +1316,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/14/7e/7a205688a5b3074933b18a906608d46d106e9a79d776bdab5a4abf4b4feb/greenlet-3.5.6-cp314-cp314t-macosx_11_0_universal2.whl", hash = "sha256:97c5a53e8c1754df58e73f047a99e287d4da1bdfe64b0072fb25c87000897951", size = 305352, upload-time = "2026-09-14T14:21:31.962Z" }, { url = "https://files.pythonhosted.org/packages/78/cb/9c4a57a9d9dd0256e20b8f7f4f06554c2c92badebf0ab73ce344321b78b9/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:fea4427d1ffdb3b523d7daa6712038428a4c16c450b9777bdd1221cfee0eab49", size = 672671, upload-time = "2026-09-14T15:12:06.347Z" }, { url = "https://files.pythonhosted.org/packages/97/52/c6729681ebbd298f4decd28746815acc8a0b0a0fde21d2df33776fd4d042/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:73a29b5ba642e35433166a03a3e02935e7238c4b3467fbd77523b99edea23e5b", size = 679489, upload-time = "2026-09-14T15:20:47.291Z" }, + { url = "https://files.pythonhosted.org/packages/71/76/3c11c21e0716b1f1dc7c1a4b3d690abb1d3b448c69a9d32049fecb64010a/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:61a61b4a95a4f97922c3a6f5606d3e360851584bd47e500a5161373c53810e3d", size = 681303, upload-time = "2026-09-14T15:25:11.088Z" }, { url = "https://files.pythonhosted.org/packages/58/c5/2b6c721ba8b8963da42d5a0f57f25b8aaeb1fe9bdd156875e57f3be648a2/greenlet-3.5.6-cp314-cp314t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:460e70b033aba8ed47e2ac9b5d0d2157b05a34fbfa30a241400aef4118902cdc", size = 676608, upload-time = "2026-09-14T14:36:03.959Z" }, + { url = "https://files.pythonhosted.org/packages/3f/26/3ae402202452cd5941bbbd483e5a74297e2397e7aa3182c2a5e3ab7d5666/greenlet-3.5.6-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:fe3170a69fe039b18ad18171e66faa9a75f6fe9d78f968fd9b54e09fbd714d81", size = 510112, upload-time = "2026-09-14T15:28:42.112Z" }, { url = "https://files.pythonhosted.org/packages/b2/04/0d018e0d05bcdde19a0fcb907834155f1fc853a9bedd3f3f5e6acadcae19/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:ca80a49b53ed1d22f7282da7255f7bb2fd1935fd0f623d8613fda38745f18961", size = 1641479, upload-time = "2026-09-14T15:10:11.216Z" }, { url = "https://files.pythonhosted.org/packages/59/bb/f02ef9073919158f6403fe3701d4ed4403d646720e7201dfc6e9d264bac3/greenlet-3.5.6-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:916f92f2a8db10508f739d0b5e00b83defe5d1115a997c54532a6d7cf8c95404", size = 1698758, upload-time = "2026-09-14T14:35:54.336Z" }, { url = "https://files.pythonhosted.org/packages/08/a5/1f48fe647473a2dcccfd1839b2ff2c78eb57009be776b4da071e901c9bff/greenlet-3.5.6-cp314-cp314t-win_amd64.whl", hash = "sha256:886bcf1870af74c32bc310fd00a6b803445e17e51b7d5a107c7b35c0f362cc16", size = 331574, upload-time = "2026-09-14T14:27:18.451Z" }, { url = "https://files.pythonhosted.org/packages/cd/72/3882855a75838faeb54a58aeef4fd77d20b2a86d4bad570c70d41b565dcf/greenlet-3.5.6-cp315-cp315-macosx_11_0_universal2.whl", hash = "sha256:3ac3494c381dab876cad7d0b22f3a722f3e0c8deb3a65b9e7f35ad7f58b8fcb3", size = 295926, upload-time = "2026-09-14T14:27:21.16Z" }, { url = "https://files.pythonhosted.org/packages/10/1f/be4d957d8a9b90bcbe8db206548a42134d96222d43e5ed3fc4708fb6e24b/greenlet-3.5.6-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:602024dae6d77e161f4b89491b62ca1d4f19949d79d47b2db057e476d21179d6", size = 666910, upload-time = "2026-09-14T15:12:07.901Z" }, { url = "https://files.pythonhosted.org/packages/a1/af/60d62571a7d6de961e4ce7625d6c2faf359345659fc782d2cdf517c34577/greenlet-3.5.6-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f8e63209c3e1e828ee6a457529b4a6d8b05d050fe0ae03a7ae49e967c5d312e0", size = 677415, upload-time = "2026-09-14T15:20:48.817Z" }, + { url = "https://files.pythonhosted.org/packages/f5/41/b3114c97c10e796010f00a30f51c81470072bca4b53e396ccca87484fcf7/greenlet-3.5.6-cp315-cp315-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:9133d68624b1f2e89ec2f554d56aea8a5b0d7168cd9320200ba58d4d794845a4", size = 681337, upload-time = "2026-09-14T15:25:12.812Z" }, { url = "https://files.pythonhosted.org/packages/fb/16/ac9e547b611539aaed1870eb1d6ddc57abdd5924b3a99bb9b5f0b44176b8/greenlet-3.5.6-cp315-cp315-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ccadce0130fd813ec86ebfe969a6c58b42acc1d0fe55a47525375b740e07b605", size = 675927, upload-time = "2026-09-14T14:36:05.34Z" }, + { url = "https://files.pythonhosted.org/packages/48/1b/d41861c2fa00968e39e467a495ca8db9ce9b6310a5d9b57561b3d0dc48fa/greenlet-3.5.6-cp315-cp315-manylinux_2_39_riscv64.whl", hash = "sha256:5adcbbfe78bdc242c71740a02e0991cc1b2f34d33c8bb15ca45eee8fd1140942", size = 487339, upload-time = "2026-09-14T15:28:43.497Z" }, { url = "https://files.pythonhosted.org/packages/c4/b1/b7ba08d6431121741f1d30be0d5d292e76873325179a63586cd9217b62f6/greenlet-3.5.6-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:9297fb9c39b9a2c039dbcd306c410bd6906b95244dec3bba4318d36c718c164c", size = 1637236, upload-time = "2026-09-14T15:10:12.442Z" }, { url = "https://files.pythonhosted.org/packages/af/c5/3b1cbc68f0c082022fc8717f7fe4b8b13b8d583c52352be37f4e9f55bcd2/greenlet-3.5.6-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:b374e79ffa7511afc11773aef40a4ccea6191fba1c856ea2f9c56738dca69d7a", size = 1698526, upload-time = "2026-09-14T14:35:56.039Z" }, { url = "https://files.pythonhosted.org/packages/de/56/12941ed2711400451c89d544e10f831800a2770f19dd55eac8f0f7f2003b/greenlet-3.5.6-cp315-cp315-win_amd64.whl", hash = "sha256:7969bffa322c097bd46ae595ada6a931cefda613f18ba64587e9cff4cb320756", size = 327739, upload-time = "2026-09-14T14:23:55.768Z" }, @@ -1321,7 +1335,9 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/16/c2/86cfc5555a98e12b86966ddbd24fd39af32f71f2f785c6595b7feb2db156/greenlet-3.5.6-cp315-cp315t-macosx_11_0_universal2.whl", hash = "sha256:de3de000d459402cda015068fd135aa50c0bf6f2477a80d4da1e646f123b4e78", size = 306244, upload-time = "2026-09-14T14:27:57.565Z" }, { url = "https://files.pythonhosted.org/packages/14/6d/83ffc9d05a75a80ab3a7595dbb1d9604e5d4fc2996d73a8ae2dbd1284900/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:45663c01a4de48b9a64a2ee1509d92d1dfd3afb02b2ccfc9333029d11aef996a", size = 676578, upload-time = "2026-09-14T15:12:09.468Z" }, { url = "https://files.pythonhosted.org/packages/5d/d6/c2cf684810e5caded075970aaadea654ecb58b8382b9aecf1d231b936894/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3deccbb57a481e3a408fe61cdfd5c13e0678fc0a30fdd09597917ca87b4be877", size = 684203, upload-time = "2026-09-14T15:20:50.261Z" }, + { url = "https://files.pythonhosted.org/packages/f2/d1/039c353d5593a97a89699e989324c9bc86af499e6c6152fe0180f5742204/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:63aff70fe5aac59c72215f42ec39fcb59ff46774fa966e717f8ecb6ee2273577", size = 686023, upload-time = "2026-09-14T15:25:14.528Z" }, { url = "https://files.pythonhosted.org/packages/62/19/00e1bee5d2af890dc8f400b54d0b0f9b489965f92bc12b407ff72cc6f469/greenlet-3.5.6-cp315-cp315t-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:311018b46472fb26ee85870847fb89eb64cc8aaddb617400789d87076f7cfeec", size = 681253, upload-time = "2026-09-14T14:36:06.742Z" }, + { url = "https://files.pythonhosted.org/packages/8a/62/97ceb8e0b2ea96046cdf8e95b042715020ebb12d83ea0690db80a8f03d23/greenlet-3.5.6-cp315-cp315t-manylinux_2_39_riscv64.whl", hash = "sha256:520648db8fb92eef7b3e6013f5a6f901cdf0d6685f639c2f7a245879f865bef7", size = 517058, upload-time = "2026-09-14T15:28:44.924Z" }, { url = "https://files.pythonhosted.org/packages/89/58/c9275fd0ca195d1d3402931bcce8cfcc74726ff76efb1883d229e6e1a3d7/greenlet-3.5.6-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:7f924a5a9d5890649566f2f6682e0d8ad8ca23028bacffbbac36dbd7fd680176", size = 1645988, upload-time = "2026-09-14T15:10:13.758Z" }, { url = "https://files.pythonhosted.org/packages/e0/36/b35747582fa4f1a5453f8f3002405dbac788e450cec7674dc2d204b6ccb5/greenlet-3.5.6-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:de9923832f2d8c1a5ecd8d7260465a6ca5a86888a0d129e3bd5cf0406d2fc5bf", size = 1702383, upload-time = "2026-09-14T14:35:58.143Z" }, { url = "https://files.pythonhosted.org/packages/ed/69/6ec22ac9351e474d2a134d0ff9400dc80362d1c20f0721088ffffdfc205b/greenlet-3.5.6-cp315-cp315t-win_amd64.whl", hash = "sha256:2ab5f42ac6c238eb71770715e6e909ad9a1a92b6c681ccb64cd5a0f07edb953f", size = 331845, upload-time = "2026-09-14T14:27:41.723Z" }, @@ -1533,7 +1549,7 @@ name = "humanfriendly" version = "10.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "pyreadline3", marker = "sys_platform == 'win32'" }, + { name = "pyreadline3", marker = "python_full_version < '3.11' and sys_platform == 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/cc/3f/2c29224acb2e2df4d2046e4c73ee2662023c58ff5b113c4c1adac0886c43/humanfriendly-10.0.tar.gz", hash = "sha256:6b0b831ce8f15f7300721aa49829fc4e83921a9a301cc7f606be6686a2288ddc", size = 360702, upload-time = "2021-09-17T21:40:43.31Z" } wheels = [ @@ -1563,7 +1579,7 @@ name = "importlib-metadata" version = "9.0.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "zipp" }, + { name = "zipp", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/a9/01/15bb152d77b21318514a96f43af312635eb2500c96b55398d020c93d86ea/importlib_metadata-9.0.0.tar.gz", hash = "sha256:a4f57ab599e6a2e3016d7595cfd72eb4661a5106e787a95bcc90c7105b831efc", size = 56405, upload-time = "2026-03-20T06:42:56.999Z" } wheels = [ @@ -2845,12 +2861,12 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "coloredlogs" }, - { name = "flatbuffers" }, - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, - { name = "packaging" }, - { name = "protobuf" }, - { name = "sympy" }, + { name = "coloredlogs", marker = "python_full_version < '3.11'" }, + { name = "flatbuffers", marker = "python_full_version < '3.11'" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "packaging", marker = "python_full_version < '3.11'" }, + { name = "protobuf", marker = "python_full_version < '3.11'" }, + { name = "sympy", marker = "python_full_version < '3.11'" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/35/d6/311b1afea060015b56c742f3531168c1644650767f27ef40062569960587/onnxruntime-1.23.2-cp310-cp310-macosx_13_0_arm64.whl", hash = "sha256:a7730122afe186a784660f6ec5807138bf9d792fa1df76556b27307ea9ebcbe3", size = 17195934, upload-time = "2025-10-27T23:06:14.143Z" }, @@ -2896,10 +2912,10 @@ resolution-markers = [ "python_full_version == '3.11.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "flatbuffers" }, - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, - { name = "packaging" }, - { name = "protobuf" }, + { name = "flatbuffers", marker = "python_full_version >= '3.11'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "packaging", marker = "python_full_version >= '3.11'" }, + { name = "protobuf", marker = "python_full_version >= '3.11'" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/d4/81/29a9eb470994a75eb7b3ccf32be314d7c66675a00ac7b50294816cc2db27/onnxruntime-1.26.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:ee1109ef4ef27cad90e823399e61e03b3c6c7bfe0fb820b4baf3678c15be8b3c", size = 18005108, upload-time = "2026-05-08T19:08:11.728Z" }, @@ -3191,10 +3207,10 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" } }, - { name = "python-dateutil" }, - { name = "pytz" }, - { name = "tzdata" }, + { name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "python-dateutil", marker = "python_full_version < '3.11'" }, + { name = "pytz", marker = "python_full_version < '3.11'" }, + { name = "tzdata", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/33/01/d40b85317f86cf08d853a4f495195c73815fdf205eef3993821720274518/pandas-2.3.3.tar.gz", hash = "sha256:e05e1af93b977f7eafa636d043f9f94c7ee3ac81af99c13508215942e64c993b", size = 4495223, upload-time = "2025-09-29T23:34:51.853Z" } wheels = [ @@ -3266,9 +3282,9 @@ resolution-markers = [ "python_full_version == '3.11.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" } }, - { name = "python-dateutil" }, - { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, + { name = "numpy", version = "2.4.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, + { name = "python-dateutil", marker = "python_full_version >= '3.11'" }, + { name = "tzdata", marker = "(python_full_version >= '3.11' and sys_platform == 'emscripten') or (python_full_version >= '3.11' and sys_platform == 'win32')" }, ] sdist = { url = "https://files.pythonhosted.org/packages/f8/87/4341c6252d1c47b08768c3d25ac487362bf403f0313ddae4a2a26c9b1b4c/pandas-3.0.3.tar.gz", hash = "sha256:696a4a00a2a2a35d4e5deb3fc946641b96c944f02230e4f76137fe35d806c4fc", size = 4651414, upload-time = "2026-05-11T18:54:29.21Z" } wheels = [ @@ -4796,23 +4812,23 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "alabaster" }, - { name = "babel" }, - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "docutils", version = "0.21.2", source = { registry = "https://pypi.org/simple" } }, - { name = "imagesize" }, - { name = "jinja2" }, - { name = "packaging" }, - { name = "pygments" }, - { name = "requests" }, - { name = "snowballstemmer" }, - { name = "sphinxcontrib-applehelp" }, - { name = "sphinxcontrib-devhelp" }, - { name = "sphinxcontrib-htmlhelp" }, - { name = "sphinxcontrib-jsmath" }, - { name = "sphinxcontrib-qthelp" }, - { name = "sphinxcontrib-serializinghtml" }, - { name = "tomli" }, + { name = "alabaster", marker = "python_full_version < '3.11'" }, + { name = "babel", marker = "python_full_version < '3.11'" }, + { name = "colorama", marker = "python_full_version < '3.11' and sys_platform == 'win32'" }, + { name = "docutils", version = "0.21.2", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, + { name = "imagesize", marker = "python_full_version < '3.11'" }, + { name = "jinja2", marker = "python_full_version < '3.11'" }, + { name = "packaging", marker = "python_full_version < '3.11'" }, + { name = "pygments", marker = "python_full_version < '3.11'" }, + { name = "requests", marker = "python_full_version < '3.11'" }, + { name = "snowballstemmer", marker = "python_full_version < '3.11'" }, + { name = "sphinxcontrib-applehelp", marker = "python_full_version < '3.11'" }, + { name = "sphinxcontrib-devhelp", marker = "python_full_version < '3.11'" }, + { name = "sphinxcontrib-htmlhelp", marker = "python_full_version < '3.11'" }, + { name = "sphinxcontrib-jsmath", marker = "python_full_version < '3.11'" }, + { name = "sphinxcontrib-qthelp", marker = "python_full_version < '3.11'" }, + { name = "sphinxcontrib-serializinghtml", marker = "python_full_version < '3.11'" }, + { name = "tomli", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/6f/6d/be0b61178fe2cdcb67e2a92fc9ebb488e3c51c4f74a36a7824c0adf23425/sphinx-8.1.3.tar.gz", hash = "sha256:43c1911eecb0d3e161ad78611bc905d1ad0e523e4ddc202a58a821773dc4c927", size = 8184611, upload-time = "2024-10-13T20:27:13.93Z" } wheels = [ @@ -4829,23 +4845,23 @@ resolution-markers = [ "python_full_version == '3.11.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "alabaster" }, - { name = "babel" }, - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "docutils", version = "0.22.4", source = { registry = "https://pypi.org/simple" } }, - { name = "imagesize" }, - { name = "jinja2" }, - { name = "packaging" }, - { name = "pygments" }, - { name = "requests" }, - { name = "roman-numerals" }, - { name = "snowballstemmer" }, - { name = "sphinxcontrib-applehelp" }, - { name = "sphinxcontrib-devhelp" }, - { name = "sphinxcontrib-htmlhelp" }, - { name = "sphinxcontrib-jsmath" }, - { name = "sphinxcontrib-qthelp" }, - { name = "sphinxcontrib-serializinghtml" }, + { name = "alabaster", marker = "python_full_version == '3.11.*'" }, + { name = "babel", marker = "python_full_version == '3.11.*'" }, + { name = "colorama", marker = "python_full_version == '3.11.*' and sys_platform == 'win32'" }, + { name = "docutils", version = "0.22.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version == '3.11.*'" }, + { name = "imagesize", marker = "python_full_version == '3.11.*'" }, + { name = "jinja2", marker = "python_full_version == '3.11.*'" }, + { name = "packaging", marker = "python_full_version == '3.11.*'" }, + { name = "pygments", marker = "python_full_version == '3.11.*'" }, + { name = "requests", marker = "python_full_version == '3.11.*'" }, + { name = "roman-numerals", marker = "python_full_version == '3.11.*'" }, + { name = "snowballstemmer", marker = "python_full_version == '3.11.*'" }, + { name = "sphinxcontrib-applehelp", marker = "python_full_version == '3.11.*'" }, + { name = "sphinxcontrib-devhelp", marker = "python_full_version == '3.11.*'" }, + { name = "sphinxcontrib-htmlhelp", marker = "python_full_version == '3.11.*'" }, + { name = "sphinxcontrib-jsmath", marker = "python_full_version == '3.11.*'" }, + { name = "sphinxcontrib-qthelp", marker = "python_full_version == '3.11.*'" }, + { name = "sphinxcontrib-serializinghtml", marker = "python_full_version == '3.11.*'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/42/50/a8c6ccc36d5eacdfd7913ddccd15a9cee03ecafc5ee2bc40e1f168d85022/sphinx-9.0.4.tar.gz", hash = "sha256:594ef59d042972abbc581d8baa577404abe4e6c3b04ef61bd7fc2acbd51f3fa3", size = 8710502, upload-time = "2025-12-04T07:45:27.343Z" } wheels = [ @@ -4868,23 +4884,23 @@ resolution-markers = [ "python_full_version == '3.12.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "alabaster" }, - { name = "babel" }, - { name = "colorama", marker = "sys_platform == 'win32'" }, - { name = "docutils", version = "0.22.4", source = { registry = "https://pypi.org/simple" } }, - { name = "imagesize" }, - { name = "jinja2" }, - { name = "packaging" }, - { name = "pygments" }, - { name = "requests" }, - { name = "roman-numerals" }, - { name = "snowballstemmer" }, - { name = "sphinxcontrib-applehelp" }, - { name = "sphinxcontrib-devhelp" }, - { name = "sphinxcontrib-htmlhelp" }, - { name = "sphinxcontrib-jsmath" }, - { name = "sphinxcontrib-qthelp" }, - { name = "sphinxcontrib-serializinghtml" }, + { name = "alabaster", marker = "python_full_version >= '3.12'" }, + { name = "babel", marker = "python_full_version >= '3.12'" }, + { name = "colorama", marker = "python_full_version >= '3.12' and sys_platform == 'win32'" }, + { name = "docutils", version = "0.22.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, + { name = "imagesize", marker = "python_full_version >= '3.12'" }, + { name = "jinja2", marker = "python_full_version >= '3.12'" }, + { name = "packaging", marker = "python_full_version >= '3.12'" }, + { name = "pygments", marker = "python_full_version >= '3.12'" }, + { name = "requests", marker = "python_full_version >= '3.12'" }, + { name = "roman-numerals", marker = "python_full_version >= '3.12'" }, + { name = "snowballstemmer", marker = "python_full_version >= '3.12'" }, + { name = "sphinxcontrib-applehelp", marker = "python_full_version >= '3.12'" }, + { name = "sphinxcontrib-devhelp", marker = "python_full_version >= '3.12'" }, + { name = "sphinxcontrib-htmlhelp", marker = "python_full_version >= '3.12'" }, + { name = "sphinxcontrib-jsmath", marker = "python_full_version >= '3.12'" }, + { name = "sphinxcontrib-qthelp", marker = "python_full_version >= '3.12'" }, + { name = "sphinxcontrib-serializinghtml", marker = "python_full_version >= '3.12'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/cd/bd/f08eb0f4eed5c83f1ba2a3bd18f7745a2b1525fad70660a1c00224ec468a/sphinx-9.1.0.tar.gz", hash = "sha256:7741722357dd75f8190766926071fed3bdc211c74dd2d7d4df5404da95930ddb", size = 8718324, upload-time = "2025-12-31T15:09:27.646Z" } wheels = [ @@ -4984,8 +5000,8 @@ resolution-markers = [ "python_full_version < '3.11'", ] dependencies = [ - { name = "greenlet", marker = "platform_machine == 'AMD64' or platform_machine == 'WIN32' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'ppc64le' or platform_machine == 'win32' or platform_machine == 'x86_64'" }, - { name = "typing-extensions" }, + { name = "greenlet", marker = "(python_full_version < '3.11' and platform_machine == 'AMD64') or (python_full_version < '3.11' and platform_machine == 'WIN32') or (python_full_version < '3.11' and platform_machine == 'aarch64') or (python_full_version < '3.11' and platform_machine == 'amd64') or (python_full_version < '3.11' and platform_machine == 'ppc64le') or (python_full_version < '3.11' and platform_machine == 'win32') or (python_full_version < '3.11' and platform_machine == 'x86_64')" }, + { name = "typing-extensions", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/29/9c/271aa905cf2964f841371a97f3e63ab692bf51b4423d0491e67bc7f64037/sqlalchemy-2.0.54.tar.gz", hash = "sha256:baa8521e8ee9f24e75dfc7aaabc08020e551ef0d48d7c3e3536f5cddf277586b", size = 9969559, upload-time = "2026-09-15T21:06:57.337Z" } wheels = [ @@ -5053,7 +5069,7 @@ resolution-markers = [ "python_full_version == '3.11.*' and sys_platform != 'emscripten' and sys_platform != 'win32'", ] dependencies = [ - { name = "typing-extensions" }, + { name = "typing-extensions", marker = "python_full_version >= '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/1f/44/311bac6b6ef81e4dfd0287d04900108b1f5c00c9761dd3c0a2b7b9d0f86b/sqlalchemy-2.1.4.tar.gz", hash = "sha256:7bd7ad604487daa7eab8716471c29a7185f17b5287ce73bb7bc79fea050d8cfd", size = 10544216, upload-time = "2026-10-07T17:33:59.116Z" } wheels = [ @@ -5135,7 +5151,7 @@ name = "sympy" version = "1.14.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "mpmath" }, + { name = "mpmath", marker = "python_full_version < '3.11'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } wheels = [ @@ -5176,8 +5192,8 @@ dependencies = [ { name = "networkx", version = "3.6.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, { name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "pandas", version = "3.0.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, - { name = "psycopg2-binary" }, - { name = "pymysql" }, + { name = "platformdirs" }, + { name = "pydantic" }, { name = "python-dotenv" }, { name = "sqlalchemy", version = "2.0.54", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" }, { name = "sqlalchemy", version = "2.1.4", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" }, @@ -5202,6 +5218,12 @@ docs = [ { name = "sphinx", version = "9.1.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.12'" }, { name = "sphinx-rtd-theme" }, ] +mysql = [ + { name = "pymysql" }, +] +postgres = [ + { name = "psycopg2-binary" }, +] [package.metadata] requires-dist = [ @@ -5210,17 +5232,19 @@ requires-dist = [ { name = "chromadb", specifier = ">=1.5.9" }, { name = "flake8", marker = "extra == 'dev'", specifier = ">=6.0" }, { name = "isort", marker = "extra == 'dev'", specifier = ">=5.12" }, - { name = "langchain", specifier = ">=0.2.0" }, - { name = "langchain-core", specifier = ">=0.2.0" }, - { name = "langchain-google-genai", specifier = ">=2.0.0" }, - { name = "langchain-openai", specifier = ">=0.1.0" }, - { name = "langgraph", specifier = ">=0.2.0" }, - { name = "matplotlib", specifier = ">=3.8.0" }, + { name = "langchain", specifier = ">=1.2" }, + { name = "langchain-core", specifier = ">=1.2" }, + { name = "langchain-google-genai", specifier = ">=4.2" }, + { name = "langchain-openai", specifier = ">=1.1" }, + { name = "langgraph", specifier = ">=1.1" }, + { name = "matplotlib", specifier = ">=3.9.0" }, { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.0" }, { name = "networkx", specifier = ">=3.0" }, - { name = "pandas", specifier = ">=2.0.0" }, - { name = "psycopg2-binary", specifier = ">=2.9.0" }, - { name = "pymysql", specifier = ">=1.1.0" }, + { name = "pandas", specifier = ">=2.2.2" }, + { name = "platformdirs", specifier = ">=3.0" }, + { name = "psycopg2-binary", marker = "extra == 'postgres'", specifier = ">=2.9.0" }, + { name = "pydantic", specifier = ">=2.0" }, + { name = "pymysql", marker = "extra == 'mysql'", specifier = ">=1.1.0" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0" }, { name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0" }, { name = "pytest-recording", marker = "extra == 'dev'", specifier = ">=0.13.0" }, @@ -5231,7 +5255,7 @@ requires-dist = [ { name = "sqlalchemy", specifier = ">=2.0.0" }, { name = "tabulate", specifier = ">=0.10.0" }, ] -provides-extras = ["dev", "docs"] +provides-extras = ["postgres", "mysql", "dev", "docs"] [[package]] name = "tiktoken"