george duan commited on
Commit
89019a3
1 Parent(s): c65f122

initial commits

Browse files
Files changed (10) hide show
  1. .dockerignore +164 -0
  2. .gitignore +165 -0
  3. Dockerfile +11 -0
  4. LICENSE +202 -0
  5. app.py +371 -0
  6. description.md +3 -0
  7. head.html +49 -0
  8. requirements.txt +19 -0
  9. static/icon.png +0 -0
  10. static/logo.png +0 -0
.dockerignore ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
163
+
164
+ gradio_cached_examples/
.gitignore ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
163
+
164
+ gradio_cached_examples/
165
+ .DS_Store
Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ RUN pip install uv
4
+ RUN uv venv
5
+
6
+ COPY requirements.txt .
7
+ RUN uv pip install -r requirements.txt
8
+
9
+ COPY . .
10
+
11
+ CMD .venv/bin/granian --interface asgi --port 8080 --host 0.0.0.0 app:app
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 describing the origin of the Work and
142
+ 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 2024 Stephan Fitzpatrick
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.
app.py ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import concurrent.futures as cf
2
+ import glob
3
+ import io
4
+ import os
5
+ import time
6
+ from pathlib import Path
7
+ from tempfile import NamedTemporaryFile
8
+ from typing import List, Literal
9
+ import requests
10
+
11
+ import gradio as gr
12
+ import sentry_sdk
13
+ from fastapi import FastAPI
14
+ from fastapi.staticfiles import StaticFiles
15
+ from loguru import logger
16
+ from openai import OpenAI
17
+ from promptic import llm
18
+ from pydantic import BaseModel, ValidationError
19
+ from pypdf import PdfReader
20
+ from tenacity import retry, retry_if_exception_type
21
+
22
+ import pdfplumber
23
+ import concurrent.futures
24
+ # from docx import Document
25
+ # from pptx import Presentation
26
+
27
+ from langchain_openai import ChatOpenAI
28
+ from langchain.chains.summarize import load_summarize_chain
29
+ from langchain.docstore.document import Document
30
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
31
+ from langchain_community.document_loaders.llmsherpa import LLMSherpaFileLoader
32
+ from langchain_community.document_loaders import WebBaseLoader
33
+
34
+
35
+ sentry_sdk.init(os.getenv("SENTRY_DSN"))
36
+
37
+ app = FastAPI()
38
+
39
+ app.mount("/static", StaticFiles(directory="static"), name="static")
40
+
41
+
42
+ class DialogueItem(BaseModel):
43
+ text: str
44
+ speaker: Literal["female-1", "male-1", "female-2"]
45
+
46
+ @property
47
+ def voice(self):
48
+ return {
49
+ "female-1": "nova",
50
+ "male-1": "onyx",
51
+ "female-2": "shimmer",
52
+ }[self.speaker]
53
+
54
+
55
+ class Dialogue(BaseModel):
56
+ scratchpad: str
57
+ dialogue: List[DialogueItem]
58
+
59
+
60
+ @retry(retry=retry_if_exception_type(ValidationError))
61
+ @llm(model="gpt-4o")
62
+ def generate_dialogue(text: str) -> Dialogue:
63
+ """
64
+ Your task is to take the input text provided and turn it into an engaging, informative podcast dialogue. The input text may be messy or unstructured, as it could come from a variety of sources like PDFs or web pages. Don't worry about the formatting issues or any irrelevant information; your goal is to extract the key points and interesting facts that could be fully discussed in a podcast.
65
+
66
+ Here is the input text you will be working with:
67
+
68
+ <input_text>
69
+ {text}
70
+ </input_text>
71
+
72
+ First, carefully read through the input text and identify the main topics, key points, and any interesting facts or anecdotes. Think about how you could present this information in a fun, engaging way that would be suitable for an audio podcast.
73
+
74
+ <scratchpad>
75
+ Brainstorm creative ways to discuss the main topics and key points you identified in the input text. Consider using analogies, storytelling techniques, or hypothetical scenarios to make the content more relatable and engaging for listeners.
76
+ Keep in mind that your podcast should be accessible to a general audience, so avoid using too much jargon or assuming prior knowledge of the topic. If necessary, think of ways to briefly explain any complex concepts in simple terms.
77
+
78
+ Use your imagination to fill in any gaps in the input text or to come up with thought-provoking questions that could be explored in the podcast. The goal is to create an informative and entertaining dialogue, so feel free to be creative in your approach.
79
+
80
+ Write your brainstorming ideas and a rough outline for the podcast dialogue here. Be sure to note the key insights and takeaways you want to reiterate at the end.
81
+ </scratchpad>
82
+
83
+ Now that you have brainstormed ideas and created a rough outline, it's time to write the actual podcast dialogue. Aim for a natural, conversational flow between the host and any guest speakers. Incorporate the best ideas from your brainstorming session and make sure to explain any complex topics in an easy-to-understand way.
84
+
85
+ <podcast_dialogue>
86
+ Write your engaging, informative podcast dialogue here, based on the key points and creative ideas you came up with during the brainstorming session. Use a conversational tone and include any necessary context or explanations to make the content accessible to a general audience. Use made-up names for the hosts and guests to create a more engaging and immersive experience for listeners. Design your output to be read aloud -- it will be directly converted into audio.
87
+
88
+ Make the dialogue sound like a natural conversation between Taiwanese people. Use colloquial language zh-hant, cultural references, and a friendly tone that reflects how people in Taiwan typically speak to each other. Incorporate local phrases and expressions to make the conversation authentic and relatable.
89
+
90
+ Throughout the dialogue, sprinkle in new insights or interesting ideas that might arise naturally from the conversation. These could be personal anecdotes, hypothetical scenarios, or surprising facts that keep the listeners engaged.
91
+
92
+ Include emotional cues to make the conversation more engaging, such as laughter, excitement, or surprise.
93
+
94
+ Make the dialogue as long and detailed as possible, while still staying on topic and maintaining an engaging flow. Aim to use your full output capacity to create the longest podcast episode you can, while still communicating the key information from the input text in an entertaining way.
95
+
96
+ At the end of the dialogue, have the host and guest speakers naturally summarize the main insights and takeaways from their discussion. This should flow organically from the conversation, reiterating the key points in a casual, conversational manner. Avoid making it sound like an obvious recap - the goal is to reinforce the central ideas one last time before signing off.
97
+ </podcast_dialogue>
98
+ """
99
+
100
+
101
+ def get_mp3(text: str, voice: str, api_key: str = None) -> bytes:
102
+ client = OpenAI(
103
+ api_key=api_key or os.getenv("OPENAI_API_KEY"),
104
+ )
105
+
106
+ with client.audio.speech.with_streaming_response.create(
107
+ model="tts-1-hd",
108
+ voice=voice,
109
+ input=text,
110
+ ) as response:
111
+ with io.BytesIO() as file:
112
+ for chunk in response.iter_bytes():
113
+ file.write(chunk)
114
+ return file.getvalue()
115
+ # def get_ppt_text(filename):
116
+ # prs = Presentation(filename)
117
+ # full_text = []
118
+ # for slide in prs.slides:
119
+ # for shape in slide.shapes:
120
+ # if hasattr(shape, "text"):
121
+ # full_text.append(shape.text)
122
+ # return '\n'.join(full_text)
123
+
124
+
125
+ # def get_doc_text(filename):
126
+ # doc = Document(filename)
127
+ # full_text = [para.text for para in doc.paragraphs]
128
+ # return '\n'.join(full_text)
129
+
130
+
131
+ # def get_page_text(filename, page_num):
132
+ # with pdfplumber.open(filename) as pdf:
133
+ # page = pdf.pages[page_num]
134
+ # return page.extract_text()
135
+
136
+ # def summarize_page(i, text):
137
+ # prompt = """Summarize the text in a detailed and concise manner."""
138
+ # # text = get_page_text(filename, page_num)
139
+ # client = OpenAI()
140
+ # # Check if text extraction was successful
141
+ # if text:
142
+ # response = client.chat.completions.create(
143
+ # model="gpt-4o",
144
+ # temperature=0.1,
145
+ # messages=[
146
+ # {"role": "system", "content": prompt},
147
+ # {"role": "user", "content": text}
148
+ # ]
149
+ # )
150
+ # return i, response.choices[0].message.content
151
+ # else:
152
+ # return i, "No text found on this page."
153
+
154
+ # def summarize_large_text(texts):
155
+ # summary_parts = []
156
+ # num_pages = len(texts)
157
+ # with concurrent.futures.ThreadPoolExecutor() as executor:
158
+ # future_to_page = {executor.submit(summarize_page, i, texts[i]): i for i in range(num_pages)}
159
+ # for future in concurrent.futures.as_completed(future_to_page):
160
+ # i, page_summary = future.result()
161
+ # summary_parts.append((i, f"p{i+1}: {page_summary}"))
162
+
163
+ # # Sort the summary parts by page index and join them into a single string
164
+ # summary_parts.sort(key=lambda x: x[0])
165
+ # full_summary = "\n".join(part[1] for part in summary_parts)
166
+
167
+ # return full_summary
168
+
169
+ # def summarize_pdf_parallel(filename):
170
+ # with pdfplumber.open(filename) as pdf:
171
+ # num_pages = len(pdf.pages)
172
+ # texts = [get_page_text(filename, i) for i in range(num_pages)]
173
+
174
+ # all_text = "\n".join(texts)
175
+
176
+ # if len(all_text) > 70000:
177
+ # return summarize_large_text(texts)
178
+ # else:
179
+ # return all_text
180
+
181
+ # def summarize_file(filename):
182
+ # if filename.endswith(".pdf"):
183
+ # return summarize_pdf_parallel(filename)
184
+ # elif filename.endswith(".txt"):
185
+ # with open(filename, "r") as f:
186
+ # return f.read()
187
+ # elif filename.endswith(".docx"):
188
+ # return get_doc_text(filename)
189
+ # elif filename.endswith(".pptx"):
190
+ # return get_ppt_text(filename)
191
+ # else:
192
+ # raise ValueError("Unsupported file type")
193
+
194
+ def summarize_chunk(chunk_text: str) -> str:
195
+ llm = ChatOpenAI(temperature=0, model_name="gpt-4o")
196
+ document = Document(page_content=chunk_text)
197
+ summarize_chain = load_summarize_chain(llm=llm)
198
+ summary = summarize_chain.invoke([document])
199
+ return summary["output_text"]
200
+
201
+ # Function to read and extract text from a DOCX file
202
+ def get_doc_text(filename: str) -> str:
203
+ from docx import Document as DocxDocument
204
+ doc = DocxDocument(filename)
205
+ full_text = [para.text for para in doc.paragraphs]
206
+ return '\n'.join(full_text)
207
+
208
+ def get_pdf_text(filename: str) -> str:
209
+ full_text = []
210
+ with pdfplumber.open(filename) as pdf:
211
+ for page in pdf.pages:
212
+ text = page.extract_text()
213
+ if text:
214
+ full_text.append(text)
215
+ return '\n'.join(full_text)
216
+
217
+ # Function to split text into smaller chunks
218
+ def split_text(text: str, chunk_size: int = 1000, chunk_overlap: int = 200) -> List[str]:
219
+ text_splitter = RecursiveCharacterTextSplitter(
220
+ chunk_size=chunk_size,
221
+ chunk_overlap=chunk_overlap
222
+ )
223
+ chunks = text_splitter.split_text(text)
224
+ return chunks
225
+
226
+ # Function to summarize a large document with text splitting in parallel
227
+ def summarize_large_document(filename: str, chunk_size: int = 1000, chunk_overlap: int = 200) -> str:
228
+ if filename.endswith(".docx"):
229
+ text = get_doc_text(filename)
230
+ elif filename.endswith(".pdf"):
231
+ text = get_pdf_text(filename)
232
+ else:
233
+ raise ValueError("Unsupported file type")
234
+ chunks = split_text(text, chunk_size, chunk_overlap)
235
+
236
+ summaries = []
237
+ with concurrent.futures.ThreadPoolExecutor() as executor:
238
+ futures = {executor.submit(summarize_chunk, chunk): chunk for chunk in chunks}
239
+ for future in concurrent.futures.as_completed(futures):
240
+ summaries.append(future.result())
241
+
242
+ # Combine all summaries into one final summary
243
+ final_summary = "\n".join(summaries)
244
+ return final_summary
245
+
246
+
247
+ def summarize_with_sherpa(url: str) -> str:
248
+ response = requests.head(url)
249
+ content_type = response.headers.get('content-type')
250
+ allowed_types = [
251
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', # DOCX
252
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation', # PPTX
253
+ 'text/html', # HTML
254
+ 'text/plain', # TXT
255
+ 'application/xml', # XML
256
+ 'application/pdf', # PDF
257
+ ]
258
+ if content_type not in allowed_types:
259
+ loader = WebBaseLoader(url)
260
+ # print(content_type)
261
+ else:
262
+ loader = LLMSherpaFileLoader(
263
+ file_path=url,
264
+ new_indent_parser=True,
265
+ apply_ocr=True,
266
+ strategy="text",
267
+ llmsherpa_api_url="https://readers.llmsherpa.com/api/document/developer/parseDocument?renderFormat=all",
268
+ )
269
+ docs = loader.load()
270
+ return docs[0].page_content
271
+
272
+ def generate_audio(file=None, url=None, openai_api_key: str = None) -> bytes:
273
+
274
+ if not os.getenv("OPENAI_API_KEY", openai_api_key):
275
+ raise gr.Error("OpenAI API key is required")
276
+
277
+ text = ""
278
+ if file:
279
+ try:
280
+ text = summarize_large_document(file)
281
+ except ValueError as e:
282
+ raise gr.Error(str(e))
283
+ elif url:
284
+ try:
285
+ text = summarize_with_sherpa(url)
286
+ except Exception as e:
287
+ raise gr.Error(str(e))
288
+
289
+ print(text)
290
+
291
+ llm_output = generate_dialogue(text)
292
+
293
+ audio = b""
294
+ transcript = ""
295
+
296
+ characters = 0
297
+
298
+ with cf.ThreadPoolExecutor() as executor:
299
+ futures = []
300
+ for line in llm_output.dialogue:
301
+ transcript_line = f"{line.speaker}: {line.text}"
302
+ future = executor.submit(get_mp3, line.text, line.voice, openai_api_key)
303
+ futures.append((future, transcript_line))
304
+ characters += len(line.text)
305
+
306
+ for future, transcript_line in futures:
307
+ audio_chunk = future.result()
308
+ audio += audio_chunk
309
+ transcript += transcript_line + "\n\n"
310
+
311
+ logger.info(f"Generated {characters} characters of audio")
312
+
313
+ temporary_directory = "./gradio_cached_examples/tmp/"
314
+ os.makedirs(temporary_directory, exist_ok=True)
315
+
316
+ # we use a temporary file because Gradio's audio component doesn't work with raw bytes in Safari
317
+ temporary_file = NamedTemporaryFile(
318
+ dir=temporary_directory,
319
+ delete=False,
320
+ suffix=".mp3",
321
+ )
322
+ temporary_file.write(audio)
323
+ temporary_file.close()
324
+
325
+ # Delete any files in the temp directory that end with .mp3 and are over a day old
326
+ for file in glob.glob(f"{temporary_directory}*.mp3"):
327
+ if os.path.isfile(file) and time.time() - os.path.getmtime(file) > 24 * 60 * 60:
328
+ os.remove(file)
329
+
330
+ return temporary_file.name, transcript
331
+
332
+
333
+ demo = gr.Interface(
334
+ title="PDF to Podcast",
335
+ description=Path("description.md").read_text(),
336
+ fn=generate_audio,
337
+ examples=[],
338
+ inputs=[
339
+ gr.File(
340
+ label="PDF",
341
+ ),
342
+ gr.Textbox(
343
+ label="URL",
344
+ placeholder="Enter URL of a PDF, DOCX, or PPTX file",
345
+ ),
346
+ gr.Textbox(
347
+ label="OpenAI API Key",
348
+ visible=not os.getenv("OPENAI_API_KEY"),
349
+ ),
350
+ ],
351
+ outputs=[
352
+ gr.Audio(label="Audio", format="mp3"),
353
+ gr.Textbox(label="Transcript"),
354
+ ],
355
+ allow_flagging=False,
356
+ clear_btn=None,
357
+ head=os.getenv("HEAD", "") + Path("head.html").read_text(),
358
+ cache_examples="lazy",
359
+ api_name=False,
360
+ )
361
+
362
+
363
+ demo = demo.queue(
364
+ max_size=20,
365
+ default_concurrency_limit=20,
366
+ )
367
+
368
+ app = gr.mount_gradio_app(app, demo, path="/")
369
+
370
+ if __name__ == "__main__":
371
+ demo.launch(show_api=False)
description.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ <p style="text-align:center">
2
+ <strong>Convert any PDF into a podcast episode! Experience research papers, websites, and more in a whole new way.</strong>
3
+ </p>
head.html ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!-- Primary Meta Tags -->
2
+ <title>PDF to Podcast - Convert Your Documents to Audio</title>
3
+ <meta name="title" content="PDF to Podcast - Convert Your Documents to Audio" />
4
+ <meta
5
+ name="description"
6
+ content="Easily convert your PDF documents into audio podcasts. Perfect for listening on the go and making content more accessible."
7
+ />
8
+
9
+ <!-- Open Graph / Facebook -->
10
+ <meta property="og:type" content="website" />
11
+ <meta property="og:url" content="https://pdf-to-podcast.com/" />
12
+ <meta
13
+ property="og:title"
14
+ content="PDF to Podcast - Convert Your Documents to Audio"
15
+ />
16
+ <meta
17
+ property="og:description"
18
+ content="Easily convert your PDF documents into audio podcasts. Perfect for listening on the go and making content more accessible."
19
+ />
20
+ <meta
21
+ property="og:image"
22
+ content="https://pdf-to-podcast.com/static/logo.png"
23
+ />
24
+
25
+ <!-- Twitter -->
26
+ <meta property="twitter:card" content="summary_large_image" />
27
+ <meta property="twitter:url" content="https://pdf-to-podcast.com/" />
28
+ <meta
29
+ property="twitter:title"
30
+ content="PDF to Podcast - Convert Your Documents to Audio"
31
+ />
32
+ <meta
33
+ property="twitter:description"
34
+ content="Easily convert your PDF documents into audio podcasts. Perfect for listening on the go and making content more accessible."
35
+ />
36
+ <meta
37
+ property="twitter:image"
38
+ content="https://pdf-to-podcast.com/static/logo.png"
39
+ />
40
+
41
+ <!-- Additional Meta Tags -->
42
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
43
+ <meta charset="UTF-8" />
44
+ <meta name="author" content="Stephan Fitzpatrick" />
45
+ <meta
46
+ name="keywords"
47
+ content="PDF to Podcast, PDF to audio, document to podcast, audio conversion, podcast creation, accessible content"
48
+ />
49
+ <link rel="icon" href="/static/icon.png" type="image/png" />
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio~=4.36
2
+ promptic==0.7.5
3
+ pydantic
4
+ google-generativeai
5
+ loguru~=0.7
6
+ pypdf~=4.1
7
+ tenacity~=8.3
8
+ sentry-sdk~=2.5
9
+ granian~=1.4
10
+ # PyPDF2
11
+ pdfplumber
12
+ openai
13
+ # docx
14
+ # python-pptx
15
+ llmsherpa
16
+ langchain_openai
17
+ langchain_community
18
+ langchain
19
+ bs4
static/icon.png ADDED
static/logo.png ADDED