agroplan-ai-cli 1.0.17 → 1.0.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -540,177 +540,54 @@ def ensure_zarc_file(safra: str = ZARC_SAFRA_DEFAULT) -> Optional[Dict[str, Any]
540
540
  # Nenhum arquivo disponível
541
541
  return None
542
542
 
543
- # OBSOLETO: Funções antigas que carregavam CSV inteiro em memória
544
- # Mantidas apenas para referência, não devem ser usadas
545
- # Use: ensure_zarc_file() + iter_zarc_records() + buscar_zarc()
543
+ # REMOVIDO: Funções obsoletas que carregavam CSV inteiro em memória
544
+ # Essas funções foram removidas para evitar problemas de memória
545
+ # Use: ensure_zarc_file() + iter_zarc_records() + buscar_zarc_indexado()
546
546
 
547
- # def download_zarc_dataset(safra: str) -> Optional[str]:
548
- # """OBSOLETO - Não usar, causa problemas de memória"""
549
- # pass
550
-
551
- # def get_zarc_dataset(safra: str = ZARC_SAFRA_DEFAULT) -> Dict[str, Any]:
552
- # """OBSOLETO - Não usar, carrega 1M+ registros em memória"""
553
- # pass
554
-
555
- # def load_zarc_from_file(file_path: str) -> List[Dict[str, Any]]:
556
- # """OBSOLETO - Não usar, carrega CSV inteiro em lista"""
557
- # pass
547
+ def download_zarc_dataset(*args, **kwargs):
558
548
  """
559
- Baixa dataset ZARC oficial
549
+ REMOVIDO: Esta função carregava o CSV inteiro em memória (214 MB).
560
550
 
561
- Returns:
562
- Caminho do arquivo baixado ou None se falhar
551
+ Use: ensure_zarc_file() para gerenciar o arquivo sem carregar dados
563
552
  """
564
- try:
565
- url = ZARC_URLS.get(safra)
566
- if not url:
567
- print(f"URL não disponível para safra {safra}")
568
- return None
569
-
570
- cache_path = get_cache_path(safra)
571
-
572
- print(f"Baixando ZARC oficial de {url}...")
573
-
574
- # Criar request com User-Agent
575
- req = urllib.request.Request(
576
- url,
577
- headers={
578
- 'User-Agent': 'AgroPlan-AI/1.0 (https://github.com/Kuuhaku-Allan/agroplan-ai)'
579
- }
580
- )
581
-
582
- # Download
583
- with urllib.request.urlopen(req, timeout=30) as response:
584
- content = response.read().decode('utf-8')
585
-
586
- # Salvar
587
- with open(cache_path, 'w', encoding='utf-8') as f:
588
- f.write(content)
589
-
590
- print(f"ZARC oficial baixado e salvo em {cache_path}")
591
- return cache_path
592
-
593
- except Exception as e:
594
- print(f"Erro ao baixar ZARC oficial: {e}")
595
- return None
553
+ raise RuntimeError(
554
+ "download_zarc_dataset() foi removido por causar problemas de memória. "
555
+ "Use ensure_zarc_file() para gerenciar o arquivo ZARC."
556
+ )
596
557
 
597
- def get_zarc_dataset(safra: str = ZARC_SAFRA_DEFAULT) -> Dict[str, Any]:
558
+ def get_zarc_dataset(*args, **kwargs):
598
559
  """
599
- Obtém dataset ZARC (cache ou download)
560
+ REMOVIDO: Esta função carregava 1M+ registros em memória.
600
561
 
601
- Returns:
602
- Dicionário com:
603
- - records: Lista de registros ZARC
604
- - source: "zarc-oficial" | "zarc-cache" | "zarc-fallback"
605
- - fallback: bool
606
- - cache_path: str ou None
607
- - error: str ou None
562
+ Use: buscar_zarc_indexado() para lookup rápido O(1)
563
+ Use: iter_zarc_records() para processar em streaming
608
564
  """
609
- cache_path = get_cache_path(safra)
610
-
611
- # Verificar cache válido
612
- if is_cache_valid(cache_path):
613
- try:
614
- records = load_zarc_from_file(cache_path)
615
- return {
616
- "records": records,
617
- "source": "zarc-cache",
618
- "fallback": False,
619
- "cache_path": cache_path,
620
- "error": None
621
- }
622
- except Exception as e:
623
- print(f"Erro ao carregar cache ZARC: {e}")
624
-
625
- # Tentar download se source for official
626
- if ZARC_SOURCE == "official":
627
- downloaded_path = download_zarc_dataset(safra)
628
- if downloaded_path:
629
- try:
630
- records = load_zarc_from_file(downloaded_path)
631
- return {
632
- "records": records,
633
- "source": "zarc-oficial",
634
- "fallback": False,
635
- "cache_path": downloaded_path,
636
- "error": None
637
- }
638
- except Exception as e:
639
- print(f"Erro ao carregar ZARC baixado: {e}")
640
-
641
- # Usar cache antigo se existir (mesmo expirado)
642
- if os.path.exists(cache_path):
643
- try:
644
- records = load_zarc_from_file(cache_path)
645
- return {
646
- "records": records,
647
- "source": "zarc-cache",
648
- "fallback": False,
649
- "cache_path": cache_path,
650
- "error": "Cache expirado mas usado"
651
- }
652
- except Exception as e:
653
- print(f"Erro ao carregar cache antigo: {e}")
654
-
655
- # Fallback para dados simplificados
656
- print("Usando fallback ZARC simplificado")
657
- return {
658
- "records": get_zarc_fallback(),
659
- "source": "zarc-fallback",
660
- "fallback": True,
661
- "cache_path": None,
662
- "error": "CSV oficial não disponível, usando dados simplificados"
663
- }
565
+ raise RuntimeError(
566
+ "get_zarc_dataset() foi removido por carregar 1M+ registros em memória. "
567
+ "Use buscar_zarc_indexado() para lookup rápido ou iter_zarc_records() para streaming."
568
+ )
664
569
 
665
- def load_zarc_from_file(file_path: str) -> List[Dict[str, Any]]:
666
- """Carrega dados ZARC de arquivo CSV"""
667
- registros = []
668
-
669
- with open(file_path, 'r', encoding='utf-8-sig') as f: # utf-8-sig remove BOM
670
- # Detectar delimitador (CSV oficial usa ponto-e-vírgula)
671
- primeira_linha = f.readline()
672
- f.seek(0)
673
-
674
- delimiter = ';' if ';' in primeira_linha else ','
675
-
676
- reader = csv.DictReader(f, delimiter=delimiter)
677
-
678
- # Log das colunas encontradas (primeira vez)
679
- if reader.fieldnames:
680
- print(f"Colunas ZARC encontradas ({len(reader.fieldnames)} colunas, delimiter='{delimiter}')")
681
-
682
- for row in reader:
683
- registros.append(row)
570
+ def load_zarc_from_file(*args, **kwargs):
571
+ """
572
+ REMOVIDO: Esta função carregava o CSV inteiro em uma lista.
684
573
 
685
- return registros
574
+ Use: iter_zarc_records() para processar linha por linha
575
+ """
576
+ raise RuntimeError(
577
+ "load_zarc_from_file() foi removido por carregar CSV inteiro em lista. "
578
+ "Use iter_zarc_records() para processar linha por linha."
579
+ )
686
580
 
687
- def inspect_zarc_columns(safra: str = ZARC_SAFRA_DEFAULT) -> Optional[List[str]]:
581
+ def inspect_zarc_columns(*args, **kwargs):
688
582
  """
689
- Inspeciona colunas do CSV ZARC oficial
583
+ REMOVIDO: Esta função dependia de get_zarc_dataset().
690
584
 
691
- Returns:
692
- Lista de nomes de colunas ou None se falhar
585
+ Use: iter_zarc_records() e inspecione a primeira linha
693
586
  """
694
- try:
695
- dataset = get_zarc_dataset(safra)
696
-
697
- if not dataset or not dataset.get("records"):
698
- print("Nenhum registro ZARC disponível")
699
- return None
700
-
701
- # Pegar colunas do primeiro registro
702
- if dataset["records"]:
703
- colunas = list(dataset["records"][0].keys())
704
- print(f"\nColunas do CSV ZARC ({dataset['source']}):")
705
- for i, col in enumerate(colunas, 1):
706
- print(f" {i}. {col}")
707
- return colunas
708
-
709
- return None
710
-
711
- except Exception as e:
712
- print(f"Erro ao inspecionar colunas ZARC: {e}")
713
- return None
587
+ raise RuntimeError(
588
+ "inspect_zarc_columns() foi removido por depender de get_zarc_dataset(). "
589
+ "Use iter_zarc_records() e inspecione a primeira linha."
590
+ )
714
591
 
715
592
  def get_zarc_fallback() -> List[Dict[str, Any]]:
716
593
  """
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agroplan-ai-cli",
3
- "version": "1.0.17",
3
+ "version": "1.0.19",
4
4
  "description": "CLI global para AgroPlan AI - modo local acelerado",
5
5
  "type": "module",
6
6
  "bin": {
@@ -14,6 +14,8 @@
14
14
  "scripts": {
15
15
  "build": "bun build src/index.ts --outdir dist --target bun",
16
16
  "postbuild": "node -e \"const fs=require('fs'); let content=fs.readFileSync('dist/index.js','utf8'); if(!content.startsWith('#!/usr/bin/env bun')) content='#!/usr/bin/env bun\\n'+content; fs.writeFileSync('dist/index.js',content);\"",
17
+ "prepack": "bun run build",
18
+ "prepublishOnly": "bun run build",
17
19
  "dev": "bun run src/index.ts",
18
20
  "agroplan": "bun run src/index.ts"
19
21
  },