Spaces:
Running
Running
| from dotenv import load_dotenv | |
| import os | |
| import gspread | |
| from google.oauth2.service_account import Credentials | |
| import pandas as pd | |
| import json # <-- NOVO IMPORT OBRIGATÓRIO | |
| # Abrindo o cofre .env para pegar as chaves (funciona no PC, é ignorado no Hugging Face) | |
| load_dotenv() | |
| # --- 1. CONFIGURAÇÕES --- | |
| ID_PLANILHA = os.getenv("ID_PLANILHA") | |
| # Escopos (permissões) que o robô vai pedir | |
| ESCOPOS = [ | |
| "https://www.googleapis.com/auth/spreadsheets", | |
| "https://www.googleapis.com/auth/drive" | |
| ] | |
| def conectar_sheets(): | |
| """Lê as credenciais (da nuvem ou local) e abre a conexão definitiva com o Google""" | |
| try: | |
| # Tenta puxar o JSON gigante direto do cofre (Hugging Face) | |
| segredo_google = os.environ.get("GOOGLE_JSON") | |
| if segredo_google: | |
| # --- MODO NUVEM (Hugging Face) --- | |
| print("Tentando conectar pelo MODO NUVEM...") | |
| credenciais_dict = json.loads(segredo_google) | |
| # Usa o from_service_account_info em vez do _file | |
| credenciais = Credentials.from_service_account_info(credenciais_dict, scopes=ESCOPOS) | |
| else: | |
| # --- MODO LOCAL (Seu Computador) --- | |
| print("Tentando conectar pelo MODO LOCAL...") | |
| CAMINHO_JSON = os.getenv("CAMINHO_JSON") | |
| credenciais = Credentials.from_service_account_file(CAMINHO_JSON, scopes=ESCOPOS) | |
| # Autoriza e cria o cliente final | |
| cliente = gspread.authorize(credenciais) | |
| print("✅ Conectado ao Google com sucesso!") | |
| return cliente | |
| except Exception as e: | |
| print(f"❌ Erro ao conectar: {e}") | |
| return None | |
| # ============================================================================== | |
| # AS FUNÇÕES ABAIXO NÃO PRECISARAM DE MUDANÇAS, POIS A LÓGICA ACIMA RESOLVE TUDO! | |
| # ============================================================================== | |
| def adicionar_linha_sheets(historico): | |
| cliente = conectar_sheets() | |
| if not cliente: | |
| return | |
| try: | |
| print("1. Abrindo a planilha...") | |
| # Abre a planilha pelo ID e seleciona a primeira aba (Página1) | |
| planilha = cliente.open_by_key(ID_PLANILHA) | |
| aba = planilha.sheet1 | |
| print("3. Preparando a nova linha...") | |
| linha_formato_lista = list(historico.values()) | |
| # Capturamos o que o Google nos responde ao mesmo tempo que ao passar a linha para registra obriga ele a criar uma linha nova no sheets | |
| resposta_google = aba.append_row(linha_formato_lista,value_input_option="USER_ENTERED", insert_data_option="INSERT_ROWS") | |
| # Verificamos se o Google confirmou a alteração de células | |
| if resposta_google and 'updates' in resposta_google: | |
| celulas_atualizadas = resposta_google['updates'].get('updatedCells', 0) | |
| if celulas_atualizadas > 0: | |
| return {"status": "sucesso", "mensagem": "Registro salvo!"} | |
| # Se rodou sem erro, mas o Google não confirmou a inserção | |
| return {"status": "erro", "mensagem": "A API não confirmou a gravação na planilha."} | |
| except Exception as e: | |
| return {"status": "erro", "mensagem": str(e)} | |
| def ler_historico(): | |
| print("Baixando registros do Google Sheets...") | |
| cliente = conectar_sheets() | |
| planilha = cliente.open_by_key(ID_PLANILHA) | |
| aba = planilha.sheet1 | |
| # O COMANDO MÁGICO AQUI: | |
| dados = aba.get_all_records() | |
| df = pd.DataFrame(dados) | |
| return df | |
| def senhas(): | |
| cliente = conectar_sheets() | |
| planilha = cliente.open_by_key(ID_PLANILHA) | |
| aba = planilha.worksheet("acessos") | |
| # O COMANDO MÁGICO AQUI: | |
| dados = aba.get_all_records() | |
| df = pd.DataFrame(dados) | |
| return df |