File size: 2,883 Bytes
932dcdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# -*- coding: utf-8 -*-
"""
Модель проектирования микрофлюидных чипов V16.1 — локальный запуск.

Команда:
    python app.py
"""
from __future__ import annotations

import importlib.util
import os
from pathlib import Path
import subprocess
import sys
import threading
import time
import urllib.request
import webbrowser

APP_DIR = Path(__file__).resolve().parent
NOTEBOOK = APP_DIR / "app.ipynb"
OUTPUT_DIR = APP_DIR / "model_outputs"

HOST = os.environ.get("MICROFLUIDIC_HOST", "127.0.0.1")
PORT = int(os.environ.get("MICROFLUIDIC_PORT", "8866"))
URL = f"http://{HOST}:{PORT}/"

def _check_dependencies() -> None:
    required = {
        "voila": "voila",
        "ipywidgets": "ipywidgets",
        "numpy": "numpy",
        "pandas": "pandas",
        "matplotlib": "matplotlib",
        "scipy": "scipy",
        "sklearn": "scikit-learn",
        "torch": "torch",
        "requests": "requests",
        "openpyxl": "openpyxl",
    }
    missing = [pip_name for module, pip_name in required.items()
               if importlib.util.find_spec(module) is None]
    if missing:
        print("\nНе установлены зависимости:", ", ".join(missing))
        print("Сначала выполните:")
        print(f'  "{sys.executable}" -m pip install -r "{APP_DIR / "requirements.txt"}"' )
        raise SystemExit(1)

def _open_browser_when_ready(timeout: float = 60.0) -> None:
    deadline = time.time() + timeout
    while time.time() < deadline:
        try:
            with urllib.request.urlopen(URL, timeout=1.0):
                webbrowser.open(URL)
                return
        except Exception:
            time.sleep(0.4)
    webbrowser.open(URL)

def main() -> None:
    _check_dependencies()
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

    env = os.environ.copy()
    env["MEGANET_PINN_OUTPUT_DIR"] = str(OUTPUT_DIR)
    env["PYTHONUNBUFFERED"] = "1"

    print("Модель проектирования микрофлюидных чипов V16.1")
    print(f"Интерфейс откроется в браузере: {URL}")
    print("Для остановки нажмите Ctrl+C.\n")

    threading.Thread(target=_open_browser_when_ready, daemon=True).start()

    cmd = [
        sys.executable, "-m", "voila", str(NOTEBOOK),
        "--no-browser",
        f"--Voila.ip={HOST}",
        f"--Voila.port={PORT}",
        "--Voila.theme=light",
        "--Voila.show_tracebacks=True",
    ]

    try:
        subprocess.run(cmd, cwd=str(APP_DIR), env=env, check=True)
    except KeyboardInterrupt:
        print("\nМодель остановлена.")
    except subprocess.CalledProcessError as exc:
        print(f"\nVoilà завершился с кодом {exc.returncode}.")
        raise SystemExit(exc.returncode)

if __name__ == "__main__":
    main()