formless 0.3.0__tar.gz → 0.4.0__tar.gz

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 formless might be problematic. Click here for more details.

@@ -35,5 +35,7 @@ jobs:
35
35
  # - name: Run tests
36
36
  # # For example, using `pytest`
37
37
  # run: uv run pytest tests
38
+ - name: Install pre-commit
39
+ run: uvx pre-commit install
38
40
  - name: Run pre-commit hooks
39
- run: uv run pre-commit run --all-files
41
+ run: uvx pre-commit run --all-files
@@ -199,6 +199,7 @@ cython_debug/
199
199
  #.idea/
200
200
 
201
201
  .vscode
202
+ .env.*
202
203
 
203
204
  # FastHTML
204
205
  .sesskey
@@ -1,10 +1,11 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: formless
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Handwritten + image OCR.
5
5
  License-File: LICENSE
6
6
  Requires-Python: >=3.12
7
7
  Requires-Dist: modal>=0.64.178
8
+ Requires-Dist: pre-commit>=4.0.1
8
9
  Requires-Dist: python-dotenv>=1.0.1
9
10
  Requires-Dist: requests>=2.32.3
10
11
  Requires-Dist: term-image>=0.7.2
@@ -41,10 +42,26 @@ Set up the environment:
41
42
 
42
43
  ```bash
43
44
  uv sync --all-extras --dev
44
- uv run pre-commit install
45
45
  modal setup
46
46
  ```
47
47
 
48
+ Create a `.env` (+ `.env.dev` + `.env.local`):
49
+
50
+ ```bash
51
+ API_URL=
52
+ HF_TOKEN=
53
+
54
+ LIVE=
55
+ DEBUG=
56
+ STRIPE_PUBLISHABLE_KEY=
57
+ STRIPE_SECRET_KEY=
58
+ STRIPE_WEBHOOK_SECRET=
59
+ DOMAIN=
60
+
61
+ WANDB_API_KEY=
62
+ WANDB_ENTITY=
63
+ ```
64
+
48
65
  ### Repository Structure
49
66
 
50
67
  ```bash
@@ -57,30 +74,51 @@ modal setup
57
74
 
58
75
  ### API
59
76
 
60
- Run the API:
77
+ Test the API:
61
78
 
62
79
  ```bash
63
80
  modal run api/app.py
64
81
  ```
65
82
 
66
- Deploy:
83
+ Run the API "locally":
84
+
85
+ ```bash
86
+ modal serve --env=dev api/app.py
87
+ ```
88
+
89
+ Deploy on dev:
67
90
 
68
91
  ```bash
69
- modal deploy api/app.py
92
+ modal deploy --env=dev api/app.py
93
+ ```
94
+
95
+ Deploy on main:
96
+
97
+ ```bash
98
+ modal deploy --env=main api/app.py
70
99
  ```
71
100
 
72
101
  ### Frontend
73
102
 
74
- Run the web app:
103
+ Run the web app "locally":
104
+
105
+ ```bash
106
+ modal serve --env=dev frontend/app.py
107
+ stripe listen --forward-to <url>/webhook
108
+ # update API_URL, STRIPE_WEBHOOK_SECRET, and DOMAIN in .env.dev
109
+ ```
110
+
111
+ Deploy on dev:
75
112
 
76
113
  ```bash
77
- modal serve frontend/app.py
114
+ modal deploy --env=dev frontend/app.py
115
+ # update API_URL, STRIPE_WEBHOOK_SECRET, and DOMAIN in .env.dev
78
116
  ```
79
117
 
80
- Deploy:
118
+ Deploy on main:
81
119
 
82
120
  ```bash
83
- modal deploy frontend/app.py
121
+ modal deploy --env=main frontend/app.py
84
122
  ```
85
123
 
86
124
  ### PyPI
@@ -89,6 +127,7 @@ Run the package:
89
127
 
90
128
  ```bash
91
129
  uv run formless -v
130
+ # update API_URL in src/formless/__init__.py
92
131
  ```
93
132
 
94
133
  Build the package:
@@ -29,10 +29,26 @@ Set up the environment:
29
29
 
30
30
  ```bash
31
31
  uv sync --all-extras --dev
32
- uv run pre-commit install
33
32
  modal setup
34
33
  ```
35
34
 
35
+ Create a `.env` (+ `.env.dev` + `.env.local`):
36
+
37
+ ```bash
38
+ API_URL=
39
+ HF_TOKEN=
40
+
41
+ LIVE=
42
+ DEBUG=
43
+ STRIPE_PUBLISHABLE_KEY=
44
+ STRIPE_SECRET_KEY=
45
+ STRIPE_WEBHOOK_SECRET=
46
+ DOMAIN=
47
+
48
+ WANDB_API_KEY=
49
+ WANDB_ENTITY=
50
+ ```
51
+
36
52
  ### Repository Structure
37
53
 
38
54
  ```bash
@@ -45,30 +61,51 @@ modal setup
45
61
 
46
62
  ### API
47
63
 
48
- Run the API:
64
+ Test the API:
49
65
 
50
66
  ```bash
51
67
  modal run api/app.py
52
68
  ```
53
69
 
54
- Deploy:
70
+ Run the API "locally":
71
+
72
+ ```bash
73
+ modal serve --env=dev api/app.py
74
+ ```
75
+
76
+ Deploy on dev:
55
77
 
56
78
  ```bash
57
- modal deploy api/app.py
79
+ modal deploy --env=dev api/app.py
80
+ ```
81
+
82
+ Deploy on main:
83
+
84
+ ```bash
85
+ modal deploy --env=main api/app.py
58
86
  ```
59
87
 
60
88
  ### Frontend
61
89
 
62
- Run the web app:
90
+ Run the web app "locally":
91
+
92
+ ```bash
93
+ modal serve --env=dev frontend/app.py
94
+ stripe listen --forward-to <url>/webhook
95
+ # update API_URL, STRIPE_WEBHOOK_SECRET, and DOMAIN in .env.dev
96
+ ```
97
+
98
+ Deploy on dev:
63
99
 
64
100
  ```bash
65
- modal serve frontend/app.py
101
+ modal deploy --env=dev frontend/app.py
102
+ # update API_URL, STRIPE_WEBHOOK_SECRET, and DOMAIN in .env.dev
66
103
  ```
67
104
 
68
- Deploy:
105
+ Deploy on main:
69
106
 
70
107
  ```bash
71
- modal deploy frontend/app.py
108
+ modal deploy --env=main frontend/app.py
72
109
  ```
73
110
 
74
111
  ### PyPI
@@ -77,6 +114,7 @@ Run the package:
77
114
 
78
115
  ```bash
79
116
  uv run formless -v
117
+ # update API_URL in src/formless/__init__.py
80
118
  ```
81
119
 
82
120
  Build the package:
@@ -5,9 +5,12 @@ from pathlib import Path
5
5
  from uuid import uuid4
6
6
 
7
7
  import modal
8
+ from fastapi import FastAPI, HTTPException, Request, Security
9
+ from fastapi.security import APIKeyHeader
8
10
  from PIL import ImageFile
9
11
 
10
12
  from utils import (
13
+ DATA_VOLUME,
11
14
  DEFAULT_IMG_URL,
12
15
  GPU_IMAGE,
13
16
  MINUTES,
@@ -16,11 +19,11 @@ from utils import (
16
19
  Colors,
17
20
  )
18
21
 
22
+ parent_path: Path = Path(__file__).parent
19
23
  ImageFile.LOAD_TRUNCATED_IMAGES = True
20
- # -----------------------------------------------------------------------------
21
24
 
25
+ # -----------------------------------------------------------------------------
22
26
 
23
- only_download = False # turn off gpu for initial download
24
27
  model = "meta-llama/Llama-3.2-11B-Vision-Instruct"
25
28
  gpu_memory_utilization = 0.90
26
29
  max_model_len = 8192
@@ -29,7 +32,7 @@ enforce_eager = True
29
32
 
30
33
  question = "What is the content of this image?"
31
34
  temperature = 0.2
32
- max_tokens = 128
35
+ max_tokens = 1024
33
36
 
34
37
  # -----------------------------------------------------------------------------
35
38
 
@@ -44,9 +47,26 @@ config = {k: str(v) if isinstance(v, Path) else v for k, v in config.items()} #
44
47
  # -----------------------------------------------------------------------------
45
48
 
46
49
 
50
+ # container build-time fns
51
+ def download_model():
52
+ from huggingface_hub import login, snapshot_download
53
+
54
+ login(token=os.getenv("HF_TOKEN"), new_session=False)
55
+ snapshot_download(
56
+ config["model"],
57
+ ignore_patterns=["*.pt", "*.bin"],
58
+ )
59
+
60
+
47
61
  # Modal
62
+ in_prod: bool = os.getenv("MODAL_ENVIRONMENT", "dev") == "main"
63
+ SECRETS = [modal.Secret.from_dotenv(path=parent_path, filename=".env" if in_prod else ".env.dev")]
48
64
  IMAGE = GPU_IMAGE.pip_install( # add Python dependencies
49
- "vllm==0.6.2", "term-image==0.7.2"
65
+ "vllm==0.6.2", "term-image==0.7.2", "python-fasthtml==0.6.10", "sqlite-utils==3.18"
66
+ ).run_function(
67
+ download_model,
68
+ secrets=SECRETS,
69
+ volumes=VOLUME_CONFIG,
50
70
  )
51
71
  API_TIMEOUT = 5 * MINUTES
52
72
  API_CONTAINER_IDLE_TIMEOUT = 1 * MINUTES # max
@@ -65,55 +85,58 @@ app = modal.App(name=APP_NAME)
65
85
  # -----------------------------------------------------------------------------
66
86
 
67
87
 
68
- # Model
69
- @app.cls(
88
+ # Main API
89
+ @app.function(
70
90
  image=IMAGE,
71
- gpu=None if only_download else GPU_CONFIG,
91
+ gpu=GPU_CONFIG,
72
92
  volumes=VOLUME_CONFIG,
73
- secrets=[modal.Secret.from_dotenv(path=Path(__file__).parent)],
93
+ secrets=SECRETS,
74
94
  timeout=API_TIMEOUT,
75
95
  container_idle_timeout=API_CONTAINER_IDLE_TIMEOUT,
76
96
  allow_concurrent_inputs=API_ALLOW_CONCURRENT_INPUTS,
77
97
  )
78
- class Model:
79
- @modal.enter() # what should a container do after it starts but before it gets input?
80
- async def download_model(self):
81
- from huggingface_hub import login, snapshot_download
82
- from vllm import LLM
83
-
84
- login(token=os.getenv("HF_TOKEN"), new_session=False)
85
- snapshot_download(
86
- config["model"],
87
- ignore_patterns=["*.pt", "*.bin"],
88
- )
89
-
90
- if config["only_download"]:
91
- return
92
-
93
- self.llm = LLM(
94
- model=config["model"],
95
- gpu_memory_utilization=config["gpu_memory_utilization"],
96
- max_model_len=config["max_model_len"],
97
- max_num_seqs=config["max_num_seqs"],
98
- enforce_eager=config["enforce_eager"],
99
- tensor_parallel_size=GPU_COUNT,
100
- )
101
-
102
- @modal.web_endpoint(method="POST")
103
- async def infer(self, request: dict) -> str:
104
- if config["only_download"]:
105
- return ""
106
-
107
- import requests
108
- from PIL import Image
109
- from term_image.image import from_file
110
- from vllm import SamplingParams
98
+ @modal.asgi_app()
99
+ def modal_get():
100
+ import requests
101
+ from fasthtml import common as fh
102
+ from PIL import Image
103
+ from term_image.image import from_file
104
+ from vllm import LLM, SamplingParams
105
+
106
+ f_app = FastAPI()
107
+
108
+ db_path = f"/{DATA_VOLUME}/main.db"
109
+ tables = fh.database(db_path).t
110
+ api_keys = tables.api_keys
111
+ if api_keys not in tables:
112
+ api_keys.create(api_key=str, pk="api_key")
113
+ ApiKey = api_keys.dataclass()
114
+
115
+ llm = LLM(
116
+ model=config["model"],
117
+ gpu_memory_utilization=config["gpu_memory_utilization"],
118
+ max_model_len=config["max_model_len"],
119
+ max_num_seqs=config["max_num_seqs"],
120
+ enforce_eager=config["enforce_eager"],
121
+ tensor_parallel_size=GPU_COUNT,
122
+ )
123
+
124
+ async def verify_api_key(
125
+ api_key_header: str = Security(APIKeyHeader(name="X-API-Key")),
126
+ ) -> bool:
127
+ if api_key_header in api_keys:
128
+ return True
129
+ raise HTTPException(status_code=401, detail="Could not validate credentials")
130
+
131
+ @f_app.post("/")
132
+ async def main(request: Request, api_key: bool = Security(verify_api_key)) -> str:
133
+ body = await request.json()
111
134
 
112
135
  start = time.monotonic_ns()
113
136
  request_id = uuid4()
114
137
  print(f"Generating response to request {request_id}")
115
138
 
116
- image_url = request.get("image_url")
139
+ image_url = body.get("image_url")
117
140
  response = requests.get(image_url, stream=True)
118
141
  response.raise_for_status()
119
142
  image = Image.open(response.raw).convert("RGB")
@@ -131,7 +154,7 @@ class Model:
131
154
  "multi_modal_data": {"image": image},
132
155
  }
133
156
 
134
- outputs = self.llm.generate(inputs, sampling_params=sampling_params)
157
+ outputs = llm.generate(inputs, sampling_params=sampling_params)
135
158
  generated_text = outputs[0].outputs[0].text.strip()
136
159
 
137
160
  # show the question, image, and response in the terminal for demonstration purposes
@@ -153,6 +176,14 @@ class Model:
153
176
 
154
177
  return generated_text
155
178
 
179
+ @f_app.post("/api-key")
180
+ async def apikey() -> str:
181
+ api_key = str(uuid4())
182
+ api_keys.insert(ApiKey(api_key=api_key))
183
+ return api_key
184
+
185
+ return f_app
186
+
156
187
 
157
188
  ## For testing
158
189
  @app.local_entrypoint()
@@ -161,12 +192,14 @@ def main(
161
192
  ):
162
193
  import requests
163
194
 
164
- model = Model()
195
+ response = requests.post(f"{modal_get.web_url}/api-key")
196
+ assert response.ok, response.status_code
197
+ api_key = response.json()
165
198
 
166
- response = requests.post(model.infer.web_url, json={"image_url": DEFAULT_IMG_URL})
199
+ response = requests.post(modal_get.web_url, json={"image_url": DEFAULT_IMG_URL}, headers={"X-API-Key": api_key})
167
200
  assert response.ok, response.status_code
168
201
 
169
202
  if twice:
170
203
  # second response is faster, because the Function is already running
171
- response = requests.post(model.infer.web_url, json={"image_url": DEFAULT_IMG_URL})
204
+ response = requests.post(modal_get.web_url, json={"image_url": DEFAULT_IMG_URL}, headers={"X-API-Key": api_key})
172
205
  assert response.ok, response.status_code
@@ -0,0 +1,475 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+ import modal
5
+
6
+ from utils import (
7
+ DATA_VOLUME,
8
+ MINUTES,
9
+ NAME,
10
+ PYTHON_VERSION,
11
+ VOLUME_CONFIG,
12
+ )
13
+
14
+ parent_path: Path = Path(__file__).parent
15
+ in_prod = os.getenv("MODAL_ENVIRONMENT", "dev") == "main"
16
+
17
+ # Modal
18
+ FE_IMAGE = (
19
+ modal.Image.debian_slim(python_version=PYTHON_VERSION)
20
+ .pip_install( # add Python dependencies
21
+ "python-fasthtml==0.6.10", "simpleicons==7.21.0", "requests==2.32.3", "sqlite-utils==3.18", "stripe==11.1.0"
22
+ )
23
+ .copy_local_dir(parent_path, "/root/")
24
+ )
25
+
26
+ FE_TIMEOUT = 24 * 60 * MINUTES # max
27
+ FE_CONTAINER_IDLE_TIMEOUT = 20 * MINUTES # max
28
+ FE_ALLOW_CONCURRENT_INPUTS = 1000 # max
29
+
30
+
31
+ APP_NAME = f"{NAME}-frontend"
32
+ app = modal.App(APP_NAME)
33
+
34
+
35
+ @app.function(
36
+ image=FE_IMAGE,
37
+ secrets=[modal.Secret.from_dotenv(path=parent_path, filename=".env" if in_prod else ".env.dev")],
38
+ timeout=FE_TIMEOUT,
39
+ container_idle_timeout=FE_CONTAINER_IDLE_TIMEOUT,
40
+ allow_concurrent_inputs=FE_ALLOW_CONCURRENT_INPUTS,
41
+ volumes=VOLUME_CONFIG,
42
+ )
43
+ @modal.asgi_app()
44
+ def modal_get(): # noqa: C901
45
+ import uuid
46
+
47
+ import requests
48
+ import stripe
49
+ from fasthtml import common as fh
50
+ from simpleicons.icons import si_github, si_pypi
51
+
52
+ # FastHTML setup
53
+ f_app, _ = fh.fast_app(
54
+ ws_hdr=True,
55
+ hdrs=[
56
+ fh.Script(src="https://cdn.tailwindcss.com"),
57
+ fh.HighlightJS(langs=["python", "javascript", "html", "css"]),
58
+ fh.Link(rel="icon", href="/favicon.ico", type="image/x-icon"),
59
+ ],
60
+ live=os.getenv("LIVE", False),
61
+ debug=os.getenv("DEBUG", False),
62
+ )
63
+ fh.setup_toasts(f_app)
64
+
65
+ # database
66
+ db_path = f"/{DATA_VOLUME}/main.db"
67
+ # TODO: uncomment for debugging
68
+ # os.remove(db_path)
69
+ tables = fh.database(db_path).t
70
+ gens = tables.gens
71
+ if gens not in tables:
72
+ gens.create(image_url=str, response=str, session_id=str, id=int, pk="id")
73
+ Generation = gens.dataclass()
74
+
75
+ ## write global balance to db
76
+ init_balance = 100
77
+ global_balance = tables.global_balance
78
+ if global_balance not in tables:
79
+ global_balance.create(balance=int, pk="id")
80
+ Balance = global_balance.dataclass()
81
+
82
+ def get_curr_balance():
83
+ try:
84
+ return global_balance.get(1)
85
+ except Exception:
86
+ global_balance.insert(Balance(balance=init_balance))
87
+ return global_balance.get(1)
88
+
89
+ # Stripe
90
+ stripe.api_key = os.environ["STRIPE_SECRET_KEY"]
91
+ webhook_secret = os.environ["STRIPE_WEBHOOK_SECRET"]
92
+ DOMAIN: str = os.environ["DOMAIN"]
93
+
94
+ # preview while waiting for response
95
+ def generation_preview(g, session):
96
+ if "session_id" not in session:
97
+ fh.add_toast(session, "Please refresh the page", "error")
98
+ return None
99
+ if g.session_id != session["session_id"]:
100
+ fh.add_toast(session, "Please refresh the page", "error")
101
+ return None
102
+
103
+ if g.response:
104
+ return (
105
+ fh.Card(
106
+ fh.Img(src=g.image_url, alt="Card image", cls="w-80 object-contain"),
107
+ fh.P(
108
+ g.response,
109
+ onclick="navigator.clipboard.writeText(this.innerText);",
110
+ hx_post="/toast?message=Copied to clipboard!&type=success",
111
+ hx_target="#toast-container",
112
+ hx_swap="outerHTML",
113
+ cls="text-blue-300 hover:text-blue-100 cursor-pointer",
114
+ title="Click to copy",
115
+ ),
116
+ cls="w-2/3 flex flex-col justify-center items-center gap-4",
117
+ id=f"gen-{g.id}",
118
+ ),
119
+ )
120
+ return fh.Card(
121
+ fh.Img(src=g.image_url, alt="Card image", cls="w-80 object-contain"),
122
+ fh.P("Scanning image ..."),
123
+ cls="w-2/3 flex flex-col justify-center items-center gap-4",
124
+ id=f"gen-{g.id}",
125
+ hx_get=f"/gens/{g.id}",
126
+ hx_trigger="every 2s",
127
+ hx_swap="outerHTML",
128
+ )
129
+
130
+ # components
131
+ def icon(
132
+ svg,
133
+ width="35",
134
+ height="35",
135
+ viewBox="0 0 15 15",
136
+ fill="none",
137
+ cls="rounded p-0.5 hover:bg-zinc-700 cursor-pointer",
138
+ ):
139
+ return fh.Svg(
140
+ fh.NotStr(svg),
141
+ width=width,
142
+ height=height,
143
+ viewBox=viewBox,
144
+ fill=fill,
145
+ cls=cls,
146
+ )
147
+
148
+ # layout
149
+ def nav():
150
+ return fh.Nav(
151
+ fh.A(
152
+ f"{NAME}",
153
+ href="/",
154
+ cls="text-xl text-blue-300 hover:text-blue-100 font-mono font-family:Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'",
155
+ ),
156
+ fh.Div(
157
+ fh.A(
158
+ icon(si_github.svg),
159
+ href="https://github.com/andrewhinh/formless",
160
+ target="_blank",
161
+ ),
162
+ fh.A(
163
+ icon(si_pypi.svg),
164
+ href="https://pypi.org/project/formless/",
165
+ target="_blank",
166
+ ),
167
+ cls="flex gap-4",
168
+ ),
169
+ cls="flex justify-between p-4",
170
+ )
171
+
172
+ def main_content(session):
173
+ gen_containers = [
174
+ generation_preview(g, session) for g in gens(limit=10, where=f"session_id == '{session['session_id']}'")
175
+ ]
176
+ return fh.Main(
177
+ fh.Form(
178
+ fh.Group(
179
+ fh.Input(
180
+ id="new-image-url",
181
+ name="image_url",
182
+ placeholder="Enter an image url",
183
+ cls="p-2",
184
+ ),
185
+ fh.Button(
186
+ "Scan",
187
+ cls="text-blue-300 hover:text-blue-100 p-2 border-blue-300 border-2 hover:border-blue-100",
188
+ ),
189
+ ),
190
+ hx_post="/",
191
+ target_id="gen-list",
192
+ hx_swap="afterbegin",
193
+ cls="w-2/3",
194
+ ),
195
+ fh.Button(
196
+ "Clear all",
197
+ id="clear-all",
198
+ hx_post="/clear",
199
+ target_id="gen-list",
200
+ hx_swap="innerHTML",
201
+ cls=f"text-red-300 hover:text-red-100 p-2 w-1/3 border-red-300 border-2 hover:border-red-100 {'hidden' if not gen_containers else ''}",
202
+ ),
203
+ # fh.Div(
204
+ # fh.Button(
205
+ # "Clear all",
206
+ # id="clear-all",
207
+ # hx_post="/clear",
208
+ # target_id="gen-list",
209
+ # hx_swap="innerHTML",
210
+ # cls=f"text-red-300 hover:text-red-100 p-2 w-full border-red-300 border-2 hover:border-red-100 {'hidden' if not gen_containers else ''}",
211
+ # ),
212
+ # fh.Button(
213
+ # "Export to CSV",
214
+ # id="export-csv",
215
+ # hx_get="/export",
216
+ # cls=f"text-green-300 hover:text-green-100 p-2 w-full border-green-300 border-2 hover:border-green-100 {'hidden' if not gen_containers else ''}",
217
+ # ),
218
+ # cls="flex justify-center gap-4 w-2/3",
219
+ # ),
220
+ fh.Div(*gen_containers[::-1], id="gen-list", cls="flex flex-col justify-center items-center gap-4"),
221
+ cls="flex flex-col justify-center items-center gap-4",
222
+ )
223
+
224
+ def toast_container():
225
+ return fh.Div(id="toast-container", cls="hidden")
226
+
227
+ def footer():
228
+ return fh.Footer(
229
+ get_balance(), # Live-updating balance
230
+ fh.Div(
231
+ fh.P("Made by"),
232
+ fh.A(
233
+ "Andrew Hinh",
234
+ href="https://andrewhinh.github.io/",
235
+ cls="font-bold text-blue-300 hover:text-blue-100",
236
+ ),
237
+ cls="flex flex-col text-right gap-0.5",
238
+ ),
239
+ cls="flex justify-between p-4 text-lg",
240
+ )
241
+
242
+ # routes
243
+ @f_app.get("/")
244
+ async def home(session):
245
+ if "session_id" not in session:
246
+ session["session_id"] = str(uuid.uuid4())
247
+ return fh.Title(NAME), fh.Div(
248
+ nav(),
249
+ main_content(session),
250
+ toast_container(),
251
+ footer(),
252
+ cls="flex flex-col justify-between min-h-screen text-slate-100 bg-zinc-900 w-full",
253
+ )
254
+
255
+ ## pending preview keeps polling this route until we return the image preview
256
+ @f_app.get("/gens/{id}")
257
+ def preview(id: int, session):
258
+ return generation_preview(gens.get(id), session)
259
+
260
+ ## Likewise we poll to keep the balance updated
261
+ @f_app.get("/balance")
262
+ def get_balance():
263
+ curr_balance = get_curr_balance()
264
+ return fh.Div(
265
+ fh.Div(
266
+ fh.P("Global balance:"),
267
+ fh.P(f"{curr_balance.balance} credits", cls="font-bold"),
268
+ cls="flex gap-1",
269
+ ),
270
+ fh.P(
271
+ fh.A("Buy 50 more", href="/buy_global", cls="font-bold text-blue-300 hover:text-blue-100"),
272
+ " to share ($1)",
273
+ ),
274
+ id="balance",
275
+ hx_get="/balance",
276
+ hx_trigger="every 2s",
277
+ hx_swap="outerHTML",
278
+ cls="flex flex-col gap-0.5",
279
+ )
280
+
281
+ ## toasts without target
282
+ @f_app.post("/toast")
283
+ async def toast(session, message: str, type: str):
284
+ fh.add_toast(session, message, type)
285
+ return fh.Div(id="toast-container", cls="hidden")
286
+
287
+ ## for images, CSS, etc.
288
+ @f_app.get("/{fname:path}.{ext:static}")
289
+ async def static_files(fname: str, ext: str):
290
+ static_file_path = parent_path / f"{fname}.{ext}"
291
+ if static_file_path.exists():
292
+ return fh.FileResponse(static_file_path)
293
+
294
+ ## generation route
295
+ @f_app.post("/")
296
+ def generate(session, image_url: str = None):
297
+ # Check for session ID
298
+ if "session_id" not in session:
299
+ fh.add_toast(session, "Please refresh the page", "error")
300
+ return None
301
+
302
+ # Check image URL
303
+ if not image_url:
304
+ fh.add_toast(session, "No image URL provided", "error")
305
+ return None
306
+ if requests.head(image_url).headers["content-type"] not in ("image/png", "image/jpeg", "image/jpg"):
307
+ fh.add_toast(session, "Invalid image URL", "error")
308
+ return None
309
+
310
+ # Warn if we're out of balance
311
+ curr_balance = get_curr_balance()
312
+ if curr_balance.balance < 1:
313
+ fh.add_toast(session, "Out of balance!", "error")
314
+ return None
315
+
316
+ # Decrement balance
317
+ curr_balance.balance -= 1
318
+ global_balance.update(curr_balance)
319
+
320
+ # Clear input and button
321
+ clear_input = fh.Input(
322
+ id="new-image-url", name="image-url", placeholder="Enter an image url", hx_swap_oob="true"
323
+ )
324
+ clear_c_button = (
325
+ fh.Button(
326
+ "Clear all",
327
+ id="clear-all",
328
+ hx_post="/clear",
329
+ target_id="gen-list",
330
+ hx_swap="innerHTML",
331
+ hx_swap_oob="true",
332
+ cls="text-red-300 hover:text-red-100 p-2 w-1/3 border-red-300 border-2 hover:border-red-100",
333
+ ),
334
+ )
335
+ # clear_e_button = (
336
+ # fh.Button(
337
+ # "Export to CSV",
338
+ # id="export-csv",
339
+ # hx_get="/export",
340
+ # cls="text-green-300 hover:text-green-100 p-2 w-1/3 border-green-300 border-2 hover:border-green-100",
341
+ # ),
342
+ # )
343
+
344
+ # Generate as before
345
+ g = gens.insert(Generation(image_url=image_url, session_id=session["session_id"]))
346
+ generate_and_save(g)
347
+
348
+ return generation_preview(g, session), clear_input, clear_c_button # , clear_e_button
349
+
350
+ ## generate the response (in a separate thread)
351
+ @fh.threaded
352
+ def generate_and_save(g) -> None:
353
+ response = requests.post(f"{os.getenv('API_URL')}/api-key")
354
+ if not response.ok:
355
+ g.response = "Failed with status code: " + str(response.status_code)
356
+ else:
357
+ api_key = response.json()
358
+ response = requests.post(
359
+ os.getenv("API_URL"), json={"image_url": g.image_url}, headers={"X-API-Key": api_key}
360
+ )
361
+ if not response.ok:
362
+ g.response = "Failed with status code: " + str(response.status_code)
363
+ else:
364
+ g.response = response.json()
365
+ # TODO: uncomment for debugging
366
+ # g.response = "temp"
367
+ gens.update(g)
368
+
369
+ ## clear all
370
+ @f_app.post("/clear")
371
+ def clear_all(session):
372
+ ids = [g.id for g in gens(where=f"session_id == '{session['session_id']}'")]
373
+ for id in ids:
374
+ gens.delete(id)
375
+ clear_button = (
376
+ fh.Button(
377
+ "Clear all",
378
+ id="clear-all",
379
+ hx_post="/clear",
380
+ target_id="gen-list",
381
+ hx_swap="innerHTML",
382
+ hx_swap_oob="true",
383
+ cls="text-red-300 hover:text-red-100 p-2 w-1/3 border-red-300 border-2 hover:border-red-100 hidden",
384
+ ),
385
+ )
386
+ return None, clear_button
387
+
388
+ # ## export to CSV
389
+ # @f_app.get("/export")
390
+ # def export(session):
391
+ # output = io.StringIO()
392
+ # writer = csv.writer(output)
393
+ # writer.writerow(["image_url", "response"])
394
+ # for g in gens(where=f"session_id == '{session['session_id']}'"):
395
+ # writer.writerow([g.image_url, g.response])
396
+
397
+ # return fh.FileResponse(output.getvalue(), headers={"Content-Disposition": "attachment; filename=export.csv"})
398
+
399
+ ## We send the user here to buy credits
400
+ @f_app.get("/buy_global")
401
+ def buy_credits(session):
402
+ if "session_id" not in session:
403
+ return "Error no session id"
404
+
405
+ # Create Stripe Checkout Session
406
+ s = stripe.checkout.Session.create(
407
+ payment_method_types=["card"],
408
+ line_items=[
409
+ {
410
+ "price_data": {
411
+ "currency": "usd",
412
+ "unit_amount": 100,
413
+ "product_data": {
414
+ "name": "Buy 50 credits for $1 (to share)",
415
+ },
416
+ },
417
+ "quantity": 1,
418
+ }
419
+ ],
420
+ mode="payment",
421
+ success_url=DOMAIN + "/success?session_id={CHECKOUT_SESSION_ID}",
422
+ cancel_url=DOMAIN + "/cancel",
423
+ )
424
+
425
+ # Send the USER to STRIPE
426
+ return fh.RedirectResponse(s["url"])
427
+
428
+ ## STRIPE sends the USER here after a payment was canceled.
429
+ @f_app.get("/cancel")
430
+ def cancel():
431
+ return fh.RedirectResponse("/")
432
+
433
+ ## STRIPE sends the USER here after a payment was 'successful'.
434
+ @f_app.get("/success")
435
+ def success():
436
+ return fh.RedirectResponse("/")
437
+
438
+ ## STRIPE calls this to tell APP when a payment was completed.
439
+ @f_app.post("/webhook")
440
+ async def stripe_webhook(request):
441
+ print(request)
442
+ print("Received webhook")
443
+ payload = await request.body()
444
+ payload = payload.decode("utf-8")
445
+ signature = request.headers.get("stripe-signature")
446
+ print(payload)
447
+
448
+ # Verify the Stripe webhook signature
449
+ try:
450
+ event = stripe.Webhook.construct_event(payload, signature, webhook_secret)
451
+ except ValueError:
452
+ print("Invalid payload")
453
+ return {"error": "Invalid payload"}, 400
454
+ except stripe.error.SignatureVerificationError:
455
+ print("Invalid signature")
456
+ return {"error": "Invalid signature"}, 400
457
+
458
+ # Handle the event
459
+ if event["type"] == "checkout.session.completed":
460
+ session = event["data"]["object"]
461
+ print("Session completed", session)
462
+ curr_balance = get_curr_balance()
463
+ curr_balance.balance += 50
464
+ global_balance.update(curr_balance)
465
+ return {"status": "success"}, 200
466
+
467
+ return f_app
468
+
469
+
470
+ # TODO:
471
+ # - add export to csv
472
+ # - replace polling routes with websockets
473
+ # - add user authentication
474
+ # - add api key management
475
+ # - add error reporting
@@ -1,11 +1,12 @@
1
1
  [project]
2
2
  name = "formless"
3
- version = "0.3.0"
3
+ version = "0.4.0"
4
4
  description = "Handwritten + image OCR."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
7
7
  dependencies = [
8
8
  "modal>=0.64.178",
9
+ "pre-commit>=4.0.1",
9
10
  "python-dotenv>=1.0.1",
10
11
  "requests>=2.32.3",
11
12
  "term-image>=0.7.2",
@@ -12,7 +12,7 @@ from typing_extensions import Annotated
12
12
 
13
13
 
14
14
  DEFAULT_IMG_URL = "https://modal-public-assets.s3.amazonaws.com/golden-gate-bridge.jpg"
15
- API_URL = "https://andrewhinh--formless-api-model-infer.modal.run"
15
+ API_URL = "https://andrewhinh--formless-api-modal-get-infer.modal.run"
16
16
 
17
17
  # Typer CLI
18
18
  app = typer.Typer(
@@ -24,7 +24,10 @@ state = {"verbose": False}
24
24
  # Fns
25
25
  def run() -> None:
26
26
  image_url = state["image_url"]
27
- response = requests.post(API_URL, json={"image_url": image_url})
27
+ response = requests.post(f"{API_URL}/api-key")
28
+ assert response.ok, response.status_code
29
+ api_key = response.json()
30
+ response = requests.post(API_URL, json={"image_url": image_url}, headers={"X-API-Key": api_key})
28
31
  assert response.ok, response.status_code
29
32
  return response.json()
30
33
 
@@ -86,3 +89,7 @@ def main(
86
89
  print(f"[red]Failed with error: {e}[/red]")
87
90
  print(traceback.format_exc())
88
91
  print("[red]\n\nExiting...[/red]")
92
+
93
+
94
+ # TODO:
95
+ # - Add more CLI options
@@ -14,9 +14,11 @@ OS = "ubuntu22.04"
14
14
  TAG = f"nvidia/cuda:{CUDA_VERSION}-{FLAVOR}-{OS}"
15
15
  PYTHON_VERSION = "3.12"
16
16
 
17
+ DATA_VOLUME = f"{NAME}-data"
17
18
  PRETRAINED_VOLUME = f"{NAME}-pretrained"
18
19
  RUNS_VOLUME = f"{NAME}-runs"
19
20
  VOLUME_CONFIG: dict[str | PurePosixPath, modal.Volume] = {
21
+ f"/{DATA_VOLUME}": modal.Volume.from_name(DATA_VOLUME, create_if_missing=True),
20
22
  f"/{PRETRAINED_VOLUME}": modal.Volume.from_name(PRETRAINED_VOLUME, create_if_missing=True),
21
23
  f"/{RUNS_VOLUME}": modal.Volume.from_name(RUNS_VOLUME, create_if_missing=True),
22
24
  }
@@ -124,6 +124,15 @@ wheels = [
124
124
  { url = "https://files.pythonhosted.org/packages/12/90/3c9ff0512038035f59d279fddeb79f5f1eccd8859f06d6163c58798b9487/certifi-2024.8.30-py3-none-any.whl", hash = "sha256:922820b53db7a7257ffbda3f597266d435245903d80737e34f8a45ff3e3230d8", size = 167321 },
125
125
  ]
126
126
 
127
+ [[package]]
128
+ name = "cfgv"
129
+ version = "3.4.0"
130
+ source = { registry = "https://pypi.org/simple" }
131
+ sdist = { url = "https://files.pythonhosted.org/packages/11/74/539e56497d9bd1d484fd863dd69cbbfa653cd2aa27abfe35653494d85e94/cfgv-3.4.0.tar.gz", hash = "sha256:e52591d4c5f5dead8e0f673fb16db7949d2cfb3f7da4582893288f0ded8fe560", size = 7114 }
132
+ wheels = [
133
+ { url = "https://files.pythonhosted.org/packages/c5/55/51844dd50c4fc7a33b653bfaba4c2456f06955289ca770a5dbd5fd267374/cfgv-3.4.0-py2.py3-none-any.whl", hash = "sha256:b7265b1f29fd3316bfcd2b330d63d024f2bfd8bcb8b0272f8e19a504856c48f9", size = 7249 },
134
+ ]
135
+
127
136
  [[package]]
128
137
  name = "charset-normalizer"
129
138
  version = "3.4.0"
@@ -184,6 +193,15 @@ wheels = [
184
193
  { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335 },
185
194
  ]
186
195
 
196
+ [[package]]
197
+ name = "distlib"
198
+ version = "0.3.9"
199
+ source = { registry = "https://pypi.org/simple" }
200
+ sdist = { url = "https://files.pythonhosted.org/packages/0d/dd/1bec4c5ddb504ca60fc29472f3d27e8d4da1257a854e1d96742f15c1d02d/distlib-0.3.9.tar.gz", hash = "sha256:a60f20dea646b8a33f3e7772f74dc0b2d0772d2837ee1342a00645c81edf9403", size = 613923 }
201
+ wheels = [
202
+ { url = "https://files.pythonhosted.org/packages/91/a1/cf2472db20f7ce4a6be1253a81cfdf85ad9c7885ffbed7047fb72c24cf87/distlib-0.3.9-py2.py3-none-any.whl", hash = "sha256:47f8c22fd27c27e25a65601af709b38e4f0a45ea4fc2e710f65755fa8caaaf87", size = 468973 },
203
+ ]
204
+
187
205
  [[package]]
188
206
  name = "fastapi"
189
207
  version = "0.115.0"
@@ -198,12 +216,22 @@ wheels = [
198
216
  { url = "https://files.pythonhosted.org/packages/06/ab/a1f7eed031aeb1c406a6e9d45ca04bff401c8a25a30dd0e4fd2caae767c3/fastapi-0.115.0-py3-none-any.whl", hash = "sha256:17ea427674467486e997206a5ab25760f6b09e069f099b96f5b55a32fb6f1631", size = 94625 },
199
217
  ]
200
218
 
219
+ [[package]]
220
+ name = "filelock"
221
+ version = "3.16.1"
222
+ source = { registry = "https://pypi.org/simple" }
223
+ sdist = { url = "https://files.pythonhosted.org/packages/9d/db/3ef5bb276dae18d6ec2124224403d1d67bccdbefc17af4cc8f553e341ab1/filelock-3.16.1.tar.gz", hash = "sha256:c249fbfcd5db47e5e2d6d62198e565475ee65e4831e2561c8e313fa7eb961435", size = 18037 }
224
+ wheels = [
225
+ { url = "https://files.pythonhosted.org/packages/b9/f8/feced7779d755758a52d1f6635d990b8d98dc0a29fa568bbe0625f18fdf3/filelock-3.16.1-py3-none-any.whl", hash = "sha256:2082e5703d51fbf98ea75855d9d5527e33d8ff23099bec374a134febee6946b0", size = 16163 },
226
+ ]
227
+
201
228
  [[package]]
202
229
  name = "formless"
203
230
  version = "0.3.0"
204
231
  source = { editable = "." }
205
232
  dependencies = [
206
233
  { name = "modal" },
234
+ { name = "pre-commit" },
207
235
  { name = "python-dotenv" },
208
236
  { name = "requests" },
209
237
  { name = "term-image" },
@@ -212,6 +240,7 @@ dependencies = [
212
240
  [package.metadata]
213
241
  requires-dist = [
214
242
  { name = "modal", specifier = ">=0.64.178" },
243
+ { name = "pre-commit", specifier = ">=4.0.1" },
215
244
  { name = "python-dotenv", specifier = ">=1.0.1" },
216
245
  { name = "requests", specifier = ">=2.32.3" },
217
246
  { name = "term-image", specifier = ">=0.7.2" },
@@ -282,6 +311,15 @@ wheels = [
282
311
  { url = "https://files.pythonhosted.org/packages/d7/de/85a784bcc4a3779d1753a7ec2dee5de90e18c7bcf402e71b51fcf150b129/hyperframe-6.0.1-py3-none-any.whl", hash = "sha256:0ec6bafd80d8ad2195c4f03aacba3a8265e57bc4cff261e802bf39970ed02a15", size = 12389 },
283
312
  ]
284
313
 
314
+ [[package]]
315
+ name = "identify"
316
+ version = "2.6.1"
317
+ source = { registry = "https://pypi.org/simple" }
318
+ sdist = { url = "https://files.pythonhosted.org/packages/29/bb/25024dbcc93516c492b75919e76f389bac754a3e4248682fba32b250c880/identify-2.6.1.tar.gz", hash = "sha256:91478c5fb7c3aac5ff7bf9b4344f803843dc586832d5f110d672b19aa1984c98", size = 99097 }
319
+ wheels = [
320
+ { url = "https://files.pythonhosted.org/packages/7d/0c/4ef72754c050979fdcc06c744715ae70ea37e734816bb6514f79df77a42f/identify-2.6.1-py2.py3-none-any.whl", hash = "sha256:53863bcac7caf8d2ed85bd20312ea5dcfc22226800f6d6881f232d861db5a8f0", size = 98972 },
321
+ ]
322
+
285
323
  [[package]]
286
324
  name = "idna"
287
325
  version = "3.10"
@@ -376,6 +414,15 @@ wheels = [
376
414
  { url = "https://files.pythonhosted.org/packages/99/b7/b9e70fde2c0f0c9af4cc5277782a89b66d35948ea3369ec9f598358c3ac5/multidict-6.1.0-py3-none-any.whl", hash = "sha256:48e171e52d1c4d33888e529b999e5900356b9ae588c2f09a52dcefb158b27506", size = 10051 },
377
415
  ]
378
416
 
417
+ [[package]]
418
+ name = "nodeenv"
419
+ version = "1.9.1"
420
+ source = { registry = "https://pypi.org/simple" }
421
+ sdist = { url = "https://files.pythonhosted.org/packages/43/16/fc88b08840de0e0a72a2f9d8c6bae36be573e475a6326ae854bcc549fc45/nodeenv-1.9.1.tar.gz", hash = "sha256:6ec12890a2dab7946721edbfbcd91f3319c6ccc9aec47be7c7e6b7011ee6645f", size = 47437 }
422
+ wheels = [
423
+ { url = "https://files.pythonhosted.org/packages/d2/1d/1b658dbd2b9fa9c4c9f32accbfc0205d532c8c6194dc0f2a4c0428e7128a/nodeenv-1.9.1-py2.py3-none-any.whl", hash = "sha256:ba11c9782d29c27c70ffbdda2d7415098754709be8a7056d79a737cd901155c9", size = 22314 },
424
+ ]
425
+
379
426
  [[package]]
380
427
  name = "pillow"
381
428
  version = "10.4.0"
@@ -406,6 +453,31 @@ wheels = [
406
453
  { url = "https://files.pythonhosted.org/packages/48/2c/2e0a52890f269435eee38b21c8218e102c621fe8d8df8b9dd06fabf879ba/pillow-10.4.0-cp313-cp313-win_arm64.whl", hash = "sha256:5b001114dd152cfd6b23befeb28d7aee43553e2402c9f159807bf55f33af8a8d", size = 2243375 },
407
454
  ]
408
455
 
456
+ [[package]]
457
+ name = "platformdirs"
458
+ version = "4.3.6"
459
+ source = { registry = "https://pypi.org/simple" }
460
+ sdist = { url = "https://files.pythonhosted.org/packages/13/fc/128cc9cb8f03208bdbf93d3aa862e16d376844a14f9a0ce5cf4507372de4/platformdirs-4.3.6.tar.gz", hash = "sha256:357fb2acbc885b0419afd3ce3ed34564c13c9b95c89360cd9563f73aa5e2b907", size = 21302 }
461
+ wheels = [
462
+ { url = "https://files.pythonhosted.org/packages/3c/a6/bc1012356d8ece4d66dd75c4b9fc6c1f6650ddd5991e421177d9f8f671be/platformdirs-4.3.6-py3-none-any.whl", hash = "sha256:73e575e1408ab8103900836b97580d5307456908a03e92031bab39e4554cc3fb", size = 18439 },
463
+ ]
464
+
465
+ [[package]]
466
+ name = "pre-commit"
467
+ version = "4.0.1"
468
+ source = { registry = "https://pypi.org/simple" }
469
+ dependencies = [
470
+ { name = "cfgv" },
471
+ { name = "identify" },
472
+ { name = "nodeenv" },
473
+ { name = "pyyaml" },
474
+ { name = "virtualenv" },
475
+ ]
476
+ sdist = { url = "https://files.pythonhosted.org/packages/2e/c8/e22c292035f1bac8b9f5237a2622305bc0304e776080b246f3df57c4ff9f/pre_commit-4.0.1.tar.gz", hash = "sha256:80905ac375958c0444c65e9cebebd948b3cdb518f335a091a670a89d652139d2", size = 191678 }
477
+ wheels = [
478
+ { url = "https://files.pythonhosted.org/packages/16/8f/496e10d51edd6671ebe0432e33ff800aa86775d2d147ce7d43389324a525/pre_commit-4.0.1-py2.py3-none-any.whl", hash = "sha256:efde913840816312445dc98787724647c65473daefe420785f885e8ed9a06878", size = 218713 },
479
+ ]
480
+
409
481
  [[package]]
410
482
  name = "protobuf"
411
483
  version = "4.25.5"
@@ -487,6 +559,32 @@ wheels = [
487
559
  { url = "https://files.pythonhosted.org/packages/6a/3e/b68c118422ec867fa7ab88444e1274aa40681c606d59ac27de5a5588f082/python_dotenv-1.0.1-py3-none-any.whl", hash = "sha256:f7b63ef50f1b690dddf550d03497b66d609393b40b564ed0d674909a68ebf16a", size = 19863 },
488
560
  ]
489
561
 
562
+ [[package]]
563
+ name = "pyyaml"
564
+ version = "6.0.2"
565
+ source = { registry = "https://pypi.org/simple" }
566
+ sdist = { url = "https://files.pythonhosted.org/packages/54/ed/79a089b6be93607fa5cdaedf301d7dfb23af5f25c398d5ead2525b063e17/pyyaml-6.0.2.tar.gz", hash = "sha256:d584d9ec91ad65861cc08d42e834324ef890a082e591037abe114850ff7bbc3e", size = 130631 }
567
+ wheels = [
568
+ { url = "https://files.pythonhosted.org/packages/86/0c/c581167fc46d6d6d7ddcfb8c843a4de25bdd27e4466938109ca68492292c/PyYAML-6.0.2-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:c70c95198c015b85feafc136515252a261a84561b7b1d51e3384e0655ddf25ab", size = 183873 },
569
+ { url = "https://files.pythonhosted.org/packages/a8/0c/38374f5bb272c051e2a69281d71cba6fdb983413e6758b84482905e29a5d/PyYAML-6.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ce826d6ef20b1bc864f0a68340c8b3287705cae2f8b4b1d932177dcc76721725", size = 173302 },
570
+ { url = "https://files.pythonhosted.org/packages/c3/93/9916574aa8c00aa06bbac729972eb1071d002b8e158bd0e83a3b9a20a1f7/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1f71ea527786de97d1a0cc0eacd1defc0985dcf6b3f17bb77dcfc8c34bec4dc5", size = 739154 },
571
+ { url = "https://files.pythonhosted.org/packages/95/0f/b8938f1cbd09739c6da569d172531567dbcc9789e0029aa070856f123984/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9b22676e8097e9e22e36d6b7bda33190d0d400f345f23d4065d48f4ca7ae0425", size = 766223 },
572
+ { url = "https://files.pythonhosted.org/packages/b9/2b/614b4752f2e127db5cc206abc23a8c19678e92b23c3db30fc86ab731d3bd/PyYAML-6.0.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:80bab7bfc629882493af4aa31a4cfa43a4c57c83813253626916b8c7ada83476", size = 767542 },
573
+ { url = "https://files.pythonhosted.org/packages/d4/00/dd137d5bcc7efea1836d6264f049359861cf548469d18da90cd8216cf05f/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:0833f8694549e586547b576dcfaba4a6b55b9e96098b36cdc7ebefe667dfed48", size = 731164 },
574
+ { url = "https://files.pythonhosted.org/packages/c9/1f/4f998c900485e5c0ef43838363ba4a9723ac0ad73a9dc42068b12aaba4e4/PyYAML-6.0.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8b9c7197f7cb2738065c481a0461e50ad02f18c78cd75775628afb4d7137fb3b", size = 756611 },
575
+ { url = "https://files.pythonhosted.org/packages/df/d1/f5a275fdb252768b7a11ec63585bc38d0e87c9e05668a139fea92b80634c/PyYAML-6.0.2-cp312-cp312-win32.whl", hash = "sha256:ef6107725bd54b262d6dedcc2af448a266975032bc85ef0172c5f059da6325b4", size = 140591 },
576
+ { url = "https://files.pythonhosted.org/packages/0c/e8/4f648c598b17c3d06e8753d7d13d57542b30d56e6c2dedf9c331ae56312e/PyYAML-6.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:7e7401d0de89a9a855c839bc697c079a4af81cf878373abd7dc625847d25cbd8", size = 156338 },
577
+ { url = "https://files.pythonhosted.org/packages/ef/e3/3af305b830494fa85d95f6d95ef7fa73f2ee1cc8ef5b495c7c3269fb835f/PyYAML-6.0.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:efdca5630322a10774e8e98e1af481aad470dd62c3170801852d752aa7a783ba", size = 181309 },
578
+ { url = "https://files.pythonhosted.org/packages/45/9f/3b1c20a0b7a3200524eb0076cc027a970d320bd3a6592873c85c92a08731/PyYAML-6.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:50187695423ffe49e2deacb8cd10510bc361faac997de9efef88badc3bb9e2d1", size = 171679 },
579
+ { url = "https://files.pythonhosted.org/packages/7c/9a/337322f27005c33bcb656c655fa78325b730324c78620e8328ae28b64d0c/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0ffe8360bab4910ef1b9e87fb812d8bc0a308b0d0eef8c8f44e0254ab3b07133", size = 733428 },
580
+ { url = "https://files.pythonhosted.org/packages/a3/69/864fbe19e6c18ea3cc196cbe5d392175b4cf3d5d0ac1403ec3f2d237ebb5/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:17e311b6c678207928d649faa7cb0d7b4c26a0ba73d41e99c4fff6b6c3276484", size = 763361 },
581
+ { url = "https://files.pythonhosted.org/packages/04/24/b7721e4845c2f162d26f50521b825fb061bc0a5afcf9a386840f23ea19fa/PyYAML-6.0.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70b189594dbe54f75ab3a1acec5f1e3faa7e8cf2f1e08d9b561cb41b845f69d5", size = 759523 },
582
+ { url = "https://files.pythonhosted.org/packages/2b/b2/e3234f59ba06559c6ff63c4e10baea10e5e7df868092bf9ab40e5b9c56b6/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:41e4e3953a79407c794916fa277a82531dd93aad34e29c2a514c2c0c5fe971cc", size = 726660 },
583
+ { url = "https://files.pythonhosted.org/packages/fe/0f/25911a9f080464c59fab9027482f822b86bf0608957a5fcc6eaac85aa515/PyYAML-6.0.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:68ccc6023a3400877818152ad9a1033e3db8625d899c72eacb5a668902e4d652", size = 751597 },
584
+ { url = "https://files.pythonhosted.org/packages/14/0d/e2c3b43bbce3cf6bd97c840b46088a3031085179e596d4929729d8d68270/PyYAML-6.0.2-cp313-cp313-win32.whl", hash = "sha256:bc2fa7c6b47d6bc618dd7fb02ef6fdedb1090ec036abab80d4681424b84c1183", size = 140527 },
585
+ { url = "https://files.pythonhosted.org/packages/fa/de/02b54f42487e3d3c6efb3f89428677074ca7bf43aae402517bc7cca949f3/PyYAML-6.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:8388ee1976c416731879ac16da0aff3f63b286ffdd57cdeb95f3f2e085687563", size = 156446 },
586
+ ]
587
+
490
588
  [[package]]
491
589
  name = "requests"
492
590
  version = "2.32.3"
@@ -642,6 +740,20 @@ wheels = [
642
740
  { url = "https://files.pythonhosted.org/packages/ce/d9/5f4c13cecde62396b0d3fe530a50ccea91e7dfc1ccf0e09c228841bb5ba8/urllib3-2.2.3-py3-none-any.whl", hash = "sha256:ca899ca043dcb1bafa3e262d73aa25c465bfb49e0bd9dd5d59f1d0acba2f8fac", size = 126338 },
643
741
  ]
644
742
 
743
+ [[package]]
744
+ name = "virtualenv"
745
+ version = "20.27.0"
746
+ source = { registry = "https://pypi.org/simple" }
747
+ dependencies = [
748
+ { name = "distlib" },
749
+ { name = "filelock" },
750
+ { name = "platformdirs" },
751
+ ]
752
+ sdist = { url = "https://files.pythonhosted.org/packages/10/7f/192dd6ab6d91ebea7adf6c030eaf549b1ec0badda9f67a77b633602f66ac/virtualenv-20.27.0.tar.gz", hash = "sha256:2ca56a68ed615b8fe4326d11a0dca5dfbe8fd68510fb6c6349163bed3c15f2b2", size = 6483858 }
753
+ wheels = [
754
+ { url = "https://files.pythonhosted.org/packages/c8/15/828ec11907aee2349a9342fa71fba4ba7f3af938162a382dd7da339dea16/virtualenv-20.27.0-py3-none-any.whl", hash = "sha256:44a72c29cceb0ee08f300b314848c86e57bf8d1f13107a5e671fb9274138d655", size = 3110969 },
755
+ ]
756
+
645
757
  [[package]]
646
758
  name = "watchfiles"
647
759
  version = "0.24.0"
@@ -1,166 +0,0 @@
1
- import os
2
- from pathlib import Path
3
-
4
- import modal
5
-
6
- from utils import (
7
- MINUTES,
8
- NAME,
9
- PYTHON_VERSION,
10
- )
11
-
12
- parent_path: Path = Path(__file__).parent
13
-
14
- # Modal
15
- FE_IMAGE = (
16
- modal.Image.debian_slim(python_version=PYTHON_VERSION)
17
- .pip_install( # add Python dependencies
18
- "python-fasthtml==0.6.10", "simpleicons==7.21.0"
19
- )
20
- .copy_local_dir(parent_path, "/root/")
21
- )
22
-
23
- FE_TIMEOUT = 24 * 60 * MINUTES # max
24
- FE_CONTAINER_IDLE_TIMEOUT = 20 * MINUTES # max
25
- FE_ALLOW_CONCURRENT_INPUTS = 1000 # max
26
-
27
-
28
- APP_NAME = f"{NAME}-frontend"
29
- app = modal.App(APP_NAME)
30
-
31
-
32
- @app.function(
33
- image=FE_IMAGE,
34
- secrets=[modal.Secret.from_dotenv(path=parent_path)],
35
- timeout=FE_TIMEOUT,
36
- container_idle_timeout=FE_CONTAINER_IDLE_TIMEOUT,
37
- allow_concurrent_inputs=FE_ALLOW_CONCURRENT_INPUTS,
38
- )
39
- @modal.asgi_app()
40
- def modal_get():
41
- from fasthtml import common as fh
42
- from simpleicons.icons import si_github, si_pypi
43
-
44
- fasthtml_app, rt = fh.fast_app(
45
- ws_hdr=True,
46
- hdrs=[
47
- fh.Script(src="https://cdn.tailwindcss.com"),
48
- fh.HighlightJS(langs=["python", "javascript", "html", "css"]),
49
- fh.Link(rel="icon", href="/favicon.ico", type="image/x-icon"),
50
- ],
51
- live=os.getenv("LIVE", False),
52
- debug=os.getenv("DEBUG", False),
53
- )
54
- fh.setup_toasts(fasthtml_app)
55
-
56
- # Components
57
- def icon(
58
- svg,
59
- width="35",
60
- height="35",
61
- viewBox="0 0 15 15",
62
- fill="none",
63
- cls="rounded p-0.5 hover:bg-zinc-700 cursor-pointer",
64
- ):
65
- return fh.Svg(
66
- fh.NotStr(svg),
67
- width=width,
68
- height=height,
69
- viewBox=viewBox,
70
- fill=fill,
71
- cls=cls,
72
- )
73
-
74
- # Layout
75
- def nav():
76
- return fh.Nav(
77
- fh.A(
78
- f"{NAME}",
79
- href="/",
80
- cls="text-xl text-blue-300 hover:text-blue-100 font-mono font-family:Consolas, Monaco, 'Lucida Console', 'Liberation Mono', 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New'",
81
- ),
82
- fh.Div(
83
- fh.A(
84
- icon(si_github.svg),
85
- href="https://github.com/andrewhinh/formless",
86
- target="_blank",
87
- ),
88
- fh.A(
89
- icon(si_pypi.svg),
90
- href="https://pypi.org/project/formless/",
91
- target="_blank",
92
- ),
93
- cls="flex gap-4",
94
- ),
95
- cls="flex justify-between p-4",
96
- )
97
-
98
- def main_content():
99
- return fh.Main(
100
- # fh.Div(
101
- # fh.Div(
102
- # fh.Label(
103
- # "Upload Image:",
104
- # fh.Input(
105
- # type="file",
106
- # id="file-input",
107
- # accept="image/*",
108
- # hx_post="/upload",
109
- # hx_target="#image-panel",
110
- # hx_swap="outerHTML",
111
- # ),
112
- # cls="flex flex-col gap-2",
113
- # ),
114
- # fh.Div(id="image-panel", cls="p-4 border border-gray-300"),
115
- # cls="w-1/2",
116
- # ),
117
- # fh.Div(
118
- # fh.P("OCR Results:", cls="text-lg font-bold"),
119
- # fh.Div(id="ocr-results", cls="p-4 border border-gray-300"),
120
- # cls="w-1/2",
121
- # ),
122
- # cls="flex justify-between",
123
- # ),
124
- # fh.Script(
125
- # "htmx.on('htmx:afterRequest', function(evt) {"
126
- # " if (evt.detail.elt.id === 'file-input' && evt.detail.requestConfig.verb === 'post') {"
127
- # " htmx.trigger('#toast-container', 'showToast', {detail: {message: 'Upload successful'}});"
128
- # " }"
129
- # "});"
130
- # "htmx.on('htmx:beforeRequest', function(evt) {"
131
- # " if (evt.detail.elt.id === 'file-input' && evt.detail.requestConfig.verb === 'post') {"
132
- # " document.getElementById('ocr-results').innerHTML = '<div class=\"loading\">Processing...</div>';"
133
- # " }"
134
- # "});"
135
- # ),
136
- # cls="flex flex-col gap-4 justify-center items-center flex-1",
137
- )
138
-
139
- def footer():
140
- return fh.Footer(
141
- fh.P("Made by", cls="text-white text-lg"),
142
- fh.A(
143
- "Andrew Hinh",
144
- href="https://andrewhinh.github.io/",
145
- cls="text-blue-300 text-lg font-bold hover:text-blue-100",
146
- ),
147
- cls="justify-end text-right p-4",
148
- )
149
-
150
- # Routes
151
- @rt("/")
152
- async def get():
153
- return fh.Title(NAME), fh.Div(
154
- nav(),
155
- main_content(),
156
- footer(),
157
- cls="flex flex-col justify-between min-h-screen bg-zinc-900 w-full",
158
- )
159
-
160
- @rt("/{fname:path}.{ext:static}")
161
- async def static_files(fname: str, ext: str):
162
- static_file_path = parent_path / f"{fname}.{ext}"
163
- if static_file_path.exists():
164
- return fh.FileResponse(static_file_path)
165
-
166
- return fasthtml_app
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes