Spaces:
Running on Zero
Running on Zero
Launch PixText Studio with OCR, editable regions and ZeroGPU refinement
Browse files- .dockerignore +9 -0
- .gitignore +11 -0
- Dockerfile +11 -0
- LICENSE +202 -0
- README.md +29 -8
- app.py +371 -0
- packages.txt +3 -0
- pixtext_ocr.py +183 -0
- requirements.txt +16 -0
- space.py +93 -0
- zerogpu_attention.py +39 -0
.dockerignore
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.git
|
| 2 |
+
.venv
|
| 3 |
+
__pycache__
|
| 4 |
+
*.pyc
|
| 5 |
+
.pytest_cache
|
| 6 |
+
.ruff_cache
|
| 7 |
+
tests
|
| 8 |
+
runtime
|
| 9 |
+
.env*
|
.gitignore
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.py[cod]
|
| 3 |
+
.pytest_cache/
|
| 4 |
+
.ruff_cache/
|
| 5 |
+
.venv/
|
| 6 |
+
.env
|
| 7 |
+
.env.*
|
| 8 |
+
runtime/
|
| 9 |
+
deps/
|
| 10 |
+
*.key
|
| 11 |
+
*.pem
|
Dockerfile
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
RUN apt-get update && apt-get install -y --no-install-recommends build-essential libgl1 libglib2.0-0 libraqm0 && rm -rf /var/lib/apt/lists/*
|
| 3 |
+
RUN useradd -m -u 1000 user
|
| 4 |
+
WORKDIR /home/user/app
|
| 5 |
+
COPY requirements.txt ./
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
COPY --chown=user:user . .
|
| 8 |
+
USER user
|
| 9 |
+
ENV HOME=/home/user PYTHONUNBUFFERED=1 PYTHONPATH=/home/user/app/vendor HF_HOME=/home/user/.cache/huggingface
|
| 10 |
+
EXPOSE 7860
|
| 11 |
+
CMD ["python", "-m", "uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright 2026 PixText Authors
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
README.md
CHANGED
|
@@ -1,15 +1,36 @@
|
|
| 1 |
---
|
| 2 |
title: PixText Studio
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.30.0
|
| 8 |
-
python_version:
|
| 9 |
-
app_file:
|
| 10 |
-
pinned: false
|
| 11 |
license: apache-2.0
|
| 12 |
-
|
|
|
|
| 13 |
---
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: PixText Studio
|
| 3 |
+
emoji: ✍️
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: red
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.30.0
|
| 8 |
+
python_version: 3.12
|
| 9 |
+
app_file: space.py
|
|
|
|
| 10 |
license: apache-2.0
|
| 11 |
+
models:
|
| 12 |
+
- ATH-MaaS/PixText
|
| 13 |
---
|
| 14 |
|
| 15 |
+
# PixText Studio
|
| 16 |
+
|
| 17 |
+
Detect words, adjust their boxes, enter the text you want, and compare the repaired regions. The interface uses the same CRAFT + PP-OCRv6 detection and PixText inference code as the ComfyUI nodes.
|
| 18 |
+
|
| 19 |
+
Upload an image or choose the English and Chinese examples. Select only the regions you want to repair. You can move or resize any box, or draw a new one. MeanFlow defaults to four steps; Teacher defaults to 25. The result includes an image slider, matching region crops, a PNG download and editable region JSON.
|
| 20 |
+
|
| 21 |
+
## Run
|
| 22 |
+
|
| 23 |
+
Deploy this directory as a Gradio Space with ZeroGPU, or run locally on an Ampere-or-newer CUDA GPU:
|
| 24 |
+
|
| 25 |
+
```sh
|
| 26 |
+
python -m pip install -r requirements.txt
|
| 27 |
+
python space.py
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
Model packages download from [ATH-MaaS/PixText](https://huggingface.co/ATH-MaaS/PixText) when first used. The optional OCR files download on the first detection run and are checked against release SHA-256 hashes. For an existing installation, set `PIXTEXT_MODEL_ROOT` to the directory containing the `PixText-MeanFlow` and `PixText-Teacher` packages and `PIXTEXT_OCR_ROOT` to the OCR model directory. Both variables are optional.
|
| 31 |
+
|
| 32 |
+
Jobs are queued one at a time. Images are stored in isolated temporary sessions and removed after one hour of inactivity, when the next session is created. Nothing is uploaded to a dataset or sent to an external inference service.
|
| 33 |
+
|
| 34 |
+
The vendored inference and OCR code is from [PixText commit 7779419](https://github.com/yaoliliu/PixText/tree/7779419de634d9785ec23558942480db713f0f99). Model packages retain their manifests, font notices and SHA-256 checks. CRAFT weights come from [EasyOCR](https://github.com/JaidedAI/EasyOCR); recognition weights and configuration come from [PaddlePaddle](https://huggingface.co/PaddlePaddle/PP-OCRv6_medium_rec_onnx).
|
| 35 |
+
|
| 36 |
+
The Space uses Gradio Server to serve the custom editor and queue GPU requests. On ZeroGPU, PyTorch SDPA uses the original PixText token-routing mask without runtime compilation. A Dockerfile is also included for dedicated GPU hosting.
|
app.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""PixText Studio: one image, editable OCR regions, real GPU refinement."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import io
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
import math
|
| 10 |
+
import os
|
| 11 |
+
import shutil
|
| 12 |
+
import sys
|
| 13 |
+
import tempfile
|
| 14 |
+
import threading
|
| 15 |
+
import time
|
| 16 |
+
import urllib.request
|
| 17 |
+
import uuid
|
| 18 |
+
import zipfile
|
| 19 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
from fastapi import FastAPI, File, HTTPException, UploadFile
|
| 23 |
+
from fastapi.responses import FileResponse
|
| 24 |
+
from fastapi.staticfiles import StaticFiles
|
| 25 |
+
from PIL import Image, ImageOps, UnidentifiedImageError
|
| 26 |
+
from pydantic import BaseModel, Field
|
| 27 |
+
|
| 28 |
+
ROOT = Path(__file__).resolve().parent
|
| 29 |
+
sys.path.insert(0, str(ROOT / "vendor"))
|
| 30 |
+
RUNTIME = Path(os.environ.get("PIXTEXT_RUNTIME", tempfile.gettempdir())) / "pixtext-studio"
|
| 31 |
+
RUNTIME.mkdir(parents=True, exist_ok=True)
|
| 32 |
+
SESSION_TTL = 3600
|
| 33 |
+
MAX_UPLOAD = 16 * 1024 * 1024
|
| 34 |
+
Image.MAX_IMAGE_PIXELS = 16_777_216
|
| 35 |
+
POOL = ThreadPoolExecutor(max_workers=1, thread_name_prefix="pixtext")
|
| 36 |
+
LOCK = threading.RLock()
|
| 37 |
+
SESSIONS: dict[str, dict] = {}
|
| 38 |
+
JOBS: dict[str, dict] = {}
|
| 39 |
+
PIPELINE = None
|
| 40 |
+
PIPELINE_VARIANT = None
|
| 41 |
+
EXAMPLES = {
|
| 42 |
+
"english": {"label": "English editorial", "subtitle": "Four words, one poster"},
|
| 43 |
+
"chinese": {"label": "Chinese New Year", "subtitle": "Character-level corrections"},
|
| 44 |
+
}
|
| 45 |
+
if os.environ.get("PIXTEXT_GRADIO") == "1":
|
| 46 |
+
from gradio import Server
|
| 47 |
+
app = Server(title="PixText Studio", docs_url=None, redoc_url=None)
|
| 48 |
+
else:
|
| 49 |
+
app = FastAPI(title="PixText Studio", docs_url=None, redoc_url=None)
|
| 50 |
+
app.mount("/static", StaticFiles(directory=ROOT / "static"), name="static")
|
| 51 |
+
app.mount("/examples", StaticFiles(directory=ROOT / "examples"), name="examples")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class ExampleRequest(BaseModel):
|
| 55 |
+
example: str
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class Region(BaseModel):
|
| 59 |
+
id: str = Field(min_length=1, max_length=80)
|
| 60 |
+
bbox: tuple[float, float, float, float]
|
| 61 |
+
text: str = Field(max_length=64)
|
| 62 |
+
enabled: bool = True
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class RefineRequest(BaseModel):
|
| 66 |
+
regions: list[Region] = Field(max_length=256)
|
| 67 |
+
variant: str = "meanflow"
|
| 68 |
+
steps: int = Field(default=4, ge=1, le=40)
|
| 69 |
+
seed: int = Field(default=42, ge=0, le=2**32 - 1)
|
| 70 |
+
guidance: float = Field(default=3.3, ge=0, le=10)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class DetectRequest(BaseModel):
|
| 74 |
+
text_threshold: float = Field(default=0.5, ge=0.1, le=0.95)
|
| 75 |
+
link_threshold: float = Field(default=0.2, ge=0.1, le=0.95)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def session_for(sid: str):
|
| 79 |
+
with LOCK:
|
| 80 |
+
value = SESSIONS.get(sid)
|
| 81 |
+
if value is None:
|
| 82 |
+
raise HTTPException(404, "This image session has expired. Please open the image again.")
|
| 83 |
+
value["touched"] = time.monotonic()
|
| 84 |
+
return value
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def make_session(image: Image.Image, example: str | None = None):
|
| 88 |
+
if image.width < 16 or image.height < 16 or max(image.size) > 4096:
|
| 89 |
+
raise HTTPException(422, "Use an image between 16 and 4096 pixels on each side.")
|
| 90 |
+
if image.width * image.height > Image.MAX_IMAGE_PIXELS:
|
| 91 |
+
raise HTTPException(422, "Use an image with no more than 16 megapixels.")
|
| 92 |
+
with LOCK:
|
| 93 |
+
for sid, value in list(SESSIONS.items()):
|
| 94 |
+
active = value.get("job") and JOBS.get(value["job"], {}).get("status") in (
|
| 95 |
+
"queued", "running"
|
| 96 |
+
)
|
| 97 |
+
if time.monotonic() - value["touched"] > SESSION_TTL and not active:
|
| 98 |
+
shutil.rmtree(value["directory"], ignore_errors=True)
|
| 99 |
+
SESSIONS.pop(sid)
|
| 100 |
+
for jid in [k for k, j in JOBS.items() if j["session"] == sid]:
|
| 101 |
+
JOBS.pop(jid)
|
| 102 |
+
if len(SESSIONS) >= 64:
|
| 103 |
+
raise HTTPException(503, "The studio is busy. Please try again shortly.")
|
| 104 |
+
sid = uuid.uuid4().hex
|
| 105 |
+
directory = RUNTIME / sid
|
| 106 |
+
directory.mkdir()
|
| 107 |
+
image.save(directory / "source.png")
|
| 108 |
+
SESSIONS[sid] = {
|
| 109 |
+
"directory": directory, "size": image.size, "example": example,
|
| 110 |
+
"touched": time.monotonic(), "job": None,
|
| 111 |
+
}
|
| 112 |
+
return {"id": sid, "width": image.width, "height": image.height,
|
| 113 |
+
"image": f"/api/sessions/{sid}/source.png", "example": example}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def update_job(jid: str, **values):
|
| 117 |
+
with LOCK:
|
| 118 |
+
JOBS[jid].update(values)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def submit(sid: str, kind: str, function, *args):
|
| 122 |
+
session = session_for(sid)
|
| 123 |
+
with LOCK:
|
| 124 |
+
current = JOBS.get(session.get("job"))
|
| 125 |
+
if current and current["status"] in ("queued", "running"):
|
| 126 |
+
if current["kind"] == kind:
|
| 127 |
+
return {"job_id": current["id"]}
|
| 128 |
+
raise HTTPException(409, "Wait for the current operation to finish.")
|
| 129 |
+
if sum(j["status"] in ("queued", "running") for j in JOBS.values()) >= 12:
|
| 130 |
+
raise HTTPException(503, "The queue is full. Please try again shortly.")
|
| 131 |
+
jid = uuid.uuid4().hex
|
| 132 |
+
JOBS[jid] = {"id": jid, "session": sid, "kind": kind, "status": "queued",
|
| 133 |
+
"progress": 0, "message": "Waiting for the model", "created": time.time()}
|
| 134 |
+
session["job"] = jid
|
| 135 |
+
|
| 136 |
+
def run():
|
| 137 |
+
started = time.perf_counter()
|
| 138 |
+
update_job(jid, status="running", message="Preparing", progress=0.02)
|
| 139 |
+
try:
|
| 140 |
+
result = function(session, jid, *args)
|
| 141 |
+
result["elapsed"] = round(time.perf_counter() - started, 2)
|
| 142 |
+
update_job(jid, status="done", progress=1, message="Complete", result=result)
|
| 143 |
+
except Exception as exc:
|
| 144 |
+
logging.exception("PixText %s job failed", kind)
|
| 145 |
+
if type(exc).__name__ == "OutOfMemoryError":
|
| 146 |
+
message = "The GPU ran out of memory. Try refining fewer regions at a time."
|
| 147 |
+
elif "CUDA GPU" in str(exc):
|
| 148 |
+
message = "Refinement needs a CUDA GPU. Detection and box editing are ready to use."
|
| 149 |
+
elif "checksum" in str(exc).lower():
|
| 150 |
+
message = "A model file failed its checksum check. Please retry or contact the Space owner."
|
| 151 |
+
elif "RAQM" in str(exc):
|
| 152 |
+
message = "Text rendering needs a Pillow build with RAQM. Please contact the Space owner."
|
| 153 |
+
else:
|
| 154 |
+
message = ("Detection" if kind == "detect" else "Refinement") + " could not finish. Please retry or contact the Space owner."
|
| 155 |
+
update_job(jid, status="error", message=message)
|
| 156 |
+
|
| 157 |
+
POOL.submit(run)
|
| 158 |
+
return {"job_id": jid}
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def download_checked(url: str, path: Path, expected: str):
|
| 162 |
+
if path.exists() and hashlib.sha256(path.read_bytes()).hexdigest() == expected:
|
| 163 |
+
return
|
| 164 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 165 |
+
partial = path.with_suffix(path.suffix + ".partial")
|
| 166 |
+
try:
|
| 167 |
+
with urllib.request.urlopen(url, timeout=90) as response, partial.open("wb") as stream:
|
| 168 |
+
shutil.copyfileobj(response, stream)
|
| 169 |
+
if hashlib.sha256(partial.read_bytes()).hexdigest() != expected:
|
| 170 |
+
raise RuntimeError("An OCR model checksum did not match. Please try the download again.")
|
| 171 |
+
partial.replace(path)
|
| 172 |
+
finally:
|
| 173 |
+
partial.unlink(missing_ok=True)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def ocr_root(jid: str):
|
| 177 |
+
existing = os.environ.get("PIXTEXT_OCR_ROOT")
|
| 178 |
+
if existing:
|
| 179 |
+
return Path(existing)
|
| 180 |
+
root = Path(os.environ.get("HF_HOME", str(Path.home() / ".cache/huggingface"))) / "pixtext_ocr"
|
| 181 |
+
craft = root / "craft_mlt_25k.pth"
|
| 182 |
+
craft_sha = "4a5efbfb48b4081100544e75e1e2b57f8de3d84f213004b14b85fd4b3748db17"
|
| 183 |
+
if not craft.exists() or hashlib.sha256(craft.read_bytes()).hexdigest() != craft_sha:
|
| 184 |
+
update_job(jid, message="Downloading CRAFT detection model", progress=0.06)
|
| 185 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 186 |
+
archive = root / "craft.zip.partial"
|
| 187 |
+
try:
|
| 188 |
+
with urllib.request.urlopen("https://github.com/JaidedAI/EasyOCR/releases/download/pre-v1.1.6/craft_mlt_25k.zip", timeout=90) as response, archive.open("wb") as stream:
|
| 189 |
+
shutil.copyfileobj(response, stream)
|
| 190 |
+
with zipfile.ZipFile(archive) as zipped:
|
| 191 |
+
entry = next(n for n in zipped.namelist() if Path(n).name == "craft_mlt_25k.pth")
|
| 192 |
+
content = zipped.read(entry)
|
| 193 |
+
if hashlib.sha256(content).hexdigest() != craft_sha:
|
| 194 |
+
raise RuntimeError("The CRAFT checksum did not match. Please try again.")
|
| 195 |
+
partial = craft.with_suffix(".partial")
|
| 196 |
+
partial.write_bytes(content)
|
| 197 |
+
partial.replace(craft)
|
| 198 |
+
finally:
|
| 199 |
+
archive.unlink(missing_ok=True)
|
| 200 |
+
base = "https://huggingface.co/PaddlePaddle/PP-OCRv6_medium_rec_onnx/resolve/50c7eacafc52fa7bcf4194e8cd08e46f8558504b/"
|
| 201 |
+
for name, sha in {
|
| 202 |
+
"inference.onnx": "9c09abf0957f7968c7586464b7397b84ad2387a0497a351af40e9acc71b673ba",
|
| 203 |
+
"inference.yml": "991b700facf5b50a7de193468207d5f4255b538dde0d312ae3b7c7a9b6873129",
|
| 204 |
+
}.items():
|
| 205 |
+
update_job(jid, message="Preparing PP-OCRv6 recognition model", progress=0.12)
|
| 206 |
+
download_checked(base + name, root / "PP-OCRv6_medium_rec_onnx" / name, sha)
|
| 207 |
+
return root
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def detect(session, jid, request: DetectRequest):
|
| 211 |
+
import torch
|
| 212 |
+
from pixtext_ocr import detect_words
|
| 213 |
+
|
| 214 |
+
torch.set_num_threads(4)
|
| 215 |
+
root = ocr_root(jid)
|
| 216 |
+
update_job(jid, message="Detecting words and reading text", progress=0.3)
|
| 217 |
+
with Image.open(session["directory"] / "source.png") as image:
|
| 218 |
+
result = detect_words(image, root, request.text_threshold, request.link_threshold)
|
| 219 |
+
return {"regions": result["regions"], "engine": result["engine"]}
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def refine(session, jid, request: RefineRequest, progress_report=None):
|
| 223 |
+
global PIPELINE, PIPELINE_VARIANT
|
| 224 |
+
import torch
|
| 225 |
+
from pixtext import PixTextPipeline, TextEdit
|
| 226 |
+
|
| 227 |
+
report = progress_report or (lambda **values: update_job(jid, **values))
|
| 228 |
+
|
| 229 |
+
if not torch.cuda.is_available():
|
| 230 |
+
raise RuntimeError("Refinement needs a CUDA GPU. Detection and box editing are ready to use.")
|
| 231 |
+
torch.set_num_threads(4)
|
| 232 |
+
if os.environ.get("PIXTEXT_GPU_MEMORY_FRACTION"):
|
| 233 |
+
torch.cuda.set_per_process_memory_fraction(float(os.environ["PIXTEXT_GPU_MEMORY_FRACTION"]))
|
| 234 |
+
if PIPELINE_VARIANT != request.variant:
|
| 235 |
+
if PIPELINE is not None:
|
| 236 |
+
PIPELINE = None
|
| 237 |
+
torch.cuda.empty_cache()
|
| 238 |
+
name = "PixText-MeanFlow" if request.variant == "meanflow" else "PixText-Teacher"
|
| 239 |
+
report(message=f"Loading {name}", progress=0.04)
|
| 240 |
+
if os.environ.get("PIXTEXT_MODEL_ROOT"):
|
| 241 |
+
package = Path(os.environ["PIXTEXT_MODEL_ROOT"]) / name
|
| 242 |
+
else:
|
| 243 |
+
from huggingface_hub import snapshot_download
|
| 244 |
+
package = Path(snapshot_download("ATH-MaaS/PixText", allow_patterns=[f"models/{name}/*"])) / "models" / name
|
| 245 |
+
PIPELINE = PixTextPipeline.from_pretrained(package, device="cuda", dtype=torch.bfloat16)
|
| 246 |
+
PIPELINE_VARIANT = request.variant
|
| 247 |
+
rows = [row for row in request.regions if row.enabled]
|
| 248 |
+
edits = [TextEdit(tuple(row.bbox), row.text.strip()) for row in rows]
|
| 249 |
+
directory = session["directory"]
|
| 250 |
+
|
| 251 |
+
def progress(done, total):
|
| 252 |
+
report(progress=0.15 + 0.8 * done / total,
|
| 253 |
+
message=f"Refining · step {done} of {total}", current=done, total=total)
|
| 254 |
+
|
| 255 |
+
result = PIPELINE.edit(directory / "source.png", edits, seed=request.seed,
|
| 256 |
+
steps=request.steps, guidance_scale=request.guidance,
|
| 257 |
+
sample_id="studio", progress_callback=progress)
|
| 258 |
+
report(message="Preparing region comparisons", progress=0.97)
|
| 259 |
+
result.image.save(directory / f"{jid}.png")
|
| 260 |
+
crops = []
|
| 261 |
+
with Image.open(directory / "source.png") as before:
|
| 262 |
+
for i, row in enumerate(rows):
|
| 263 |
+
x0, y0, x1, y1 = row.bbox
|
| 264 |
+
padding = max(8, (y1 - y0) * 0.2)
|
| 265 |
+
box = (max(0, math.floor(x0 - padding)), max(0, math.floor(y0 - padding)),
|
| 266 |
+
min(before.width, math.ceil(x1 + padding)), min(before.height, math.ceil(y1 + padding)))
|
| 267 |
+
for label, image in (("before", before), ("after", result.image)):
|
| 268 |
+
image.crop(box).save(directory / f"{jid}-{i}-{label}.png")
|
| 269 |
+
crops.append({"id": row.id, "text": row.text, "bbox": row.bbox,
|
| 270 |
+
"before": f"{jid}-{i}-before.png", "after": f"{jid}-{i}-after.png"})
|
| 271 |
+
metadata = {"regions": [row.model_dump() for row in rows], "model": request.variant,
|
| 272 |
+
"steps": request.steps, "seed": request.seed, "guidance": request.guidance}
|
| 273 |
+
(directory / f"{jid}.json").write_text(json.dumps(metadata, ensure_ascii=False, indent=2))
|
| 274 |
+
return {**metadata, "image": f"{jid}.png", "regions": crops, "metadata": f"{jid}.json"}
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@app.get("/")
|
| 278 |
+
def index():
|
| 279 |
+
return FileResponse(ROOT / "static/index.html")
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
@app.get("/api/config")
|
| 283 |
+
def config():
|
| 284 |
+
return {"examples": EXAMPLES, "models": ["meanflow", "teacher"],
|
| 285 |
+
"transport": "gradio" if os.environ.get("PIXTEXT_GRADIO") == "1" else "http"}
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@app.post("/api/session")
|
| 289 |
+
def example_session(request: ExampleRequest):
|
| 290 |
+
if request.example not in EXAMPLES:
|
| 291 |
+
raise HTTPException(404, "Example not found")
|
| 292 |
+
with Image.open(ROOT / "examples" / f"{request.example}.png") as image:
|
| 293 |
+
return make_session(image.convert("RGB"), request.example)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
@app.post("/api/upload")
|
| 297 |
+
async def upload(file: UploadFile = File(...)):
|
| 298 |
+
content = await file.read(MAX_UPLOAD + 1)
|
| 299 |
+
await file.close()
|
| 300 |
+
if len(content) > MAX_UPLOAD:
|
| 301 |
+
raise HTTPException(413, "Choose an image smaller than 16 MB.")
|
| 302 |
+
try:
|
| 303 |
+
with Image.open(io.BytesIO(content)) as opened:
|
| 304 |
+
if opened.format not in ("PNG", "JPEG", "WEBP"):
|
| 305 |
+
raise HTTPException(422, "Choose a PNG, JPEG or WebP image.")
|
| 306 |
+
image = ImageOps.exif_transpose(opened).convert("RGB")
|
| 307 |
+
return make_session(image)
|
| 308 |
+
except (UnidentifiedImageError, OSError, Image.DecompressionBombError):
|
| 309 |
+
raise HTTPException(422, "This image could not be opened. Try a PNG, JPEG or WebP file.")
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
@app.get("/api/sessions/{sid}/targets")
|
| 313 |
+
def example_targets(sid: str):
|
| 314 |
+
session = session_for(sid)
|
| 315 |
+
if not session["example"]:
|
| 316 |
+
raise HTTPException(404, "No example targets for this image")
|
| 317 |
+
rows = json.loads((ROOT / "examples" / f"{session['example']}.json").read_text())
|
| 318 |
+
return {"regions": [{**row, "id": f"example-{i}", "enabled": True,
|
| 319 |
+
"origin": "example", "recognized_text": "Example target"}
|
| 320 |
+
for i, row in enumerate(rows)]}
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
@app.post("/api/sessions/{sid}/detect")
|
| 324 |
+
def start_detect(sid: str, request: DetectRequest):
|
| 325 |
+
return submit(sid, "detect", detect, request)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@app.post("/api/sessions/{sid}/refine")
|
| 329 |
+
def start_refine(sid: str, request: RefineRequest):
|
| 330 |
+
validate_refine(sid, request)
|
| 331 |
+
return submit(sid, "refine", refine, request)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def validate_refine(sid: str, request: RefineRequest):
|
| 335 |
+
session = session_for(sid)
|
| 336 |
+
if request.variant not in ("meanflow", "teacher"):
|
| 337 |
+
raise HTTPException(422, "Choose MeanFlow or Teacher.")
|
| 338 |
+
selected = [r for r in request.regions if r.enabled]
|
| 339 |
+
if not selected or len(selected) > 24:
|
| 340 |
+
raise HTTPException(422, "Select between 1 and 24 regions to refine.")
|
| 341 |
+
for region in selected:
|
| 342 |
+
x0, y0, x1, y1 = region.bbox
|
| 343 |
+
if not all(math.isfinite(v) for v in region.bbox) or not (
|
| 344 |
+
0 <= x0 < x1 <= session["size"][0] and 0 <= y0 < y1 <= session["size"][1]
|
| 345 |
+
):
|
| 346 |
+
raise HTTPException(422, "A box is outside the image. Adjust it before refining.")
|
| 347 |
+
if not region.text.strip():
|
| 348 |
+
raise HTTPException(422, "Enter the target text for every selected region.")
|
| 349 |
+
return session
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
@app.get("/api/sessions/{sid}/jobs/{jid}")
|
| 353 |
+
def job(sid: str, jid: str):
|
| 354 |
+
session_for(sid)
|
| 355 |
+
with LOCK:
|
| 356 |
+
value = JOBS.get(jid)
|
| 357 |
+
if value is None or value["session"] != sid:
|
| 358 |
+
raise HTTPException(404, "Job not found")
|
| 359 |
+
return {k: v for k, v in value.items() if k != "session"}
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
@app.get("/api/sessions/{sid}/{filename}")
|
| 363 |
+
def session_file(sid: str, filename: str):
|
| 364 |
+
session = session_for(sid)
|
| 365 |
+
# File names are server-generated. A session cannot address another session's data.
|
| 366 |
+
if Path(filename).name != filename or not filename.endswith((".png", ".json")):
|
| 367 |
+
raise HTTPException(404, "File not found")
|
| 368 |
+
path = session["directory"] / filename
|
| 369 |
+
if not path.is_file():
|
| 370 |
+
raise HTTPException(404, "File not found")
|
| 371 |
+
return FileResponse(path, headers={"Cache-Control": "private, no-store"})
|
packages.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
libgl1
|
| 2 |
+
libglib2.0-0
|
| 3 |
+
libraqm0
|
pixtext_ocr.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Local, optional CRAFT word detection and PP-OCRv6 CTC recognition.
|
| 2 |
+
|
| 3 |
+
Models are installed explicitly; inference never downloads files or calls an OCR service.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import hashlib
|
| 9 |
+
import json
|
| 10 |
+
import math
|
| 11 |
+
from functools import lru_cache
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
from PIL import Image
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def model_files(root: Path) -> tuple[Path, Path, Path]:
|
| 19 |
+
paths = (
|
| 20 |
+
root / "craft_mlt_25k.pth",
|
| 21 |
+
root / "PP-OCRv6_medium_rec_onnx/inference.onnx",
|
| 22 |
+
root / "PP-OCRv6_medium_rec_onnx/inference.yml",
|
| 23 |
+
)
|
| 24 |
+
missing = [str(p.name) for p in paths if not p.is_file()]
|
| 25 |
+
if missing:
|
| 26 |
+
raise ValueError(
|
| 27 |
+
"Install the optional OCR models in ComfyUI/models/pixtext_ocr. "
|
| 28 |
+
"Download links and paths are in the English workflow's OCR setup note. Missing: "
|
| 29 |
+
+ ", ".join(missing)
|
| 30 |
+
)
|
| 31 |
+
return paths
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def model_identity(root: Path):
|
| 35 |
+
return tuple((str(p), p.stat().st_size, p.stat().st_mtime_ns) for p in model_files(root))
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def decode_ctc(probabilities: np.ndarray, vocabulary: list[str], valid_steps: int):
|
| 39 |
+
"""Collapse repeats before removing blanks, preserving repeated letters across blanks."""
|
| 40 |
+
sequence = probabilities[:valid_steps]
|
| 41 |
+
ids, scores = sequence.argmax(-1), sequence.max(-1)
|
| 42 |
+
text, confidence, previous = [], [], -1
|
| 43 |
+
for index, score in zip(ids, scores, strict=True):
|
| 44 |
+
index = int(index)
|
| 45 |
+
if index and index != previous:
|
| 46 |
+
if index >= len(vocabulary):
|
| 47 |
+
raise ValueError("OCR dictionary does not match the recognition model")
|
| 48 |
+
text.append(vocabulary[index])
|
| 49 |
+
confidence.append(float(score))
|
| 50 |
+
previous = index
|
| 51 |
+
return "".join(text), float(np.mean(confidence)) if confidence else 0.0
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def crop_quad(rgb: np.ndarray, quad: np.ndarray):
|
| 55 |
+
import cv2
|
| 56 |
+
|
| 57 |
+
width = max(2, round(max(np.linalg.norm(quad[1] - quad[0]), np.linalg.norm(quad[2] - quad[3]))))
|
| 58 |
+
height = max(
|
| 59 |
+
2, round(max(np.linalg.norm(quad[3] - quad[0]), np.linalg.norm(quad[2] - quad[1])))
|
| 60 |
+
)
|
| 61 |
+
destination = np.float32([[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]])
|
| 62 |
+
matrix = cv2.getPerspectiveTransform(quad.astype(np.float32), destination)
|
| 63 |
+
return cv2.warpPerspective(rgb, matrix, (width, height))
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class WordOCR:
|
| 67 |
+
def __init__(self, identity):
|
| 68 |
+
try:
|
| 69 |
+
import onnxruntime as ort
|
| 70 |
+
import torch
|
| 71 |
+
import yaml
|
| 72 |
+
from easyocr.craft import CRAFT
|
| 73 |
+
from easyocr.detection import copyStateDict
|
| 74 |
+
except ImportError as exc:
|
| 75 |
+
raise RuntimeError(
|
| 76 |
+
"Install requirements-ocr.txt into ComfyUI's Python environment to use automatic OCR."
|
| 77 |
+
) from exc
|
| 78 |
+
craft_path, rec_path, dictionary = [Path(row[0]) for row in identity]
|
| 79 |
+
self.detector = CRAFT()
|
| 80 |
+
self.detector.load_state_dict(
|
| 81 |
+
copyStateDict(torch.load(craft_path, map_location="cpu", weights_only=True))
|
| 82 |
+
)
|
| 83 |
+
self.detector.eval()
|
| 84 |
+
options = ort.SessionOptions()
|
| 85 |
+
options.intra_op_num_threads = 4
|
| 86 |
+
options.inter_op_num_threads = 1
|
| 87 |
+
self.recognizer = ort.InferenceSession(
|
| 88 |
+
str(rec_path), sess_options=options, providers=["CPUExecutionProvider"]
|
| 89 |
+
)
|
| 90 |
+
config = yaml.safe_load(dictionary.read_text(encoding="utf-8"))
|
| 91 |
+
chars = config["PostProcess"]["character_dict"]
|
| 92 |
+
self.vocabulary = (
|
| 93 |
+
["blank"] + chars + ([" "] if config["PostProcess"].get("use_space_char", True) else [])
|
| 94 |
+
)
|
| 95 |
+
self.input_name = self.recognizer.get_inputs()[0].name
|
| 96 |
+
|
| 97 |
+
def recognize(self, crops):
|
| 98 |
+
import cv2
|
| 99 |
+
|
| 100 |
+
results = []
|
| 101 |
+
# Small batches bound RAM for the large multilingual output vocabulary.
|
| 102 |
+
for start in range(0, len(crops), 8):
|
| 103 |
+
group = crops[start : start + 8]
|
| 104 |
+
widths = [min(3200, max(1, math.ceil(48 * c.shape[1] / c.shape[0]))) for c in group]
|
| 105 |
+
width = max(320, max(widths))
|
| 106 |
+
batch = np.zeros((len(group), 3, 48, width), dtype=np.float32)
|
| 107 |
+
for i, (crop, valid_width) in enumerate(zip(group, widths, strict=True)):
|
| 108 |
+
# Official PP-OCR preprocessing uses BGR, not RGB.
|
| 109 |
+
resized = cv2.resize(crop[:, :, ::-1], (valid_width, 48))
|
| 110 |
+
batch[i, :, :, :valid_width] = (
|
| 111 |
+
(resized.astype(np.float32) / 255 - 0.5) / 0.5
|
| 112 |
+
).transpose(2, 0, 1)
|
| 113 |
+
predictions = self.recognizer.run(None, {self.input_name: batch})[0]
|
| 114 |
+
if predictions.shape[-1] != len(self.vocabulary):
|
| 115 |
+
raise ValueError("OCR model output and dictionary have different vocabulary sizes")
|
| 116 |
+
for pred, valid_width in zip(predictions, widths, strict=True):
|
| 117 |
+
results.append(
|
| 118 |
+
decode_ctc(
|
| 119 |
+
pred,
|
| 120 |
+
self.vocabulary,
|
| 121 |
+
min(len(pred), math.ceil(len(pred) * valid_width / width)),
|
| 122 |
+
)
|
| 123 |
+
)
|
| 124 |
+
return results
|
| 125 |
+
|
| 126 |
+
def detect(self, image: Image.Image, text_threshold: float, link_threshold: float):
|
| 127 |
+
from easyocr.detection import test_net
|
| 128 |
+
|
| 129 |
+
rgb = np.array(image.convert("RGB"))
|
| 130 |
+
boxes, _ = test_net(
|
| 131 |
+
1280, 1.5, self.detector, rgb, text_threshold, link_threshold, 0.4, False, "cpu"
|
| 132 |
+
)
|
| 133 |
+
quads = list(boxes[0])
|
| 134 |
+
if len(quads) > 256:
|
| 135 |
+
raise ValueError(
|
| 136 |
+
"More than 256 words detected. Crop the image or raise the text threshold."
|
| 137 |
+
)
|
| 138 |
+
recognition = self.recognize([crop_quad(rgb, q) for q in quads])
|
| 139 |
+
rows = []
|
| 140 |
+
for quad, (text, score) in zip(quads, recognition, strict=True):
|
| 141 |
+
if not text.strip():
|
| 142 |
+
continue
|
| 143 |
+
low = np.maximum(0, quad.min(axis=0))
|
| 144 |
+
high = np.minimum([image.width, image.height], quad.max(axis=0))
|
| 145 |
+
if np.any(high <= low):
|
| 146 |
+
continue
|
| 147 |
+
bbox = [round(float(x), 2) for x in [*low, *high]]
|
| 148 |
+
key = json.dumps([bbox, text], ensure_ascii=False)
|
| 149 |
+
rows.append(
|
| 150 |
+
{
|
| 151 |
+
"id": "ocr-" + hashlib.sha256(key.encode()).hexdigest()[:16],
|
| 152 |
+
"bbox": bbox,
|
| 153 |
+
"text": text,
|
| 154 |
+
"recognized_text": text,
|
| 155 |
+
"confidence": round(score, 4),
|
| 156 |
+
"enabled": False,
|
| 157 |
+
"origin": "ocr",
|
| 158 |
+
}
|
| 159 |
+
)
|
| 160 |
+
rows.sort(key=lambda row: (round(row["bbox"][1] / 12), row["bbox"][0]))
|
| 161 |
+
return rows
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@lru_cache(maxsize=1)
|
| 165 |
+
def load_ocr(identity):
|
| 166 |
+
return WordOCR(identity)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def detect_words(image: Image.Image, root: Path, text_threshold=0.5, link_threshold=0.2):
|
| 170 |
+
identity = model_identity(root)
|
| 171 |
+
rows = load_ocr(identity).detect(image, text_threshold, link_threshold)
|
| 172 |
+
source_id = "pixels:" + hashlib.sha256(image.convert("RGB").tobytes()).hexdigest()
|
| 173 |
+
document = {
|
| 174 |
+
"version": 1,
|
| 175 |
+
"source_id": source_id,
|
| 176 |
+
"size": list(image.size),
|
| 177 |
+
"regions": rows,
|
| 178 |
+
"engine": "CRAFT + PP-OCRv6 medium (CPU)",
|
| 179 |
+
}
|
| 180 |
+
document["detection_id"] = hashlib.sha256(
|
| 181 |
+
json.dumps(document, sort_keys=True, ensure_ascii=False).encode()
|
| 182 |
+
).hexdigest()
|
| 183 |
+
return document
|
requirements.txt
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.8.0
|
| 2 |
+
torchvision==0.23.0
|
| 3 |
+
numpy==2.2.6
|
| 4 |
+
Pillow>=11.3.0
|
| 5 |
+
opencv-python-headless==5.0.0.93
|
| 6 |
+
safetensors>=0.4.5
|
| 7 |
+
easyocr==1.7.2
|
| 8 |
+
onnxruntime>=1.23.2,<2
|
| 9 |
+
PyYAML>=6.0.2
|
| 10 |
+
fastapi==0.162.0
|
| 11 |
+
uvicorn==0.54.0
|
| 12 |
+
python-multipart==0.0.32
|
| 13 |
+
pydantic==2.14.1
|
| 14 |
+
huggingface-hub>=1.16.0,<2
|
| 15 |
+
gradio==6.30.0
|
| 16 |
+
spaces==0.51.3
|
space.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hugging Face entry point: custom studio UI, Gradio queue, free ZeroGPU."""
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
os.environ["PIXTEXT_GRADIO"] = "1"
|
| 6 |
+
os.environ.setdefault("HF_HUB_DISABLE_TELEMETRY", "1")
|
| 7 |
+
|
| 8 |
+
# Import before torch so ZeroGPU can enable its CUDA staging mode.
|
| 9 |
+
import spaces
|
| 10 |
+
import gradio as gr
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
import time
|
| 14 |
+
import uuid
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import app as studio
|
| 18 |
+
|
| 19 |
+
from zerogpu_attention import enable_sdpa
|
| 20 |
+
|
| 21 |
+
enable_sdpa()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def load_models():
|
| 25 |
+
import torch
|
| 26 |
+
from pixtext import PixTextPipeline
|
| 27 |
+
from huggingface_hub import snapshot_download
|
| 28 |
+
|
| 29 |
+
torch.set_num_threads(4)
|
| 30 |
+
if not torch.cuda.is_available() and not spaces.config.Config.zero_gpu:
|
| 31 |
+
return {}
|
| 32 |
+
pipelines = {}
|
| 33 |
+
for variant, name in (("meanflow", "PixText-MeanFlow"), ("teacher", "PixText-Teacher")):
|
| 34 |
+
if os.environ.get("PIXTEXT_MODEL_ROOT"):
|
| 35 |
+
package = Path(os.environ["PIXTEXT_MODEL_ROOT"]) / name
|
| 36 |
+
else:
|
| 37 |
+
package = Path(snapshot_download("ATH-MaaS/PixText", allow_patterns=[f"models/{name}/*"])) / "models" / name
|
| 38 |
+
pipeline = PixTextPipeline.from_pretrained(package, device="cpu", dtype=torch.bfloat16)
|
| 39 |
+
pipeline.model = pipeline.model.to("cuda")
|
| 40 |
+
pipeline.device = torch.device("cuda")
|
| 41 |
+
pipelines[variant] = pipeline
|
| 42 |
+
return pipelines
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
# Stage both models before serving requests, as required by ZeroGPU.
|
| 46 |
+
PIPELINES = load_models()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@spaces.GPU(duration=120)
|
| 50 |
+
def gpu_refine(directory: str, size: list[int], jid: str, payload: str):
|
| 51 |
+
started = time.perf_counter()
|
| 52 |
+
request = studio.RefineRequest.model_validate_json(payload)
|
| 53 |
+
studio.PIPELINE = PIPELINES.get(request.variant)
|
| 54 |
+
studio.PIPELINE_VARIANT = request.variant if studio.PIPELINE is not None else None
|
| 55 |
+
progress = gr.Progress()
|
| 56 |
+
|
| 57 |
+
def report(**values):
|
| 58 |
+
progress(values.get("progress", 0), desc=values.get("message", "Refining"))
|
| 59 |
+
|
| 60 |
+
result = studio.refine({"directory": Path(directory), "size": size}, jid, request, report)
|
| 61 |
+
result["elapsed"] = round(time.perf_counter() - started, 2)
|
| 62 |
+
return result
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@studio.app.api(name="refine_image", concurrency_limit=1, concurrency_id="pixtext-gpu")
|
| 66 |
+
def refine_image(sid: str, payload: str) -> dict:
|
| 67 |
+
request = studio.RefineRequest.model_validate_json(payload)
|
| 68 |
+
session = studio.validate_refine(sid, request)
|
| 69 |
+
canonical = request.model_dump_json()
|
| 70 |
+
key = hashlib.sha256(canonical.encode()).hexdigest()
|
| 71 |
+
with studio.LOCK:
|
| 72 |
+
previous = session.get("last_gradio_result")
|
| 73 |
+
if previous and previous["key"] == key:
|
| 74 |
+
job = studio.JOBS.get(previous["jid"])
|
| 75 |
+
if job and job["status"] == "done":
|
| 76 |
+
return {"job_id": job["id"], "result": job["result"]}
|
| 77 |
+
jid = uuid.uuid4().hex
|
| 78 |
+
studio.JOBS[jid] = {"id": jid, "session": sid, "kind": "refine", "status": "running",
|
| 79 |
+
"progress": 0, "message": "Waiting for GPU", "created": time.time()}
|
| 80 |
+
session["job"] = jid
|
| 81 |
+
try:
|
| 82 |
+
result = gpu_refine(str(session["directory"]), list(session["size"]), jid, canonical)
|
| 83 |
+
studio.update_job(jid, status="done", progress=1, message="Complete", result=result)
|
| 84 |
+
session["last_gradio_result"] = {"key": key, "jid": jid}
|
| 85 |
+
return {"job_id": jid, "result": result}
|
| 86 |
+
except Exception:
|
| 87 |
+
studio.update_job(jid, status="error", message="Refinement could not finish. Please retry.")
|
| 88 |
+
raise
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
studio.app.launch(server_name=os.environ.get("GRADIO_SERVER_NAME", "0.0.0.0"),
|
| 93 |
+
server_port=int(os.environ.get("PIXTEXT_PORT", "7860")), show_error=False)
|
zerogpu_attention.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Use PyTorch SDPA with PixText's original token routing, without runtime compilation.
|
| 2 |
+
|
| 3 |
+
ZeroGPU does not support torch.compile. Only the attention execution changes;
|
| 4 |
+
the dense routing mask comes from the same function as PixText's reference mask.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def enable_sdpa():
|
| 14 |
+
from pixtext.modeling import attention, transformer
|
| 15 |
+
|
| 16 |
+
def forward(self, tokens, position_ids, block_mask, rotary_factors=None):
|
| 17 |
+
count = tokens.shape[0]
|
| 18 |
+
if block_mask.dtype != torch.bool or block_mask.shape != (count, count):
|
| 19 |
+
raise ValueError("Attention routing mask does not match the image tokens")
|
| 20 |
+
qkv = self.qkv(tokens).reshape(count, 3, self.num_heads, self.head_dim)
|
| 21 |
+
query, key, value = qkv.permute(1, 2, 0, 3).unbind(dim=0)
|
| 22 |
+
if rotary_factors is None:
|
| 23 |
+
rotary_factors = self.rotary.prepare(position_ids)
|
| 24 |
+
cosine, sine = rotary_factors
|
| 25 |
+
query = attention._normalize_and_apply_rotary(
|
| 26 |
+
query, self.q_norm.weight, self.q_norm.eps, cosine, sine
|
| 27 |
+
).unsqueeze(0)
|
| 28 |
+
key = attention._normalize_and_apply_rotary(
|
| 29 |
+
key, self.k_norm.weight, self.k_norm.eps, cosine, sine
|
| 30 |
+
).unsqueeze(0)
|
| 31 |
+
attended = F.scaled_dot_product_attention(
|
| 32 |
+
query, key, value.unsqueeze(0), attn_mask=block_mask[None, None], dropout_p=0.0
|
| 33 |
+
)
|
| 34 |
+
merged = attended.transpose(1, 2).reshape(count, self.hidden_size)
|
| 35 |
+
return self.proj_dropout(self.proj(merged))
|
| 36 |
+
|
| 37 |
+
attention.GroupSelfAttention.forward = forward
|
| 38 |
+
# Transformer imports this symbol directly, so replace its reference too.
|
| 39 |
+
transformer.build_flex_attention_block_mask = attention.build_dense_attention_mask
|