forithmus 0.1.0__py3-none-any.whl

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.

Potentially problematic release.


This version of forithmus might be problematic. Click here for more details.

@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.4
2
+ Name: forithmus
3
+ Version: 0.1.0
4
+ Summary: CLI tool for the Forithmus Research Hub
5
+ Author-email: Forithmus <contact@forithmus.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://research.forithmus.com
8
+ Project-URL: Documentation, https://research.forithmus.com/getting-started
9
+ Project-URL: Repository, https://github.com/forithmus/cli
10
+ Keywords: medical-imaging,ai,challenges,benchmarks,docker
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: typer>=0.9.0
24
+ Requires-Dist: httpx>=0.25.0
25
+ Requires-Dist: numpy>=1.24.0
26
+ Requires-Dist: rich>=13.0.0
27
+ Provides-Extra: medical
28
+ Requires-Dist: nibabel>=5.0.0; extra == "medical"
29
+ Requires-Dist: Pillow>=10.0.0; extra == "medical"
30
+ Provides-Extra: docker
31
+ Requires-Dist: docker>=7.0.0; extra == "docker"
@@ -0,0 +1,14 @@
1
+ forithmus_cli/__init__.py,sha256=1rXTqr5RBLO-NT-c-FTTn-nXEaajWdCUxUlHCxzDPRE,106
2
+ forithmus_cli/api.py,sha256=i5LyvY3OmvnaeRfdhoLwrgjcuwgJZGOMrPwcctlrbAg,5555
3
+ forithmus_cli/auth.py,sha256=eUtbHxKDIszvIAnjzmxYRTC9ki768jv4jtTcnlA9b4o,7540
4
+ forithmus_cli/branding.py,sha256=Wj5-xhpyif97DdZuTFrMZrnfPQwHGqJSE-yoWwSFa0o,980
5
+ forithmus_cli/buddy.py,sha256=AyhCB8u4qGIDWG3x52DgKZYDhrsgvMes2ZhNwnnMnLg,10356
6
+ forithmus_cli/docker_runner.py,sha256=AZC3x_abtIpMhnH7pKATMiKG1pwNFfdZrMef_RYLsPE,1921
7
+ forithmus_cli/main.py,sha256=rJD5ML5Tuzjh1pjkKV3dzgQgJzK_H7bUiDut8ZljdXg,22604
8
+ forithmus_cli/schema.py,sha256=Caclnqt8vDqWBWQUp7doMxpAXrtOxOGwn7tZjL3D2UI,12005
9
+ forithmus_cli/validator.py,sha256=LpqqQXU7E2Wnq4FYQM4hOtOEMsI9G8LqIVkBhDuN8AI,25829
10
+ forithmus-0.1.0.dist-info/METADATA,sha256=j3tiJ6J_05kuRLfBF69RVrD-n2gzzH28zpwcvZXfCgo,1315
11
+ forithmus-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
12
+ forithmus-0.1.0.dist-info/entry_points.txt,sha256=9zuONYonSzdmFQ5V56BkrH8SiRpEXTRmOyCD-jlnndg,53
13
+ forithmus-0.1.0.dist-info/top_level.txt,sha256=aIW3xV8CP-R85ddIbtZB2jmrGO94wMVREsIBZe_e7w4,14
14
+ forithmus-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ forithmus = forithmus_cli.main:app
@@ -0,0 +1 @@
1
+ forithmus_cli
@@ -0,0 +1,2 @@
1
+ """forithmus-cli: Local validation + submission tool for Forithmus Research Hub."""
2
+ __version__ = "0.1.0"
forithmus_cli/api.py ADDED
@@ -0,0 +1,156 @@
1
+ from __future__ import annotations
2
+ """API client for the Forithmus Research Hub."""
3
+ import sys
4
+ from pathlib import Path
5
+
6
+ import httpx
7
+ from rich.console import Console
8
+ from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, TimeElapsedColumn
9
+
10
+ from forithmus_cli.auth import get_api_url, get_token
11
+
12
+ console = Console()
13
+
14
+
15
+ def _headers() -> dict:
16
+ token = get_token()
17
+ h = {"X-Requested-With": "XMLHttpRequest"}
18
+ if token:
19
+ h["Authorization"] = f"Bearer {token}"
20
+ return h
21
+
22
+
23
+ def api_get(path: str, params: dict | None = None):
24
+ """GET request to the API. Returns parsed JSON or None."""
25
+ url = get_api_url()
26
+ try:
27
+ res = httpx.get(f"{url}{path}", headers=_headers(), params=params, timeout=30)
28
+ if res.status_code == 200:
29
+ return res.json()
30
+ if res.status_code == 401:
31
+ console.print("[red]Session expired. Run: forithmus login[/red]")
32
+ return None
33
+ return None
34
+ except httpx.RequestError as e:
35
+ console.print(f"[red]Connection error: {e}[/red]")
36
+ return None
37
+
38
+
39
+ def api_post(path: str, data=None, files=None, timeout=30):
40
+ """POST request to the API. Returns parsed JSON or None."""
41
+ url = get_api_url()
42
+ try:
43
+ if files:
44
+ res = httpx.post(f"{url}{path}", headers=_headers(), files=files, timeout=timeout)
45
+ else:
46
+ res = httpx.post(f"{url}{path}", headers=_headers(), json=data, timeout=timeout)
47
+ if res.status_code < 400:
48
+ return res.json()
49
+ detail = "Unknown error"
50
+ try:
51
+ detail = res.json().get("detail", detail)
52
+ except Exception:
53
+ pass
54
+ console.print(f"[red]Error ({res.status_code}): {detail}[/red]")
55
+ return None
56
+ except httpx.RequestError as e:
57
+ console.print(f"[red]Connection error: {e}[/red]")
58
+ return None
59
+
60
+
61
+ def upload_file(path: str, endpoint: str, field_name: str = "file",
62
+ extra_fields: dict | None = None, desc: str = "Uploading") -> dict | None:
63
+ """Upload a file with progress bar. Returns API response or None."""
64
+ url = get_api_url()
65
+ filepath = Path(path)
66
+ if not filepath.exists():
67
+ console.print(f"[red]File not found: {path}[/red]")
68
+ return None
69
+
70
+ file_size = filepath.stat().st_size
71
+ size_mb = file_size / (1024 * 1024)
72
+
73
+ with Progress(
74
+ SpinnerColumn(),
75
+ TextColumn("[progress.description]{task.description}"),
76
+ BarColumn(),
77
+ TextColumn("[progress.percentage]{task.percentage:>3.0f}%"),
78
+ TimeElapsedColumn(),
79
+ console=console,
80
+ ) as progress:
81
+ task = progress.add_task(f"{desc} ({size_mb:.0f} MB)", total=file_size)
82
+
83
+ def _read_chunks(f, chunk_size=1024 * 1024):
84
+ while True:
85
+ chunk = f.read(chunk_size)
86
+ if not chunk:
87
+ break
88
+ progress.update(task, advance=len(chunk))
89
+ yield chunk
90
+
91
+ with open(filepath, "rb") as f:
92
+ headers = _headers()
93
+ fields = extra_fields or {}
94
+
95
+ try:
96
+ # Stream file in chunks to avoid loading entire file into memory
97
+ # (Docker images can be multiple GB)
98
+ files_dict = {field_name: (filepath.name, _read_chunks(f), "application/octet-stream")}
99
+ data_dict = {k: str(v) for k, v in fields.items()} if fields else None
100
+
101
+ with httpx.Client(timeout=httpx.Timeout(600.0, connect=30.0)) as client:
102
+ res = client.post(
103
+ f"{url}{endpoint}",
104
+ headers=headers,
105
+ files=files_dict,
106
+ data=data_dict,
107
+ timeout=httpx.Timeout(600.0, connect=30.0),
108
+ )
109
+
110
+ if res.status_code < 400:
111
+ return res.json()
112
+
113
+ detail = "Upload failed"
114
+ try:
115
+ detail = res.json().get("detail", detail)
116
+ except Exception:
117
+ pass
118
+ console.print(f"[red]Error ({res.status_code}): {detail}[/red]")
119
+ return None
120
+
121
+ except httpx.RequestError as e:
122
+ console.print(f"[red]Upload failed: {e}[/red]")
123
+ return None
124
+
125
+
126
+ def poll_status(endpoint: str, key: str = "status", target: str = "ready",
127
+ fail_values: set | None = None, interval: float = 3.0,
128
+ timeout: float = 600.0, desc: str = "Processing") -> str | None:
129
+ """Poll an endpoint until status reaches target or fails. Returns final status."""
130
+ import time
131
+ fail_values = fail_values or {"failed", "rejected"}
132
+ url = get_api_url()
133
+ start = time.time()
134
+
135
+ with Progress(
136
+ SpinnerColumn(),
137
+ TextColumn(f"[progress.description]{desc}..."),
138
+ TimeElapsedColumn(),
139
+ console=console,
140
+ ) as progress:
141
+ task = progress.add_task(desc, total=None)
142
+ while time.time() - start < timeout:
143
+ try:
144
+ res = httpx.get(f"{url}{endpoint}", headers=_headers(), timeout=10)
145
+ if res.status_code == 200:
146
+ status = res.json().get(key, "")
147
+ if status == target:
148
+ return status
149
+ if status in fail_values:
150
+ return status
151
+ except Exception:
152
+ pass
153
+ time.sleep(interval)
154
+
155
+ console.print(f"[yellow]Timed out waiting for {target}[/yellow]")
156
+ return None
forithmus_cli/auth.py ADDED
@@ -0,0 +1,213 @@
1
+ from __future__ import annotations
2
+ """Authentication: browser-based login with server-side polling, token management."""
3
+ import json
4
+ import secrets
5
+ import time
6
+ import webbrowser
7
+ from pathlib import Path
8
+
9
+ import httpx
10
+ import typer
11
+ from rich.console import Console
12
+ from rich.panel import Panel
13
+
14
+ console = Console()
15
+ CONFIG_DIR = Path.home() / ".forithmus"
16
+ TOKEN_FILE = CONFIG_DIR / "credentials.json"
17
+
18
+
19
+ def get_api_url() -> str:
20
+ if TOKEN_FILE.exists():
21
+ data = json.loads(TOKEN_FILE.read_text())
22
+ return data.get("api_url", "https://research.forithmus.com/api")
23
+ return "https://research.forithmus.com/api"
24
+
25
+
26
+ def get_token() -> str | None:
27
+ """Get the current access token, refreshing if expired."""
28
+ if not TOKEN_FILE.exists():
29
+ return None
30
+ data = json.loads(TOKEN_FILE.read_text())
31
+ token = data.get("access_token")
32
+ if not token:
33
+ return None
34
+ try:
35
+ import base64
36
+ payload_b64 = token.split(".")[1]
37
+ payload_b64 += "=" * (4 - len(payload_b64) % 4)
38
+ payload = json.loads(base64.b64decode(payload_b64))
39
+ if payload.get("exp", 0) < time.time() - 60:
40
+ new_token = _refresh_token()
41
+ return new_token
42
+ except Exception:
43
+ pass
44
+ return token
45
+
46
+
47
+ def get_credentials() -> dict | None:
48
+ if not TOKEN_FILE.exists():
49
+ return None
50
+ return json.loads(TOKEN_FILE.read_text())
51
+
52
+
53
+ def save_credentials(api_url: str, access_token: str, refresh_token: str):
54
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
55
+ TOKEN_FILE.write_text(json.dumps({
56
+ "api_url": api_url,
57
+ "access_token": access_token,
58
+ "refresh_token": refresh_token,
59
+ }, indent=2))
60
+ TOKEN_FILE.chmod(0o600)
61
+
62
+
63
+ def _refresh_token() -> str | None:
64
+ if not TOKEN_FILE.exists():
65
+ return None
66
+ data = json.loads(TOKEN_FILE.read_text())
67
+ refresh = data.get("refresh_token")
68
+ api_url = data.get("api_url", "https://research.forithmus.com")
69
+ if not refresh:
70
+ return None
71
+ try:
72
+ res = httpx.post(f"{api_url}/auth/refresh", json={"refresh_token": refresh}, timeout=10)
73
+ if res.status_code == 200:
74
+ new_data = res.json()
75
+ save_credentials(api_url, new_data["access_token"], new_data.get("refresh_token", refresh))
76
+ return new_data["access_token"]
77
+ except Exception:
78
+ pass
79
+ return None
80
+
81
+
82
+ def _get_frontend_url(api_url: str) -> str:
83
+ """Resolve frontend URL from API URL.
84
+ Production: https://research.forithmus.com/api -> https://research.forithmus.com
85
+ Dev: http://localhost:3001 -> http://localhost:5181"""
86
+ if ":3001" in api_url:
87
+ return api_url.replace(":3001", ":5181")
88
+ # Strip /api suffix for production
89
+ if api_url.endswith("/api"):
90
+ return api_url[:-4]
91
+ return api_url
92
+
93
+
94
+ # ─── Browser-based auth with server-side polling ───
95
+
96
+
97
+ def login_cmd(url: str):
98
+ """Browser-based login: open browser, poll server for completion."""
99
+ api_url = url.rstrip("/")
100
+ if not api_url.startswith("http"):
101
+ api_url = f"https://{api_url}"
102
+ # Security: enforce HTTPS except for localhost development
103
+ if api_url.startswith("http://") and "localhost" not in api_url and "127.0.0.1" not in api_url:
104
+ console.print("[red]Refusing to connect over insecure HTTP. Use HTTPS.[/red]")
105
+ raise SystemExit(1)
106
+
107
+ # Create a CLI auth session on the server
108
+ session_id = secrets.token_urlsafe(32)
109
+
110
+ try:
111
+ res = httpx.post(f"{api_url}/auth/cli-session", json={"session_id": session_id}, timeout=10)
112
+ if res.status_code != 200:
113
+ console.print("[red]Could not create auth session. Check your internet connection and try again.[/red]")
114
+ raise SystemExit(1)
115
+ except httpx.RequestError:
116
+ console.print("[red]Could not reach the server. Check your internet connection and try again.[/red]")
117
+ raise SystemExit(1)
118
+
119
+ # Build the login URL
120
+ frontend_url = _get_frontend_url(api_url)
121
+ auth_url = f"{frontend_url}/login?cli=true&session={session_id}"
122
+
123
+ # Open browser
124
+ console.print("[dim]Opening browser for authentication...[/dim]")
125
+ try:
126
+ webbrowser.open(auth_url)
127
+ except Exception:
128
+ pass
129
+
130
+ console.print()
131
+ console.print(f" [bold]Login URL:[/bold]")
132
+ console.print(f" [cyan]{auth_url}[/cyan]")
133
+ console.print()
134
+ console.print(" [dim]Log in via the browser. The CLI will detect it automatically.[/dim]")
135
+ console.print(" [dim]Press Ctrl+C to cancel.[/dim]")
136
+ console.print()
137
+
138
+ # Poll the server for completion
139
+ try:
140
+ with console.status("[bold cyan]Waiting for browser authentication...[/bold cyan]"):
141
+ deadline = time.time() + 300 # 5 minute timeout
142
+ while time.time() < deadline:
143
+ time.sleep(2)
144
+ try:
145
+ poll_res = httpx.get(
146
+ f"{api_url}/auth/cli-session/{session_id}",
147
+ timeout=10,
148
+ )
149
+ if poll_res.status_code == 200:
150
+ data = poll_res.json()
151
+ if data.get("status") == "authenticated":
152
+ save_credentials(api_url, data["access_token"], data["refresh_token"])
153
+ _print_auth_success(data, api_url)
154
+ return
155
+ except httpx.RequestError:
156
+ pass # Network blip, keep polling
157
+
158
+ console.print("[yellow]Timed out waiting for browser login (5 minutes).[/yellow]")
159
+ console.print("[dim]Run forithmus login to try again.[/dim]")
160
+
161
+ except KeyboardInterrupt:
162
+ console.print("\n[dim]Cancelled.[/dim]")
163
+
164
+
165
+
166
+ def _print_auth_success(data: dict, api_url: str):
167
+ """Display authenticated success message."""
168
+ user = data.get("user", {})
169
+ name = f"{user.get('first_name', '')} {user.get('last_name', '')}".strip()
170
+ email = user.get("email", "")
171
+ role = user.get("platform_role", "user")
172
+ credits = user.get("platform_credits", 0)
173
+
174
+ console.print()
175
+ console.print(Panel(
176
+ f"[bold green]Authenticated[/bold green]\n\n"
177
+ f" [bold]{name}[/bold]\n"
178
+ f" [dim]{email}[/dim]\n"
179
+ f" [dim]{role}[/dim] [dim cyan]${credits:.2f} credits[/dim cyan]",
180
+ border_style="green",
181
+ padding=(1, 3),
182
+ ))
183
+ console.print()
184
+ console.print(" [dim]Get started:[/dim]")
185
+ console.print(" forithmus challenges [dim]List your challenges[/dim]")
186
+ console.print(" forithmus init <slug> [dim]Set up local config[/dim]")
187
+ console.print(" forithmus submit <file> [dim]Submit to platform[/dim]")
188
+ console.print()
189
+
190
+
191
+ def logout_cmd():
192
+ if TOKEN_FILE.exists():
193
+ TOKEN_FILE.unlink()
194
+ console.print("[green]Logged out.[/green]")
195
+ else:
196
+ console.print("[dim]Not logged in.[/dim]")
197
+
198
+
199
+ def whoami_cmd():
200
+ token = get_token()
201
+ if not token:
202
+ console.print("[yellow]Not logged in. Run: forithmus login[/yellow]")
203
+ return
204
+ from forithmus_cli.api import api_get
205
+ user = api_get("/users/me")
206
+ if user:
207
+ console.print(f"[bold]{user.get('first_name', '')} {user.get('last_name', '')}[/bold]")
208
+ console.print(f"Email: {user.get('email', '')}")
209
+ console.print(f"Role: {user.get('platform_role', 'user')}")
210
+ console.print(f"Credits: ${user.get('platform_credits', 0):.2f}")
211
+ console.print(f"API: {get_api_url()}")
212
+ else:
213
+ console.print("[red]Failed to fetch user info. Try: forithmus login[/red]")
@@ -0,0 +1,29 @@
1
+ """Branding and terminal art for Forithmus CLI."""
2
+ from rich.console import Console
3
+ from rich.panel import Panel
4
+
5
+ LOGO = r"""
6
+ ______ _ __ __
7
+ / ____/___ _____(_) /_/ /_ ____ ___ __ _______
8
+ / /_ / __ \/ ___/ / __/ __ \/ __ `__ \/ / / / ___/
9
+ / __/ / /_/ / / / / /_/ / / / / / / / / /_/ (__ )
10
+ /_/ \____/_/ /_/\__/_/ /_/_/ /_/ /_/\__,_/____/
11
+ """
12
+
13
+ VERSION = "0.1.0"
14
+
15
+ def print_banner(console: Console):
16
+ """Print the Forithmus CLI banner."""
17
+ console.print()
18
+ console.print(LOGO, style="bold cyan", highlight=False)
19
+ console.print(" [bold white]Forithmus[/bold white] [dim]Research Hub CLI[/dim]")
20
+ console.print(f" [dim cyan]v{VERSION}[/dim cyan]")
21
+ console.print()
22
+
23
+
24
+ def print_header(console: Console, title: str, subtitle: str = ""):
25
+ """Print a section header."""
26
+ text = f"[bold]{title}[/bold]"
27
+ if subtitle:
28
+ text += f"\n[dim]{subtitle}[/dim]"
29
+ console.print(Panel(text, border_style="cyan", padding=(0, 2)))