formless 0.1.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.

@@ -0,0 +1,39 @@
1
+ name: pre-commit
2
+
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches: [main]
7
+ # allows this Action to be triggered manually
8
+ workflow_dispatch:
9
+
10
+ jobs:
11
+ pre-commit:
12
+ runs-on: ubuntu-latest
13
+ env:
14
+ # Configure a constant location for the uv cache
15
+ UV_CACHE_DIR: /tmp/.uv-cache
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - name: Set up uv
19
+ # Install a specific uv version using the installer
20
+ run: curl -LsSf https://astral.sh/uv/0.3.0/install.sh | sh
21
+ - name: "Set up Python"
22
+ uses: actions/setup-python@v5
23
+ with:
24
+ python-version-file: "pyproject.toml"
25
+ - name: Restore uv cache
26
+ uses: actions/cache@v4
27
+ with:
28
+ path: /tmp/.uv-cache
29
+ key: uv-${{ runner.os }}-${{ hashFiles('uv.lock') }}
30
+ restore-keys: |
31
+ uv-${{ runner.os }}-${{ hashFiles('uv.lock') }}
32
+ uv-${{ runner.os }}
33
+ - name: Install the project
34
+ run: uv sync --all-extras --dev
35
+ # - name: Run tests
36
+ # # For example, using `pytest`
37
+ # run: uv run pytest tests
38
+ - name: Run pre-commit hooks
39
+ run: uv run pre-commit run --all-files
@@ -0,0 +1,207 @@
1
+ # Prerequisites
2
+ *.d
3
+
4
+ # Compiled Object files
5
+ *.slo
6
+ *.lo
7
+ *.o
8
+ *.obj
9
+
10
+ # Precompiled Headers
11
+ *.gch
12
+ *.pch
13
+
14
+ # Compiled Dynamic libraries
15
+ *.so
16
+ *.dylib
17
+ *.dll
18
+
19
+ # Fortran module files
20
+ *.mod
21
+ *.smod
22
+
23
+ # Compiled Static libraries
24
+ *.lai
25
+ *.la
26
+ *.a
27
+ *.lib
28
+
29
+ # Executables
30
+ *.exe
31
+ *.out
32
+ *.app
33
+
34
+ # cuda-toolkit
35
+ *.deb
36
+ cuda-samples/
37
+
38
+ # Byte-compiled / optimized / DLL files
39
+ __pycache__/
40
+ *.py[cod]
41
+ *$py.class
42
+
43
+ # C extensions
44
+ *.so
45
+
46
+ # Distribution / packaging
47
+ .Python
48
+ build/
49
+ develop-eggs/
50
+ dist/
51
+ downloads/
52
+ eggs/
53
+ .eggs/
54
+ lib/
55
+ lib64/
56
+ parts/
57
+ sdist/
58
+ var/
59
+ wheels/
60
+ share/python-wheels/
61
+ *.egg-info/
62
+ .installed.cfg
63
+ *.egg
64
+ MANIFEST
65
+
66
+ # PyInstaller
67
+ # Usually these files are written by a python script from a template
68
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
69
+ *.manifest
70
+ *.spec
71
+
72
+ # Installer logs
73
+ pip-log.txt
74
+ pip-delete-this-directory.txt
75
+
76
+ # Unit test / coverage reports
77
+ htmlcov/
78
+ .tox/
79
+ .nox/
80
+ .coverage
81
+ .coverage.*
82
+ .cache
83
+ nosetests.xml
84
+ coverage.xml
85
+ *.cover
86
+ *.py,cover
87
+ .hypothesis/
88
+ .pytest_cache/
89
+ cover/
90
+
91
+ # Translations
92
+ *.mo
93
+ *.pot
94
+
95
+ # Django stuff:
96
+ *.log
97
+ local_settings.py
98
+ db.sqlite3
99
+ db.sqlite3-journal
100
+
101
+ # Flask stuff:
102
+ instance/
103
+ .webassets-cache
104
+
105
+ # Scrapy stuff:
106
+ .scrapy
107
+
108
+ # Sphinx documentation
109
+ docs/_build/
110
+
111
+ # PyBuilder
112
+ .pybuilder/
113
+ target/
114
+
115
+ # Jupyter Notebook
116
+ .ipynb_checkpoints
117
+
118
+ # IPython
119
+ profile_default/
120
+ ipython_config.py
121
+
122
+ # pyenv
123
+ # For a library or package, you might want to ignore these files since the code is
124
+ # intended to run in multiple environments; otherwise, check them in:
125
+ # .python-version
126
+
127
+ # pipenv
128
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
129
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
130
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
131
+ # install all needed dependencies.
132
+ #Pipfile.lock
133
+
134
+ # poetry
135
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
136
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
137
+ # commonly ignored for libraries.
138
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
139
+ #poetry.lock
140
+
141
+ # pdm
142
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
143
+ #pdm.lock
144
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
145
+ # in version control.
146
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
147
+ .pdm.toml
148
+ .pdm-python
149
+ .pdm-build/
150
+
151
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
152
+ __pypackages__/
153
+
154
+ # Celery stuff
155
+ celerybeat-schedule
156
+ celerybeat.pid
157
+
158
+ # SageMath parsed files
159
+ *.sage.py
160
+
161
+ # Environments
162
+ .env
163
+ .venv
164
+ env/
165
+ venv/
166
+ ENV/
167
+ env.bak/
168
+ venv.bak/
169
+
170
+ # Spyder project settings
171
+ .spyderproject
172
+ .spyproject
173
+
174
+ # Rope project settings
175
+ .ropeproject
176
+
177
+ # mkdocs documentation
178
+ /site
179
+
180
+ # mypy
181
+ .mypy_cache/
182
+ .dmypy.json
183
+ dmypy.json
184
+
185
+ # Pyre type checker
186
+ .pyre/
187
+
188
+ # pytype static type analyzer
189
+ .pytype/
190
+
191
+ # Cython debug symbols
192
+ cython_debug/
193
+
194
+ # PyCharm
195
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
196
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
197
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
198
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
199
+ #.idea/
200
+
201
+ .vscode
202
+
203
+ # FastHTML
204
+ .sesskey
205
+
206
+ # Training
207
+ **/artifacts/
@@ -0,0 +1,29 @@
1
+ repos:
2
+ # a set of useful Python-based pre-commit hooks
3
+ - repo: https://github.com/pre-commit/pre-commit-hooks
4
+ rev: v4.1.0
5
+ hooks:
6
+ # list of definitions and supported hooks: https://pre-commit.com/hooks.html
7
+ - id: trailing-whitespace # removes any whitespace at the ends of lines
8
+ - id: check-toml # check toml syntax by loading all toml files
9
+ - id: check-yaml # check yaml syntax by loading all yaml files
10
+ - id: check-json # check-json syntax by loading all json files
11
+ # exclude: ^.devcontainer/.*\.json$ # exclude json files in the devcontainer
12
+ - id: check-merge-conflict # check for files with merge conflict strings
13
+ args: ["--assume-in-merge"] # and run this check even when not explicitly in a merge
14
+ - id: check-added-large-files # check that no "large" files have been added
15
+ args: ["--maxkb=10240"] # where large means 10MB+, as in Hugging Face's git server
16
+ - id: debug-statements # check for python debug statements (import pdb, breakpoint, etc.)
17
+ - id: detect-private-key # checks for private keys (BEGIN X PRIVATE KEY, etc.)
18
+
19
+ - repo: https://github.com/astral-sh/ruff-pre-commit
20
+ # Ruff version.
21
+ rev: v0.6.1
22
+ hooks:
23
+ # Run the linter.
24
+ - id: ruff
25
+ types_or: [ python, pyi, jupyter ]
26
+ args: [ --fix ]
27
+ # Run the formatter.
28
+ - id: ruff-format
29
+ types_or: [ python, pyi, jupyter ]
formless-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Andrew Hinh
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.3
2
+ Name: formless
3
+ Version: 0.1.0
4
+ Summary: Handwritten + image OCR.
5
+ License-File: LICENSE
6
+ Requires-Python: >=3.12
7
+ Requires-Dist: modal>=0.64.178
8
+ Requires-Dist: python-dotenv>=1.0.1
9
+ Requires-Dist: requests>=2.32.3
10
+ Requires-Dist: term-image>=0.7.2
11
+ Description-Content-Type: text/markdown
12
+
13
+ # formless
14
+
15
+ Handwritten + image OCR.
16
+
17
+ ## Set Up
18
+
19
+ Set up the environment:
20
+
21
+ ```bash
22
+ uv sync --all-extras --dev
23
+ uv run pre-commit install
24
+ modal setup
25
+ ```
26
+
27
+ ## Repository Structure
28
+
29
+ ```bash
30
+ .
31
+ ├── api # API.
32
+ ├── frontend # frontend.
33
+ ├── src/formless # python bindings.
34
+ ├── training # training.
35
+ ```
36
+
37
+ ## Development
38
+
39
+ ### API
40
+
41
+ Run the API:
42
+
43
+ ```bash
44
+ modal run api/app.py
45
+ ```
46
+
47
+ Deploy:
48
+
49
+ ```bash
50
+ modal deploy api/app.py
51
+ ```
52
+
53
+ ### Frontend
54
+
55
+ Run the web app:
56
+
57
+ ```bash
58
+ modal serve frontend/app.py
59
+ ```
60
+
61
+ Deploy:
62
+
63
+ ```bash
64
+ modal deploy frontend/app.py
65
+ ```
66
+
67
+ ### PyPI
68
+
69
+ Run the package:
70
+
71
+ ```bash
72
+ uv run formless -v
73
+ ```
74
+
75
+ Build the package:
76
+
77
+ ```bash
78
+ uvx --from build pyproject-build --installer uv
79
+ ```
80
+
81
+ Upload the package:
82
+
83
+ ```bash
84
+ uvx twine upload dist/*
85
+ ```
86
+
87
+ Test the uploaded package:
88
+
89
+ ```bash
90
+ uv run --with formless --no-project -- formless -vv
91
+ ```
92
+
93
+ ### Training
94
+
95
+ Run ETL on HF dataset:
96
+
97
+ ```bash
98
+ modal run ft/etl.py
99
+ ```
100
+
101
+ Train the model:
102
+
103
+ ```bash
104
+ modal run ft/train_modal.py
105
+ ```
@@ -0,0 +1,93 @@
1
+ # formless
2
+
3
+ Handwritten + image OCR.
4
+
5
+ ## Set Up
6
+
7
+ Set up the environment:
8
+
9
+ ```bash
10
+ uv sync --all-extras --dev
11
+ uv run pre-commit install
12
+ modal setup
13
+ ```
14
+
15
+ ## Repository Structure
16
+
17
+ ```bash
18
+ .
19
+ ├── api # API.
20
+ ├── frontend # frontend.
21
+ ├── src/formless # python bindings.
22
+ ├── training # training.
23
+ ```
24
+
25
+ ## Development
26
+
27
+ ### API
28
+
29
+ Run the API:
30
+
31
+ ```bash
32
+ modal run api/app.py
33
+ ```
34
+
35
+ Deploy:
36
+
37
+ ```bash
38
+ modal deploy api/app.py
39
+ ```
40
+
41
+ ### Frontend
42
+
43
+ Run the web app:
44
+
45
+ ```bash
46
+ modal serve frontend/app.py
47
+ ```
48
+
49
+ Deploy:
50
+
51
+ ```bash
52
+ modal deploy frontend/app.py
53
+ ```
54
+
55
+ ### PyPI
56
+
57
+ Run the package:
58
+
59
+ ```bash
60
+ uv run formless -v
61
+ ```
62
+
63
+ Build the package:
64
+
65
+ ```bash
66
+ uvx --from build pyproject-build --installer uv
67
+ ```
68
+
69
+ Upload the package:
70
+
71
+ ```bash
72
+ uvx twine upload dist/*
73
+ ```
74
+
75
+ Test the uploaded package:
76
+
77
+ ```bash
78
+ uv run --with formless --no-project -- formless -vv
79
+ ```
80
+
81
+ ### Training
82
+
83
+ Run ETL on HF dataset:
84
+
85
+ ```bash
86
+ modal run ft/etl.py
87
+ ```
88
+
89
+ Train the model:
90
+
91
+ ```bash
92
+ modal run ft/train_modal.py
93
+ ```
@@ -0,0 +1,171 @@
1
+ import os
2
+ import tempfile
3
+ import time
4
+ from pathlib import Path
5
+ from uuid import uuid4
6
+
7
+ import modal
8
+ from PIL import ImageFile
9
+
10
+ from utils import (
11
+ DEFAULT_IMG_URL,
12
+ GPU_IMAGE,
13
+ MINUTES,
14
+ NAME,
15
+ VOLUME_CONFIG,
16
+ Colors,
17
+ )
18
+
19
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
20
+ # -----------------------------------------------------------------------------
21
+
22
+
23
+ only_download = False # turn off gpu for initial download
24
+ model = "meta-llama/Llama-3.2-11B-Vision-Instruct"
25
+ gpu_memory_utilization = 0.90
26
+ max_model_len = 8192
27
+ max_num_seqs = 1
28
+ enforce_eager = True
29
+
30
+ question = "What is the content of this image?"
31
+ temperature = 0.2
32
+ max_tokens = 128
33
+
34
+ # -----------------------------------------------------------------------------
35
+
36
+ config_keys = [
37
+ k
38
+ for k, v in globals().items()
39
+ if not k.startswith("_") and isinstance(v, (int, float, str, bool, dict, list, tuple, Path, type(None)))
40
+ ]
41
+ config = {k: globals()[k] for k in config_keys}
42
+ config = {k: str(v) if isinstance(v, Path) else v for k, v in config.items()} # since Path not serializable
43
+
44
+ # -----------------------------------------------------------------------------
45
+
46
+
47
+ # Modal
48
+ IMAGE = GPU_IMAGE.pip_install( # add Python dependencies
49
+ "vllm==0.6.2", "term-image==0.7.2"
50
+ )
51
+ API_TIMEOUT = 5 * MINUTES
52
+ API_CONTAINER_IDLE_TIMEOUT = 20 * MINUTES # max
53
+ API_ALLOW_CONCURRENT_INPUTS = 1000 # max
54
+
55
+ GPU_TYPE = "H100"
56
+ GPU_COUNT = 2
57
+ GPU_SIZE = None # options = None, "40GB", "80GB"
58
+ GPU_CONFIG = f"{GPU_TYPE}:{GPU_COUNT}"
59
+ if GPU_TYPE.lower() == "a100":
60
+ GPU_CONFIG = modal.gpu.A100(count=GPU_COUNT, size=GPU_SIZE)
61
+
62
+ APP_NAME = f"{NAME}-api"
63
+ app = modal.App(name=APP_NAME)
64
+
65
+ # -----------------------------------------------------------------------------
66
+
67
+
68
+ # Model
69
+ @app.cls(
70
+ image=IMAGE,
71
+ gpu=None if only_download else GPU_CONFIG,
72
+ volumes=VOLUME_CONFIG,
73
+ secrets=[modal.Secret.from_dotenv(path=Path(__file__).parent)],
74
+ timeout=API_TIMEOUT,
75
+ container_idle_timeout=API_CONTAINER_IDLE_TIMEOUT,
76
+ allow_concurrent_inputs=API_ALLOW_CONCURRENT_INPUTS,
77
+ )
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
111
+
112
+ start = time.monotonic_ns()
113
+ request_id = uuid4()
114
+ print(f"Generating response to request {request_id}")
115
+
116
+ image_url = request.get("image_url")
117
+ response = requests.get(image_url, stream=True)
118
+ response.raise_for_status()
119
+ image = Image.open(response.raw).convert("RGB")
120
+ prompt = f"<|image|><|begin_of_text|>{config['question']}"
121
+ stop_token_ids = None
122
+
123
+ sampling_params = SamplingParams(
124
+ temperature=config["temperature"],
125
+ max_tokens=config["max_tokens"],
126
+ stop_token_ids=stop_token_ids,
127
+ )
128
+
129
+ inputs = {
130
+ "prompt": prompt,
131
+ "multi_modal_data": {"image": image},
132
+ }
133
+
134
+ outputs = self.llm.generate(inputs, sampling_params=sampling_params)
135
+ generated_text = outputs[0].outputs[0].text.strip()
136
+
137
+ # show the question, image, and response in the terminal for demonstration purposes
138
+ image_filename = image_url.split("/")[-1]
139
+ image_path = os.path.join(tempfile.gettempdir(), f"{uuid4()}-{image_filename}")
140
+ with open(image_path, "wb") as file:
141
+ file.write(response.content)
142
+ terminal_image = from_file(image_path)
143
+ terminal_image.draw()
144
+ print(
145
+ Colors.BOLD,
146
+ Colors.GREEN,
147
+ f"Response: {generated_text}",
148
+ Colors.END,
149
+ sep="",
150
+ )
151
+ print(f"request {request_id} completed in {round((time.monotonic_ns() - start) / 1e9, 2)} seconds")
152
+
153
+ return generated_text
154
+
155
+
156
+ ## For testing
157
+ @app.local_entrypoint()
158
+ def main(
159
+ twice=True,
160
+ ):
161
+ import requests
162
+
163
+ model = Model()
164
+
165
+ response = requests.post(model.infer.web_url, json={"image_url": DEFAULT_IMG_URL})
166
+ assert response.ok, response.status_code
167
+
168
+ if twice:
169
+ # second response is faster, because the Function is already running
170
+ response = requests.post(model.infer.web_url, json={"image_url": DEFAULT_IMG_URL})
171
+ assert response.ok, response.status_code