Spaces:
Sleeping
Sleeping
Download app.py from mathteix7/corretor-spx: direct link, hf CLI and curl.
- Browser
- Download file 6.16 kB
-
https://huggingface.co/spaces/mathteix7/corretor-spx/resolve/main/app.py
- Command line
-
hf download hf://spaces/mathteix7/corretor-spx/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mathteix7/corretor-spx/resolve/main/app.py
6.16 kB
| import json | |
| import os | |
| import threading | |
| import time | |
| from pathlib import Path | |
| import gradio as gr | |
| from automation import SPXAutomation, AutomationConfig | |
| DATA_FILE = Path(os.getenv("SPX_DATA_FILE", "/tmp/spx_profile.json")) | |
| DEFAULT_URL = "https://sites.google.com/view/spx-lista-espera-dispv90/registro-de-disponibilidade" | |
| FIELDS = [ | |
| ("driver_id", "ID do Motorista"), | |
| ("arrival_time", "Tempo de Chegada ao Hub"), | |
| ("vehicle_profile", "Perfil do Veículo"), | |
| ("car_model", "Modelo do Carro"), | |
| ("availability_window", "Qual janela você está apresentando disponibilidade?"), | |
| ("confirm_today", "Você confirma que registrou disponibilidade na data de hoje e na janela atual?"), | |
| ] | |
| ARRIVAL_OPTIONS = ["Até 15 min", "15 a 30 min", "30 a 45 min", "45 min a 1h", "Superior a 1h", "Estou no hub"] | |
| VEHICLE_OPTIONS = ["Moto", "Passeio", "Fiorino", "Van"] | |
| WINDOW_OPTIONS = ["AM", "PM-1", "PM-2"] | |
| CONFIRM_OPTIONS = ["Sim", "Não"] | |
| STOP_EVENT = threading.Event() | |
| def empty_profile(): | |
| return {k: "" for k, _ in FIELDS} | |
| def load_profile(): | |
| if DATA_FILE.exists(): | |
| try: | |
| data = json.loads(DATA_FILE.read_text(encoding="utf-8")) | |
| profile = empty_profile() | |
| profile.update({k: str(data.get(k, "") or "") for k, _ in FIELDS}) | |
| return profile | |
| except Exception: | |
| pass | |
| return empty_profile() | |
| def save_profile(*values): | |
| profile = {k: (v or "") for (k, _), v in zip(FIELDS, values)} | |
| DATA_FILE.parent.mkdir(parents=True, exist_ok=True) | |
| DATA_FILE.write_text(json.dumps(profile, ensure_ascii=False, indent=2), encoding="utf-8") | |
| return "Dados salvos. Clique em INICIAR para executar com este mesmo cadastro." | |
| def start_batch(url, interval, max_submissions): | |
| profile = load_profile() | |
| required = [k for k, _ in FIELDS] | |
| missing_saved = [k for k in required if not profile.get(k)] | |
| if missing_saved: | |
| labels = dict(FIELDS) | |
| names = ", ".join(labels[k] for k in missing_saved) | |
| yield f"Dados incompletos no perfil salvo. Preencha: {names}" | |
| return | |
| try: | |
| interval = max(1.0, float(interval or 12.0)) | |
| except (TypeError, ValueError): | |
| interval = 12.0 | |
| try: | |
| max_submissions = max(1, min(20, int(max_submissions or 20))) | |
| except (TypeError, ValueError): | |
| max_submissions = 20 | |
| STOP_EVENT.clear() | |
| bot = SPXAutomation( | |
| AutomationConfig( | |
| url=url or DEFAULT_URL, | |
| pre_submit_delay=1.0, | |
| headless=True, | |
| ) | |
| ) | |
| successes = 0 | |
| started_at = time.time() | |
| yield ( | |
| f"Iniciado. Perfil salvo carregado. Meta: até {max_submissions} submissões. " | |
| f"Intervalo: {interval:.1f}s." | |
| ) | |
| try: | |
| for attempt in range(1, max_submissions + 1): | |
| if STOP_EVENT.is_set(): | |
| yield f"Parado. Submissões realizadas: {successes}/{max_submissions}." | |
| return | |
| result = bot.fill_and_submit(profile) | |
| successes += 1 | |
| elapsed = time.time() - started_at | |
| yield ( | |
| f"Submissão {attempt}/{max_submissions} concluída.\n" | |
| f"{result}\n" | |
| f"Tempo decorrido: {elapsed:.1f}s." | |
| ) | |
| if attempt >= max_submissions: | |
| yield f"Concluído: {successes}/{max_submissions} submissões realizadas." | |
| return | |
| if STOP_EVENT.wait(interval): | |
| yield f"Parado. Submissões realizadas: {successes}/{max_submissions}." | |
| return | |
| except Exception as exc: | |
| yield f"Automação interrompida após {successes} submissões. {type(exc).__name__}: {exc}" | |
| finally: | |
| STOP_EVENT.set() | |
| def stop_batch(): | |
| STOP_EVENT.set() | |
| return "Solicitação de parada enviada." | |
| def get_defaults(): | |
| p = load_profile() | |
| return [p.get(k, "") for k, _ in FIELDS] | |
| def build(): | |
| defaults = get_defaults() | |
| with gr.Blocks(title="SPX — Automação de Disponibilidade") as demo: | |
| gr.Markdown( | |
| "# SPX — Automação de Disponibilidade\n" | |
| "Preencha os dados uma única vez, clique em SALVAR MEUS DADOS e depois use INICIAR. " | |
| "O perfil salvo será reutilizado nas execuções." | |
| ) | |
| url = gr.Textbox(value=DEFAULT_URL, label="URL do formulário", visible=False) | |
| interval = gr.Number( | |
| value=12, | |
| label="Intervalo entre submissões (segundos)", | |
| precision=1, | |
| minimum=1, | |
| maximum=3600, | |
| ) | |
| max_submissions = gr.Slider( | |
| value=20, | |
| minimum=1, | |
| maximum=20, | |
| step=1, | |
| label="Máximo de submissões nesta execução", | |
| ) | |
| driver_id = gr.Textbox(value=defaults[0], label="ID do Motorista") | |
| arrival_time = gr.Dropdown(ARRIVAL_OPTIONS, value=defaults[1] or None, label="Tempo de Chegada ao Hub") | |
| vehicle_profile = gr.Radio(VEHICLE_OPTIONS, value=defaults[2] or None, label="Perfil do Veículo") | |
| car_model = gr.Textbox(value=defaults[3], label="Modelo do Carro") | |
| availability_window = gr.Radio(WINDOW_OPTIONS, value=defaults[4] or None, label="Qual janela você está apresentando disponibilidade?") | |
| confirm_today = gr.Radio(CONFIRM_OPTIONS, value=defaults[5] or "Sim", label="Você confirma que registrou disponibilidade na data de hoje e na janela atual?") | |
| with gr.Row(): | |
| save = gr.Button("SALVAR MEUS DADOS") | |
| start = gr.Button("INICIAR", variant="primary") | |
| stop = gr.Button("PARAR", variant="stop") | |
| status = gr.Textbox(label="Status", lines=10) | |
| inputs = [driver_id, arrival_time, vehicle_profile, car_model, availability_window, confirm_today] | |
| save.click(fn=save_profile, inputs=inputs, outputs=status) | |
| start.click(fn=start_batch, inputs=[url, interval, max_submissions], outputs=status) | |
| stop.click(fn=stop_batch, inputs=None, outputs=status) | |
| return demo | |
| if __name__ == "__main__": | |
| build().launch(server_name="0.0.0.0", server_port=int(os.getenv("PORT", "7860"))) | |