Abid Ali Awan commited on
Commit
c3159df
·
1 Parent(s): e94b4cf

Update README.md: Change emoji and color scheme, update app file path, and add server run instructions

Browse files
Files changed (5) hide show
  1. .gitignore +197 -0
  2. README.md +16 -5
  3. requirements.txt +1 -0
  4. src/app.py +160 -0
  5. tests/test_app.py +25 -0
.gitignore ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ #.idea/
169
+
170
+ # Abstra
171
+ # Abstra is an AI-powered process automation framework.
172
+ # Ignore directories containing user credentials, local state, and settings.
173
+ # Learn more at https://abstra.io/docs
174
+ .abstra/
175
+
176
+ # Visual Studio Code
177
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
178
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
179
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
180
+ # you could uncomment the following to ignore the enitre vscode folder
181
+ # .vscode/
182
+
183
+ # Ruff stuff:
184
+ .ruff_cache/
185
+
186
+ # PyPI configuration file
187
+ .pypirc
188
+
189
+ # Cursor
190
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
191
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
192
+ # refer to https://docs.cursor.com/context/ignore-files
193
+ .cursorignore
194
+ .cursorindexingignore
195
+
196
+ ./temp
197
+ .gradio
README.md CHANGED
@@ -1,14 +1,25 @@
1
  ---
2
  title: Universal File Converter
3
- emoji: 😻
4
- colorFrom: red
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 5.32.0
8
- app_file: app.py
9
  pinned: false
10
  license: apache-2.0
11
  short_description: Convert any file to any file format.
12
  ---
13
 
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: Universal File Converter
3
+ emoji: 🗃️
4
+ colorFrom: yellow
5
+ colorTo: green
6
  sdk: gradio
7
  sdk_version: 5.32.0
8
+ app_file: src/app.py
9
  pinned: false
10
  license: apache-2.0
11
  short_description: Convert any file to any file format.
12
  ---
13
 
14
+
15
+ To run the server use:
16
+
17
+ ```bash
18
+ uv run python src/app.py
19
+ ```
20
+
21
+ To test the server use:
22
+
23
+ ```bash
24
+ uv run python .\test\test_app.py
25
+ ```
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ convertapi>=2.0.0
src/app.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from urllib.parse import urlparse
4
+
5
+ import convertapi
6
+ import gradio as gr
7
+ from dotenv import load_dotenv
8
+
9
+ load_dotenv()
10
+ convertapi.api_credentials = os.getenv("CONVERTAPI_TOKEN")
11
+
12
+
13
+ # Function to convert a local file
14
+ def convert_local_file(local_file_path, output_format):
15
+ """
16
+ Convert a local document to a different format.
17
+
18
+ Args:
19
+ local_file_path (str): The path to the input file.
20
+ output_format (str): The format to convert the file to.
21
+
22
+ Returns:
23
+ str: The path to the converted file or an error message.
24
+ """
25
+ try:
26
+ if not local_file_path or not os.path.exists(local_file_path):
27
+ return "Invalid or non-existent local file path."
28
+
29
+ # Convert the local file
30
+ result = convertapi.convert(output_format, {"File": local_file_path})
31
+
32
+ # Derive filename from local path
33
+ input_filename = Path(local_file_path).stem
34
+
35
+ # Save the converted file to a temporary location
36
+ output_filename = f"{input_filename}.{output_format}"
37
+ output_path = Path("temp") / output_filename
38
+ output_path.parent.mkdir(exist_ok=True)
39
+
40
+ result.file.save(str(output_path))
41
+
42
+ # Return the file path string on success
43
+ return str(output_path)
44
+
45
+ except Exception as e:
46
+ return f"Error converting file: {str(e)}"
47
+
48
+
49
+ # Function to convert a file from a URL
50
+ def convert_from_url(document_url, output_format):
51
+ """
52
+ Convert a document from a URL to a different format.
53
+
54
+ Args:
55
+ document_url (str): The URL of the input file.
56
+ output_format (str): The format to convert the file to.
57
+
58
+ Returns:
59
+ str: The path to the converted file or an error message.
60
+ """
61
+ try:
62
+ if not document_url or not (
63
+ document_url.lower().startswith("http://")
64
+ or document_url.lower().startswith("https://")
65
+ ):
66
+ return "Invalid or unsupported URL format."
67
+
68
+ # Convert the file from a URL
69
+ result = convertapi.convert(output_format, {"File": document_url})
70
+
71
+ # Attempt to derive a filename from the URL for saving
72
+ try:
73
+ url_path = urlparse(document_url).path
74
+ input_filename = (
75
+ Path(url_path).stem or "converted_file"
76
+ ) # Fallback for complex URLs or no path
77
+ except Exception:
78
+ input_filename = "converted_file"
79
+
80
+ # Save the converted file to a temporary location
81
+ output_filename = f"{input_filename}.{output_format}"
82
+ output_path = Path("temp") / output_filename
83
+ output_path.parent.mkdir(exist_ok=True)
84
+
85
+ result.file.save(str(output_path))
86
+
87
+ # Return the file path string on success
88
+ return str(output_path)
89
+
90
+ except Exception as e:
91
+ return f"Error converting file from URL: {str(e)}"
92
+
93
+
94
+ # Create Gradio interfaces
95
+ local_file_demo = gr.Interface(
96
+ fn=convert_local_file,
97
+ inputs=[
98
+ gr.File(label="Upload File"),
99
+ gr.Dropdown(
100
+ choices=[
101
+ "docx",
102
+ "pdf",
103
+ "txt",
104
+ "png",
105
+ "jpg",
106
+ "jpeg",
107
+ "xlsx",
108
+ "pptx",
109
+ "html",
110
+ "rtf",
111
+ ],
112
+ label="Output Format",
113
+ value="pdf",
114
+ ),
115
+ ],
116
+ outputs=gr.File(label="Download Converted File"),
117
+ title="Local File Converter",
118
+ description="Convert documents from your local file system to different formats.",
119
+ )
120
+
121
+ url_demo = gr.Interface(
122
+ fn=convert_from_url,
123
+ inputs=[
124
+ gr.Textbox(
125
+ label="Document URL",
126
+ placeholder="Enter the URL of the document to convert (e.g., https://example.com/document.pdf)",
127
+ value="",
128
+ ),
129
+ gr.Dropdown(
130
+ choices=[
131
+ "docx",
132
+ "pdf",
133
+ "txt",
134
+ "png",
135
+ "jpg",
136
+ "jpeg",
137
+ "xlsx",
138
+ "pptx",
139
+ "html",
140
+ "rtf",
141
+ ],
142
+ label="Output Format",
143
+ value="pdf",
144
+ ),
145
+ ],
146
+ outputs=gr.File(label="Download Converted File"),
147
+ title="URL Document Converter",
148
+ description="Download and convert documents directly from URLs to different formats.",
149
+ )
150
+
151
+ # Create tabbed interface
152
+ demo = gr.TabbedInterface(
153
+ [local_file_demo, url_demo],
154
+ ["Local Files", "Online Files"],
155
+ title="Universal Document Converter",
156
+ )
157
+
158
+ if __name__ == "__main__":
159
+ # Launch without MCP server to avoid initialization issues
160
+ demo.launch(share=False, mcp_server=True, debug=True)
tests/test_app.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from gradio_client import Client
2
+
3
+ client = Client("http://127.0.0.1:7860/")
4
+ result_1 = client.predict(
5
+ local_file_path="data/test-document.pdf", output_format="docx", api_name="/predict"
6
+ )
7
+ print("Link to the document:", result_1)
8
+ assert (
9
+ isinstance(result_1, dict)
10
+ and result_1.get("output_file") is not None
11
+ and result_1.get("output_file").endswith(".docx")
12
+ )
13
+
14
+ result_2 = client.predict(
15
+ document_url="https://raw.githubusercontent.com/kingabzpro/bbc-news-class-mlops/refs/heads/master/README.md",
16
+ output_format="pdf",
17
+ api_name="/predict_1",
18
+ )
19
+
20
+ print("Link to the document:", result_2)
21
+ assert (
22
+ isinstance(result_2, dict)
23
+ and result_2.get("output_file") is not None
24
+ and result_2.get("output_file").endswith(".pdf")
25
+ )