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85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
"""
Backend-only Modal app for GUI-driven Protify workflows.

This module intentionally avoids browser UI dependencies. It exposes remote
functions that the local Tk GUI can call to deploy, submit jobs, monitor status,
cancel jobs, and fetch artifacts.
"""

import base64
import json
import os
import random
import shutil
import string
import subprocess
import threading
import time
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Optional

import modal
import yaml


SCRIPT_DIR = Path(__file__).parent.resolve()
PROJECT_ROOT = SCRIPT_DIR.parents[1]

APP_NAME = "protify-backend"
PROTIFY_DEFAULT_GPU = "A10"
AVAILABLE_GPUS = ["H200", "H100", "A100-80GB", "A100", "L40S", "A10", "L4", "T4"]

GPU_CPU_MIN, GPU_CPU_MAX = 8.0, 16.0
GPU_MEMORY_MIN, GPU_MEMORY_MAX = 65536, 262144
MAX_CONTAINERS_GPU = 8
CPU_MEMORY_MIN, CPU_MEMORY_MAX = 4096, 8192
CPU_COUNT_MIN, CPU_COUNT_MAX = 2.0, 4.0
MAX_CONTAINERS_CPU = 10
SCALEDOWN_WINDOW_GPU = 10
SCALEDOWN_WINDOW_CPU = 300
TIMEOUT_SECONDS = 86400
HEARTBEAT_SECONDS = 10

STATUS_FILE_PATH = "/data/job_status.json"
LOG_DIR_DEFAULT = "/data/logs"
RESULTS_DIR_DEFAULT = "/data/results"
PLOTS_DIR_DEFAULT = "/data/plots"
WEIGHTS_DIR_DEFAULT = "/data/weights"
EMBED_DIR_DEFAULT = "/data/embeddings"
DOWNLOAD_DIR_DEFAULT = "/data/downloads"


def _build_image():
    image = (
        modal.Image.debian_slim(python_version="3.10")
        .apt_install("git", "wget", "curl")
        .run_commands("pip install --upgrade pip setuptools")
    )

    req_file_path = "requirements.txt"
    if (PROJECT_ROOT / req_file_path).exists():
        image = image.add_local_file(req_file_path, "/tmp/requirements.txt", copy=True)
        image = image.run_commands("pip install -r /tmp/requirements.txt")
    else:
        image = image.run_commands("pip install torch transformers datasets")

    src_dir_path = "src"
    if (PROJECT_ROOT / src_dir_path).exists():
        image = image.add_local_dir(src_dir_path, "/root/src", copy=True)

    readme_file_path = "README.md"
    if (PROJECT_ROOT / readme_file_path).exists():
        image = image.add_local_file(readme_file_path, "/root/README.md", copy=True)

    image = image.env(
        {
            "TF_CPP_MIN_LOG_LEVEL": "2",
            "TF_ENABLE_ONEDNN_OPTS": "0",
            "TOKENIZERS_PARALLELISM": "true",
            "CUBLAS_WORKSPACE_CONFIG": ":4096:8",
        }
    )
    return image


app = modal.App(APP_NAME)
image = _build_image()
volume = modal.Volume.from_name("protify-data", create_if_missing=True)

_status_lock = threading.Lock()


def _now_utc_iso() -> str:
    return datetime.now(timezone.utc).isoformat()


def _generate_job_id() -> str:
    random_letters = "".join(random.choices(string.ascii_uppercase, k=4))
    date_str = datetime.now().strftime("%Y-%m-%d-%H-%M")
    return f"{date_str}_{random_letters}"


def _safe_read_json(json_path: str) -> Dict[str, Any]:
    if not os.path.exists(json_path):
        return {}
    try:
        with open(json_path, "r", encoding="utf-8") as file:
            return json.load(file)
    except Exception:
        return {}


def _safe_write_json(json_path: str, payload: Dict[str, Any]) -> None:
    os.makedirs(os.path.dirname(json_path), exist_ok=True)
    with open(json_path, "w", encoding="utf-8") as file:
        json.dump(payload, file, indent=2)


def _update_job_status(job_id: str, patch: Dict[str, Any]) -> Dict[str, Any]:
    with _status_lock:
        status_store = _safe_read_json(STATUS_FILE_PATH)
        if job_id not in status_store:
            status_store[job_id] = {
                "job_id": job_id,
                "status": "PENDING",
                "phase": "created",
                "created_at_utc": _now_utc_iso(),
                "updated_at_utc": _now_utc_iso(),
            }
        status_store[job_id].update(patch)
        status_store[job_id]["updated_at_utc"] = _now_utc_iso()
        _safe_write_json(STATUS_FILE_PATH, status_store)
        volume.commit()
        return status_store[job_id]


def _infer_phase_from_line(line: str, current_phase: str) -> str:
    lowered = line.lower()
    if "loading and preparing datasets" in lowered or "getting data" in lowered:
        return "data_loading"
    if "computing embeddings" in lowered or "saving embeddings" in lowered or "download embeddings" in lowered:
        return "embedding"
    if "starting training" in lowered or "training probe" in lowered or "run_wandb_hyperopt" in lowered:
        return "training"
    if "proteingym" in lowered:
        return "proteingym"
    if "generating visualization plots" in lowered:
        return "plotting"
    if "successfully saved model to huggingface hub" in lowered:
        return "pushing_to_hub"
    return current_phase


def _tail_text(text: str, max_chars: int) -> str:
    if len(text) <= max_chars:
        return text
    return text[-max_chars:]


def _fix_paths(config_obj: Any) -> Any:
    if isinstance(config_obj, dict):
        for key in list(config_obj.keys()):
            value = config_obj[key]
            if isinstance(value, str):
                if value.startswith("data/") or value.startswith("local_data/"):
                    config_obj[key] = f"/data/{value.split('/', 1)[1]}"
                elif key.endswith("_dir") and (not os.path.isabs(value)):
                    config_obj[key] = f"/data/{value}"
            elif isinstance(value, list):
                config_obj[key] = [_fix_paths(item) for item in value]
            elif isinstance(value, dict):
                config_obj[key] = _fix_paths(value)
    elif isinstance(config_obj, list):
        return [_fix_paths(item) for item in config_obj]
    return config_obj


def _prepare_config(config: Dict[str, Any]) -> Dict[str, Any]:
    config_copy = dict(config)
    config_copy = _fix_paths(config_copy)

    if ("log_dir" not in config_copy) or (not config_copy["log_dir"]):
        config_copy["log_dir"] = LOG_DIR_DEFAULT
    if ("results_dir" not in config_copy) or (not config_copy["results_dir"]):
        config_copy["results_dir"] = RESULTS_DIR_DEFAULT
    if ("model_save_dir" not in config_copy) or (not config_copy["model_save_dir"]):
        config_copy["model_save_dir"] = WEIGHTS_DIR_DEFAULT
    if ("embedding_save_dir" not in config_copy) or (not config_copy["embedding_save_dir"]):
        config_copy["embedding_save_dir"] = EMBED_DIR_DEFAULT
    if ("plots_dir" not in config_copy) or (not config_copy["plots_dir"]):
        config_copy["plots_dir"] = PLOTS_DIR_DEFAULT
    if ("download_dir" not in config_copy) or (not config_copy["download_dir"]):
        config_copy["download_dir"] = DOWNLOAD_DIR_DEFAULT
    if "replay_path" not in config_copy:
        config_copy["replay_path"] = None
    if "pretrained_probe_path" not in config_copy:
        config_copy["pretrained_probe_path"] = None
    if "hf_home" not in config_copy:
        config_copy["hf_home"] = None

    path_keys = ["log_dir", "results_dir", "model_save_dir", "embedding_save_dir", "plots_dir", "download_dir"]
    for path_key in path_keys:
        os.makedirs(config_copy[path_key], exist_ok=True)

    return config_copy


def _execute_protify_job(
    config: Dict[str, Any],
    hf_token: Optional[str] = None,
    wandb_api_key: Optional[str] = None,
    synthyra_api_key: Optional[str] = None,
    job_id: Optional[str] = None,
    gpu_type: Optional[str] = None,
    timeout_seconds: int = TIMEOUT_SECONDS,
) -> Dict[str, Any]:
    if job_id is None:
        job_id = _generate_job_id()

    selected_gpu = gpu_type if gpu_type in AVAILABLE_GPUS else PROTIFY_DEFAULT_GPU
    _update_job_status(
        job_id,
        {
            "status": "RUNNING",
            "phase": "startup",
            "gpu_type": selected_gpu,
            "last_heartbeat_utc": _now_utc_iso(),
            "started_at_utc": _now_utc_iso(),
            "error": None,
        },
    )

    active_hf_token = hf_token
    if active_hf_token is None:
        active_hf_token = os.environ.get("HF_TOKEN")

    if active_hf_token is not None:
        try:
            from huggingface_hub import login

            os.environ["HF_TOKEN"] = active_hf_token
            login(active_hf_token)
        except Exception:
            pass

    prepared_config = _prepare_config(config)
    log_file_path = os.path.join(prepared_config["log_dir"], f"{job_id}.txt")
    _update_job_status(
        job_id,
        {
            "log_file_path": log_file_path,
            "results_dir": prepared_config["results_dir"],
            "plots_dir": prepared_config["plots_dir"],
        },
    )

    run_dir = Path("/tmp/protify_run") / job_id
    run_dir.mkdir(parents=True, exist_ok=True)
    config_path = run_dir / "config.yaml"

    config_to_dump = dict(prepared_config)
    config_to_dump["hf_token"] = None
    config_to_dump["wandb_api_key"] = None
    config_to_dump["synthyra_api_key"] = None
    with open(config_path, "w", encoding="utf-8") as config_file:
        yaml.dump(config_to_dump, config_file, default_flow_style=False, allow_unicode=True, sort_keys=False)

    command = ["python", "-u", "main.py", "--yaml_path", str(config_path)]
    if active_hf_token is not None:
        command.extend(["--hf_token", active_hf_token])
    if wandb_api_key is not None:
        command.extend(["--wandb_api_key", wandb_api_key])
    if synthyra_api_key is not None:
        command.extend(["--synthyra_api_key", synthyra_api_key])

    process_env = os.environ.copy()
    process_env["PYTHONPATH"] = "/root/src"
    process_env["WORKING_DIR"] = "/root"
    process_env["PYTHONUNBUFFERED"] = "1"
    process_env["PROTIFY_JOB_ID"] = job_id
    process_env["CUDA_VISIBLE_DEVICES"] = "0"
    if active_hf_token is not None:
        process_env["HF_TOKEN"] = active_hf_token
    if wandb_api_key is not None:
        process_env["WANDB_API_KEY"] = wandb_api_key

    os.makedirs(os.path.dirname(log_file_path), exist_ok=True)
    with open(log_file_path, "w", encoding="utf-8") as log_file:
        log_file.write(f"[{_now_utc_iso()}] Starting job {job_id}\n")
        log_file.write(f"GPU={selected_gpu}\n")
        log_file.write(f"Command={' '.join(command)}\n")
    volume.commit()

    stdout_lines = []
    stderr_lines = []
    log_lock = threading.Lock()
    phase_state = {"phase": "startup"}

    def append_log(log_line: str) -> None:
        with log_lock:
            with open(log_file_path, "a", encoding="utf-8", errors="ignore") as log_file:
                log_file.write(log_line + "\n")

    def stream_output(pipe, output_list, prefix: str = ""):
        try:
            for line in iter(pipe.readline, ""):
                if not line:
                    continue
                clean_line = line.rstrip("\n")
                full_line = f"{prefix}{clean_line}"
                output_list.append(full_line)
                phase_state["phase"] = _infer_phase_from_line(clean_line, phase_state["phase"])
                append_log(full_line)
                print(full_line, flush=True)
        finally:
            pipe.close()

    timed_out = False
    process = None
    try:
        process = subprocess.Popen(
            command,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            text=True,
            bufsize=1,
            cwd="/root/src/protify",
            env=process_env,
        )

        stdout_thread = threading.Thread(target=stream_output, args=(process.stdout, stdout_lines, ""), daemon=True)
        stderr_thread = threading.Thread(target=stream_output, args=(process.stderr, stderr_lines, "[STDERR] "), daemon=True)
        stdout_thread.start()
        stderr_thread.start()

        max_runtime_seconds = timeout_seconds
        if max_runtime_seconds > TIMEOUT_SECONDS - 60:
            max_runtime_seconds = TIMEOUT_SECONDS - 60

        start_time = time.time()
        last_heartbeat = 0.0
        while process.poll() is None:
            now = time.time()
            if now - start_time > max_runtime_seconds:
                timed_out = True
                process.kill()
                break
            if now - last_heartbeat >= HEARTBEAT_SECONDS:
                _update_job_status(
                    job_id,
                    {
                        "status": "RUNNING",
                        "phase": phase_state["phase"],
                        "last_heartbeat_utc": _now_utc_iso(),
                    },
                )
                last_heartbeat = now
            time.sleep(1)

        stdout_thread.join(timeout=5)
        stderr_thread.join(timeout=5)

        return_code = process.returncode if process is not None else -1
        stdout_text = "\n".join(stdout_lines)
        stderr_text = "\n".join(stderr_lines)

        if timed_out:
            _update_job_status(
                job_id,
                {
                    "status": "TIMEOUT",
                    "phase": "timeout",
                    "last_heartbeat_utc": _now_utc_iso(),
                    "error": f"Process timed out after {max_runtime_seconds} seconds.",
                    "exit_code": -1,
                    "finished_at_utc": _now_utc_iso(),
                },
            )
            return {
                "success": False,
                "job_id": job_id,
                "status": "TIMEOUT",
                "error": f"Process timed out after {max_runtime_seconds} seconds.",
                "stdout": _tail_text(stdout_text, 5000),
            }

        if return_code != 0:
            _update_job_status(
                job_id,
                {
                    "status": "FAILED",
                    "phase": "failed",
                    "last_heartbeat_utc": _now_utc_iso(),
                    "error": _tail_text(stderr_text, 5000) if stderr_text else "Unknown subprocess error.",
                    "exit_code": return_code,
                    "finished_at_utc": _now_utc_iso(),
                },
            )
            return {
                "success": False,
                "job_id": job_id,
                "status": "FAILED",
                "error": _tail_text(stderr_text, 5000) if stderr_text else "Unknown subprocess error.",
                "stdout": _tail_text(stdout_text, 5000),
            }

        _update_job_status(
            job_id,
            {
                "status": "SUCCESS",
                "phase": "completed",
                "last_heartbeat_utc": _now_utc_iso(),
                "error": None,
                "exit_code": return_code,
                "finished_at_utc": _now_utc_iso(),
            },
        )
        return {
            "success": True,
            "job_id": job_id,
            "status": "SUCCESS",
            "stdout": _tail_text(stdout_text, 5000),
        }
    except Exception as error:
        _update_job_status(
            job_id,
            {
                "status": "FAILED",
                "phase": "exception",
                "last_heartbeat_utc": _now_utc_iso(),
                "error": str(error),
                "exit_code": -1,
                "finished_at_utc": _now_utc_iso(),
            },
        )
        return {
            "success": False,
            "job_id": job_id,
            "status": "FAILED",
            "error": str(error),
            "stdout": "",
        }


@app.function(
    image=image,
    gpu="H200",
    volumes={"/data": volume},
    memory=(GPU_MEMORY_MIN, GPU_MEMORY_MAX),
    cpu=(GPU_CPU_MIN, GPU_CPU_MAX),
    max_containers=MAX_CONTAINERS_GPU,
    scaledown_window=SCALEDOWN_WINDOW_GPU,
    timeout=TIMEOUT_SECONDS,
)
def run_protify_job_h200(
    config: Dict[str, Any],
    hf_token: Optional[str] = None,
    wandb_api_key: Optional[str] = None,
    synthyra_api_key: Optional[str] = None,
    job_id: Optional[str] = None,
    gpu_type: Optional[str] = None,
    timeout_seconds: int = TIMEOUT_SECONDS,
) -> Dict[str, Any]:
    return _execute_protify_job(config, hf_token, wandb_api_key, synthyra_api_key, job_id, gpu_type, timeout_seconds)


@app.function(
    image=image,
    gpu="H100",
    volumes={"/data": volume},
    memory=(GPU_MEMORY_MIN, GPU_MEMORY_MAX),
    cpu=(GPU_CPU_MIN, GPU_CPU_MAX),
    max_containers=MAX_CONTAINERS_GPU,
    scaledown_window=SCALEDOWN_WINDOW_GPU,
    timeout=TIMEOUT_SECONDS,
)
def run_protify_job_h100(
    config: Dict[str, Any],
    hf_token: Optional[str] = None,
    wandb_api_key: Optional[str] = None,
    synthyra_api_key: Optional[str] = None,
    job_id: Optional[str] = None,
    gpu_type: Optional[str] = None,
    timeout_seconds: int = TIMEOUT_SECONDS,
) -> Dict[str, Any]:
    return _execute_protify_job(config, hf_token, wandb_api_key, synthyra_api_key, job_id, gpu_type, timeout_seconds)


@app.function(
    image=image,
    gpu="A100-80GB",
    volumes={"/data": volume},
    memory=(GPU_MEMORY_MIN, GPU_MEMORY_MAX),
    cpu=(GPU_CPU_MIN, GPU_CPU_MAX),
    max_containers=MAX_CONTAINERS_GPU,
    scaledown_window=SCALEDOWN_WINDOW_GPU,
    timeout=TIMEOUT_SECONDS,
)
def run_protify_job_a100_80gb(
    config: Dict[str, Any],
    hf_token: Optional[str] = None,
    wandb_api_key: Optional[str] = None,
    synthyra_api_key: Optional[str] = None,
    job_id: Optional[str] = None,
    gpu_type: Optional[str] = None,
    timeout_seconds: int = TIMEOUT_SECONDS,
) -> Dict[str, Any]:
    return _execute_protify_job(config, hf_token, wandb_api_key, synthyra_api_key, job_id, gpu_type, timeout_seconds)


@app.function(
    image=image,
    gpu="A100",
    volumes={"/data": volume},
    memory=(GPU_MEMORY_MIN, GPU_MEMORY_MAX),
    cpu=(GPU_CPU_MIN, GPU_CPU_MAX),
    max_containers=MAX_CONTAINERS_GPU,
    scaledown_window=SCALEDOWN_WINDOW_GPU,
    timeout=TIMEOUT_SECONDS,
)
def run_protify_job_a100(
    config: Dict[str, Any],
    hf_token: Optional[str] = None,
    wandb_api_key: Optional[str] = None,
    synthyra_api_key: Optional[str] = None,
    job_id: Optional[str] = None,
    gpu_type: Optional[str] = None,
    timeout_seconds: int = TIMEOUT_SECONDS,
) -> Dict[str, Any]:
    return _execute_protify_job(config, hf_token, wandb_api_key, synthyra_api_key, job_id, gpu_type, timeout_seconds)


@app.function(
    image=image,
    gpu="L40S",
    volumes={"/data": volume},
    memory=(GPU_MEMORY_MIN, GPU_MEMORY_MAX),
    cpu=(GPU_CPU_MIN, GPU_CPU_MAX),
    max_containers=MAX_CONTAINERS_GPU,
    scaledown_window=SCALEDOWN_WINDOW_GPU,
    timeout=TIMEOUT_SECONDS,
)
def run_protify_job_l40s(
    config: Dict[str, Any],
    hf_token: Optional[str] = None,
    wandb_api_key: Optional[str] = None,
    synthyra_api_key: Optional[str] = None,
    job_id: Optional[str] = None,
    gpu_type: Optional[str] = None,
    timeout_seconds: int = TIMEOUT_SECONDS,
) -> Dict[str, Any]:
    return _execute_protify_job(config, hf_token, wandb_api_key, synthyra_api_key, job_id, gpu_type, timeout_seconds)


@app.function(
    image=image,
    gpu="A10",
    volumes={"/data": volume},
    memory=(GPU_MEMORY_MIN, GPU_MEMORY_MAX),
    cpu=(GPU_CPU_MIN, GPU_CPU_MAX),
    max_containers=MAX_CONTAINERS_GPU,
    scaledown_window=SCALEDOWN_WINDOW_GPU,
    timeout=TIMEOUT_SECONDS,
)
def run_protify_job_a10(
    config: Dict[str, Any],
    hf_token: Optional[str] = None,
    wandb_api_key: Optional[str] = None,
    synthyra_api_key: Optional[str] = None,
    job_id: Optional[str] = None,
    gpu_type: Optional[str] = None,
    timeout_seconds: int = TIMEOUT_SECONDS,
) -> Dict[str, Any]:
    return _execute_protify_job(config, hf_token, wandb_api_key, synthyra_api_key, job_id, gpu_type, timeout_seconds)


@app.function(
    image=image,
    gpu="L4",
    volumes={"/data": volume},
    memory=(GPU_MEMORY_MIN, GPU_MEMORY_MAX),
    cpu=(GPU_CPU_MIN, GPU_CPU_MAX),
    max_containers=MAX_CONTAINERS_GPU,
    scaledown_window=SCALEDOWN_WINDOW_GPU,
    timeout=TIMEOUT_SECONDS,
)
def run_protify_job_l4(
    config: Dict[str, Any],
    hf_token: Optional[str] = None,
    wandb_api_key: Optional[str] = None,
    synthyra_api_key: Optional[str] = None,
    job_id: Optional[str] = None,
    gpu_type: Optional[str] = None,
    timeout_seconds: int = TIMEOUT_SECONDS,
) -> Dict[str, Any]:
    return _execute_protify_job(config, hf_token, wandb_api_key, synthyra_api_key, job_id, gpu_type, timeout_seconds)


@app.function(
    image=image,
    gpu="T4",
    volumes={"/data": volume},
    memory=(GPU_MEMORY_MIN, GPU_MEMORY_MAX),
    cpu=(GPU_CPU_MIN, GPU_CPU_MAX),
    max_containers=MAX_CONTAINERS_GPU,
    scaledown_window=SCALEDOWN_WINDOW_GPU,
    timeout=TIMEOUT_SECONDS,
)
def run_protify_job_t4(
    config: Dict[str, Any],
    hf_token: Optional[str] = None,
    wandb_api_key: Optional[str] = None,
    synthyra_api_key: Optional[str] = None,
    job_id: Optional[str] = None,
    gpu_type: Optional[str] = None,
    timeout_seconds: int = TIMEOUT_SECONDS,
) -> Dict[str, Any]:
    return _execute_protify_job(config, hf_token, wandb_api_key, synthyra_api_key, job_id, gpu_type, timeout_seconds)


gpu_functions = {
    "H200": run_protify_job_h200,
    "H100": run_protify_job_h100,
    "A100-80GB": run_protify_job_a100_80gb,
    "A100": run_protify_job_a100,
    "L40S": run_protify_job_l40s,
    "A10": run_protify_job_a10,
    "L4": run_protify_job_l4,
    "T4": run_protify_job_t4,
}


@app.function(
    image=image,
    volumes={"/data": volume},
    memory=(CPU_MEMORY_MIN, CPU_MEMORY_MAX),
    cpu=(CPU_COUNT_MIN, CPU_COUNT_MAX),
    max_containers=MAX_CONTAINERS_CPU,
    scaledown_window=SCALEDOWN_WINDOW_CPU,
)
def submit_protify_job(
    config: Dict[str, Any],
    gpu_type: str = PROTIFY_DEFAULT_GPU,
    hf_token: Optional[str] = None,
    wandb_api_key: Optional[str] = None,
    synthyra_api_key: Optional[str] = None,
    timeout_seconds: int = TIMEOUT_SECONDS,
    job_id: Optional[str] = None,
) -> Dict[str, Any]:
    if job_id is None:
        job_id = _generate_job_id()

    selected_gpu = gpu_type if gpu_type in AVAILABLE_GPUS else PROTIFY_DEFAULT_GPU
    _update_job_status(
        job_id,
        {
            "status": "PENDING",
            "phase": "queued",
            "gpu_type": selected_gpu,
            "last_heartbeat_utc": _now_utc_iso(),
            "error": None,
        },
    )

    selected_gpu_function = gpu_functions[selected_gpu]
    handle = selected_gpu_function.spawn(
        config=config,
        hf_token=hf_token,
        wandb_api_key=wandb_api_key,
        synthyra_api_key=synthyra_api_key,
        job_id=job_id,
        gpu_type=selected_gpu,
        timeout_seconds=timeout_seconds,
    )
    function_call_id = handle.object_id
    _update_job_status(
        job_id,
        {
            "status": "RUNNING",
            "phase": "queued",
            "function_call_id": function_call_id,
            "last_heartbeat_utc": _now_utc_iso(),
        },
    )
    return {
        "success": True,
        "job_id": job_id,
        "function_call_id": function_call_id,
        "status": "RUNNING",
        "gpu_type": selected_gpu,
    }


@app.function(
    image=image,
    volumes={"/data": volume},
    memory=(CPU_MEMORY_MIN, CPU_MEMORY_MAX),
    cpu=(CPU_COUNT_MIN, CPU_COUNT_MAX),
    max_containers=MAX_CONTAINERS_CPU,
    scaledown_window=SCALEDOWN_WINDOW_CPU,
)
def get_job_status(job_id: str) -> Dict[str, Any]:
    volume.reload()
    status_store = _safe_read_json(STATUS_FILE_PATH)
    if job_id not in status_store:
        return {"success": False, "job_id": job_id, "error": "Job ID not found."}

    job_status = status_store[job_id]
    heartbeat_age_seconds = None
    if "last_heartbeat_utc" in job_status and job_status["last_heartbeat_utc"]:
        try:
            heartbeat_time = datetime.fromisoformat(job_status["last_heartbeat_utc"])
            heartbeat_age_seconds = (datetime.now(timezone.utc) - heartbeat_time).total_seconds()
        except Exception:
            heartbeat_age_seconds = None
    job_status["heartbeat_age_seconds"] = heartbeat_age_seconds
    job_status["success"] = True
    return job_status


@app.function(
    image=image,
    volumes={"/data": volume},
    memory=(CPU_MEMORY_MIN, CPU_MEMORY_MAX),
    cpu=(CPU_COUNT_MIN, CPU_COUNT_MAX),
    max_containers=MAX_CONTAINERS_CPU,
    scaledown_window=SCALEDOWN_WINDOW_CPU,
)
def get_job_log_tail(job_id: str, max_chars: int = 5000) -> Dict[str, Any]:
    volume.reload()
    status_store = _safe_read_json(STATUS_FILE_PATH)
    status_entry = status_store[job_id] if job_id in status_store else None
    if status_entry is not None and "log_file_path" in status_entry and status_entry["log_file_path"]:
        log_file_path = status_entry["log_file_path"]
    else:
        log_file_path = os.path.join(LOG_DIR_DEFAULT, f"{job_id}.txt")

    if not os.path.exists(log_file_path):
        if status_entry is None:
            return {"success": False, "job_id": job_id, "error": "Job ID not found.", "log_tail": ""}
        return {"success": True, "job_id": job_id, "log_tail": ""}

    with open(log_file_path, "r", encoding="utf-8", errors="ignore") as log_file:
        text = log_file.read()
    return {"success": True, "job_id": job_id, "log_tail": _tail_text(text, max_chars)}


@app.function(
    image=image,
    volumes={"/data": volume},
    memory=(CPU_MEMORY_MIN, CPU_MEMORY_MAX),
    cpu=(CPU_COUNT_MIN, CPU_COUNT_MAX),
    max_containers=MAX_CONTAINERS_CPU,
    scaledown_window=SCALEDOWN_WINDOW_CPU,
)
def get_job_log_delta(job_id: str, offset: int = 0, max_chars: int = 5000) -> Dict[str, Any]:
    volume.reload()
    if offset < 0:
        offset = 0
    if max_chars <= 0:
        max_chars = 1

    status_store = _safe_read_json(STATUS_FILE_PATH)
    status_entry = status_store[job_id] if job_id in status_store else None
    if status_entry is not None and "log_file_path" in status_entry and status_entry["log_file_path"]:
        log_file_path = status_entry["log_file_path"]
    else:
        log_file_path = os.path.join(LOG_DIR_DEFAULT, f"{job_id}.txt")

    if not os.path.exists(log_file_path):
        return {
            "success": True,
            "job_id": job_id,
            "file_exists": False,
            "chunk": "",
            "next_offset": offset,
            "file_size": 0,
        }

    with open(log_file_path, "r", encoding="utf-8", errors="ignore") as log_file:
        text = log_file.read()
    file_size = len(text)
    if offset > file_size:
        offset = file_size
    end_offset = offset + max_chars
    if end_offset > file_size:
        end_offset = file_size
    chunk = text[offset:end_offset]
    return {
        "success": True,
        "job_id": job_id,
        "file_exists": True,
        "chunk": chunk,
        "next_offset": end_offset,
        "file_size": file_size,
    }


@app.function(
    image=image,
    volumes={"/data": volume},
    memory=(CPU_MEMORY_MIN, CPU_MEMORY_MAX),
    cpu=(CPU_COUNT_MIN, CPU_COUNT_MAX),
    max_containers=MAX_CONTAINERS_CPU,
    scaledown_window=SCALEDOWN_WINDOW_CPU,
)
def delete_modal_embeddings() -> Dict[str, Any]:
    volume.reload()
    embedding_dir = Path(EMBED_DIR_DEFAULT)
    if not embedding_dir.exists():
        return {
            "success": True,
            "message": f"Embedding directory does not exist: {EMBED_DIR_DEFAULT}",
            "deleted_files": 0,
            "deleted_dirs": 0,
        }

    deleted_files = 0
    deleted_dirs = 0
    for path in embedding_dir.glob("*"):
        if path.is_file():
            path.unlink()
            deleted_files += 1
        elif path.is_dir():
            shutil.rmtree(path)
            deleted_dirs += 1

    volume.commit()
    return {
        "success": True,
        "message": f"Deleted modal embedding cache contents ({deleted_files} files, {deleted_dirs} directories).",
        "deleted_files": deleted_files,
        "deleted_dirs": deleted_dirs,
    }


@app.function(
    image=image,
    volumes={"/data": volume},
    memory=(CPU_MEMORY_MIN, CPU_MEMORY_MAX),
    cpu=(CPU_COUNT_MIN, CPU_COUNT_MAX),
    max_containers=MAX_CONTAINERS_CPU,
    scaledown_window=SCALEDOWN_WINDOW_CPU,
)
def cancel_protify_job(function_call_id: str, job_id: Optional[str] = None) -> Dict[str, Any]:
    function_call = modal.FunctionCall.from_id(function_call_id)
    function_call.cancel()
    if job_id is not None:
        _update_job_status(
            job_id,
            {
                "status": "TERMINATED",
                "phase": "cancelled",
                "last_heartbeat_utc": _now_utc_iso(),
                "finished_at_utc": _now_utc_iso(),
            },
        )
    return {"success": True, "function_call_id": function_call_id, "job_id": job_id}


@app.function(
    image=image,
    volumes={"/data": volume},
    memory=(CPU_MEMORY_MIN, CPU_MEMORY_MAX),
    cpu=(CPU_COUNT_MIN, CPU_COUNT_MAX),
    max_containers=MAX_CONTAINERS_CPU,
    scaledown_window=SCALEDOWN_WINDOW_CPU,
)
def get_results(job_id: str) -> Dict[str, Any]:
    volume.reload()
    image_extensions = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".svg", ".webp"}
    results = {"success": True, "files": {}, "images": {}}

    results_dir = Path(RESULTS_DIR_DEFAULT)
    plots_dir = Path(PLOTS_DIR_DEFAULT)
    logs_dir = Path(LOG_DIR_DEFAULT)

    collected_files = set()
    result_file = results_dir / f"{job_id}.tsv"
    if result_file.exists():
        collected_files.add(result_file)
    log_file = logs_dir / f"{job_id}.txt"
    if log_file.exists():
        collected_files.add(log_file)
    plot_dir = plots_dir / job_id
    if plot_dir.exists() and plot_dir.is_dir():
        for file_path in plot_dir.rglob("*"):
            if file_path.is_file():
                collected_files.add(file_path)

    for file_path in collected_files:
        relative_path = str(file_path.relative_to(Path("/data")))
        suffix = file_path.suffix.lower()
        try:
            if suffix in image_extensions:
                with open(file_path, "rb") as image_file:
                    encoded = base64.b64encode(image_file.read()).decode("utf-8")
                mime_type = f"image/{suffix[1:]}" if suffix != ".svg" else "image/svg+xml"
                results["images"][relative_path] = {"data": encoded, "mime_type": mime_type}
            else:
                with open(file_path, "r", encoding="utf-8", errors="ignore") as text_file:
                    results["files"][relative_path] = text_file.read()
        except Exception as error:
            if suffix in image_extensions:
                results["images"][relative_path] = {"error": str(error)}
            else:
                results["files"][relative_path] = f"Error reading file: {error}"

    return results


@app.function(
    image=image,
    volumes={"/data": volume},
    memory=(CPU_MEMORY_MIN, CPU_MEMORY_MAX),
    cpu=(CPU_COUNT_MIN, CPU_COUNT_MAX),
    max_containers=MAX_CONTAINERS_CPU,
    scaledown_window=SCALEDOWN_WINDOW_CPU,
)
def list_jobs() -> Dict[str, Any]:
    volume.reload()
    status_store = _safe_read_json(STATUS_FILE_PATH)
    jobs = []
    for job_id in status_store:
        jobs.append(status_store[job_id])
    jobs.sort(key=lambda item: item["job_id"], reverse=True)
    return {"success": True, "jobs": jobs}


if __name__ == "__main__":
    with app.run():
        pass