haydso commited on
Commit
8eef780
·
1 Parent(s): 5517c02

added files

Browse files
Files changed (7) hide show
  1. .gitignore +1 -0
  2. Dockerfile +31 -0
  3. README.md +72 -10
  4. app.py +609 -0
  5. docker-compose.yml +7 -0
  6. license.txt +201 -0
  7. requirements.txt +8 -0
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .env
Dockerfile ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ ENV PORT=8501
4
+
5
+ RUN apt-get update && apt-get install -y --no-install-recommends \
6
+ git \
7
+ git-lfs \
8
+ cmake \
9
+ build-essential \
10
+ curl \
11
+ && rm -rf /var/lib/apt/lists/* \
12
+ && git lfs install
13
+
14
+ WORKDIR /app
15
+
16
+ ARG TRANSFORMERS_JS_VERSION=3.8.1
17
+ RUN curl -L "https://github.com/huggingface/transformers.js/archive/refs/tags/${TRANSFORMERS_JS_VERSION}.tar.gz" -o transformers.tar.gz \
18
+ && tar -xzf transformers.tar.gz \
19
+ && mv "transformers.js-${TRANSFORMERS_JS_VERSION}" transformers.js \
20
+ && pip install --no-cache-dir -r "transformers.js/scripts/requirements.txt" \
21
+ && rm -rf transformers.tar.gz
22
+
23
+ COPY requirements.txt ./
24
+ RUN pip install --no-cache-dir -U pip \
25
+ && pip install --no-cache-dir -r requirements.txt
26
+
27
+ COPY . .
28
+
29
+ EXPOSE $PORT
30
+
31
+ CMD ["sh", "-c", "streamlit run app.py --server.port $PORT --server.address 0.0.0.0"]
README.md CHANGED
@@ -1,13 +1,75 @@
1
  ---
2
- title: Convert Onnx V2
3
- emoji:
4
- colorFrom: red
5
- colorTo: green
6
- sdk: gradio
7
- sdk_version: 6.5.1
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Convert to ONNX
3
+ emoji:
4
+ colorFrom: indigo
5
+ colorTo: yellow
6
+ sdk: docker
7
+ app_port: 8501
8
+ pinned: true
9
+ license: apache-2.0
10
+ short_description: Convert a Hugging Face model to ONNX format
11
  ---
12
 
13
+ # Convert to ONNX
14
+
15
+ ## Overview
16
+
17
+ This project provides a Streamlit application that facilitates the conversion of Hugging Face models to ONNX format, downloading, converting, and uploading models to Hugging Face.
18
+
19
+ ## Docker Compose usage
20
+
21
+ ### 1. Prepare environment variables
22
+
23
+ Copy the provided template and fill in your Hugging Face write token:
24
+
25
+ ```bash
26
+ cp .env.example .env
27
+ ```
28
+
29
+ ### 2. Start the application
30
+
31
+ ```bash
32
+ docker compose up
33
+ ```
34
+
35
+ Access the interface at `http://localhost:8501`.
36
+
37
+ Enter a Hugging Face model ID (e.g., `EleutherAI/pythia-14m`).
38
+
39
+ After a successful conversion, the ONNX export is available under `{username}/{model-name}-ONNX` unless you opt into reusing the same repository.
40
+
41
+ To stop the service, press `Ctrl+C` (or run `docker compose down`). Add `-d` to run detached.
42
+
43
+ ## Direct Docker usage (optional)
44
+
45
+ If you prefer not to use Docker Compose, you can still build and run manually:
46
+
47
+ ```bash
48
+ docker build -t convert-to-onnx .
49
+
50
+ docker run --rm \
51
+ -p 8501:8501 \
52
+ -e HF_TOKEN="your_write_token" \
53
+ convert-to-onnx
54
+ ```
55
+
56
+ ## Development
57
+
58
+ ### Contributing
59
+
60
+ 1. Fork the repository
61
+ 2. Create a feature branch
62
+ 3. Implement changes with tests
63
+ 4. Submit a pull request
64
+
65
+ ## Troubleshooting
66
+
67
+ Common issues and solutions:
68
+
69
+ - **Authentication Errors**: Verify your Hugging Face credentials
70
+ - **Conversion Failures**: Check model compatibility and available disk space
71
+ - **Upload Issues**: Ensure stable internet connection and valid permissions
72
+
73
+ ## License
74
+
75
+ [Apache 2.0 License](license.txt)
app.py ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert Hugging Face models to ONNX format.
2
+
3
+ This application provides a Streamlit interface for converting Hugging Face models
4
+ to ONNX format using the Transformers.js conversion scripts. It handles:
5
+ - Model conversion with optional trust_remote_code and output_attentions
6
+ - Automatic task inference with fallback support
7
+ - README generation with merged metadata from the original model
8
+ - Upload to Hugging Face Hub
9
+ """
10
+
11
+ import logging
12
+ import os
13
+ import re
14
+ import shutil
15
+ import subprocess
16
+ import sys
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+ from typing import List, Optional, Tuple
20
+
21
+ import streamlit as st
22
+ import yaml
23
+ from huggingface_hub import HfApi, hf_hub_download, model_info, whoami
24
+
25
+ logging.basicConfig(level=logging.INFO)
26
+ logger = logging.getLogger(__name__)
27
+
28
+
29
+ @dataclass
30
+ class Config:
31
+ """Application configuration containing authentication and path settings.
32
+
33
+ Attributes:
34
+ hf_token: Hugging Face API token (user token takes precedence over system token)
35
+ hf_username: Hugging Face username associated with the token
36
+ is_using_user_token: True if using a user-provided token, False if using system token
37
+ hf_base_url: Base URL for Hugging Face Hub
38
+ repo_path: Path to the bundled transformers.js repository
39
+ """
40
+
41
+ hf_token: str
42
+ hf_username: str
43
+ is_using_user_token: bool
44
+ hf_base_url: str = "https://huggingface.co"
45
+ repo_path: Path = Path("./transformers.js")
46
+
47
+ @classmethod
48
+ def from_env(cls) -> "Config":
49
+ """Create configuration from environment variables and Streamlit session state.
50
+
51
+ Priority order for tokens:
52
+ 1. User-provided token from Streamlit session (st.session_state.user_hf_token)
53
+ 2. System token from environment variable (HF_TOKEN)
54
+
55
+ Returns:
56
+ Config: Initialized configuration object
57
+
58
+ Raises:
59
+ ValueError: If no valid token is available
60
+ """
61
+ system_token = os.getenv("HF_TOKEN")
62
+ user_token = st.session_state.get("user_hf_token")
63
+
64
+ # Determine username based on which token is being used
65
+ if user_token:
66
+ hf_username = whoami(token=user_token)["name"]
67
+ else:
68
+ hf_username = (
69
+ os.getenv("SPACE_AUTHOR_NAME") or whoami(token=system_token)["name"]
70
+ )
71
+
72
+ # User token takes precedence over system token
73
+ hf_token = user_token or system_token
74
+
75
+ if not hf_token:
76
+ raise ValueError(
77
+ "When the user token is not provided, the system token must be set."
78
+ )
79
+
80
+ return cls(
81
+ hf_token=hf_token,
82
+ hf_username=hf_username,
83
+ is_using_user_token=bool(user_token),
84
+ )
85
+
86
+
87
+ class ModelConverter:
88
+ """Handles model conversion to ONNX format and upload to Hugging Face Hub.
89
+
90
+ This class manages the entire conversion workflow:
91
+ 1. Fetching original model metadata and README
92
+ 2. Running the ONNX conversion subprocess
93
+ 3. Generating an enhanced README with merged metadata
94
+ 4. Uploading the converted model to Hugging Face Hub
95
+
96
+ Attributes:
97
+ config: Application configuration containing tokens and paths
98
+ api: Hugging Face API client for repository operations
99
+ """
100
+
101
+ def __init__(self, config: Config):
102
+ """Initialize the converter with configuration.
103
+
104
+ Args:
105
+ config: Application configuration object
106
+ """
107
+ self.config = config
108
+ self.api = HfApi(token=config.hf_token)
109
+
110
+ # ============================================================================
111
+ # README Processing Methods
112
+ # ============================================================================
113
+
114
+ def _fetch_original_readme(self, repo_id: str) -> str:
115
+ """Download the README from the original model repository.
116
+
117
+ Args:
118
+ repo_id: Hugging Face model repository ID (e.g., 'username/model-name')
119
+
120
+ Returns:
121
+ str: Content of the README file, or empty string if not found
122
+ """
123
+ try:
124
+ readme_path = hf_hub_download(
125
+ repo_id=repo_id, filename="README.md", token=self.config.hf_token
126
+ )
127
+ with open(readme_path, "r", encoding="utf-8", errors="ignore") as f:
128
+ return f.read()
129
+ except Exception:
130
+ # Silently fail if README doesn't exist or can't be downloaded
131
+ return ""
132
+
133
+ def _strip_yaml_frontmatter(self, text: str) -> str:
134
+ """Remove YAML frontmatter from text, returning only the body.
135
+
136
+ YAML frontmatter is delimited by '---' at the start and end.
137
+
138
+ Args:
139
+ text: Text that may contain YAML frontmatter
140
+
141
+ Returns:
142
+ str: Text with frontmatter removed, or original text if no frontmatter found
143
+ """
144
+ if not text:
145
+ return ""
146
+ if text.startswith("---"):
147
+ match = re.match(r"^---[\s\S]*?\n---\s*\n", text)
148
+ if match:
149
+ return text[match.end() :]
150
+ return text
151
+
152
+ def _extract_yaml_frontmatter(self, text: str) -> Tuple[dict, str]:
153
+ """Parse and extract YAML frontmatter from text.
154
+
155
+ Args:
156
+ text: Text that may contain YAML frontmatter
157
+
158
+ Returns:
159
+ Tuple containing:
160
+ - dict: Parsed YAML frontmatter as a dictionary (empty dict if none found)
161
+ - str: Remaining body text after the frontmatter
162
+ """
163
+ if not text or not text.startswith("---"):
164
+ return {}, text or ""
165
+
166
+ # Match YAML frontmatter pattern: ---\n...content...\n---\n
167
+ match = re.match(r"^---\s*\n([\s\S]*?)\n---\s*\n", text)
168
+ if not match:
169
+ return {}, text
170
+
171
+ frontmatter_text = match.group(1)
172
+ body = text[match.end() :]
173
+
174
+ # Parse YAML safely, returning empty dict on any error
175
+ try:
176
+ parsed_data = yaml.safe_load(frontmatter_text)
177
+ if not isinstance(parsed_data, dict):
178
+ parsed_data = {}
179
+ except Exception:
180
+ parsed_data = {}
181
+
182
+ return parsed_data, body
183
+
184
+ def _get_pipeline_docs_url(self, pipeline_tag: Optional[str]) -> str:
185
+ """Generate Transformers.js documentation URL for a given pipeline tag.
186
+
187
+ Args:
188
+ pipeline_tag: Hugging Face pipeline tag (e.g., 'text-generation')
189
+
190
+ Returns:
191
+ str: URL to the relevant Transformers.js pipeline documentation
192
+ """
193
+ base_url = "https://huggingface.co/docs/transformers.js/api/pipelines"
194
+
195
+ if not pipeline_tag:
196
+ return base_url
197
+
198
+ # Map Hugging Face pipeline tags to Transformers.js pipeline class names
199
+ pipeline_class_mapping = {
200
+ "text-classification": "TextClassificationPipeline",
201
+ "token-classification": "TokenClassificationPipeline",
202
+ "question-answering": "QuestionAnsweringPipeline",
203
+ "fill-mask": "FillMaskPipeline",
204
+ "text2text-generation": "Text2TextGenerationPipeline",
205
+ "summarization": "SummarizationPipeline",
206
+ "translation": "TranslationPipeline",
207
+ "text-generation": "TextGenerationPipeline",
208
+ "zero-shot-classification": "ZeroShotClassificationPipeline",
209
+ "feature-extraction": "FeatureExtractionPipeline",
210
+ "image-feature-extraction": "ImageFeatureExtractionPipeline",
211
+ "audio-classification": "AudioClassificationPipeline",
212
+ "zero-shot-audio-classification": "ZeroShotAudioClassificationPipeline",
213
+ "automatic-speech-recognition": "AutomaticSpeechRecognitionPipeline",
214
+ "image-to-text": "ImageToTextPipeline",
215
+ "image-classification": "ImageClassificationPipeline",
216
+ "image-segmentation": "ImageSegmentationPipeline",
217
+ "background-removal": "BackgroundRemovalPipeline",
218
+ "zero-shot-image-classification": "ZeroShotImageClassificationPipeline",
219
+ "object-detection": "ObjectDetectionPipeline",
220
+ "zero-shot-object-detection": "ZeroShotObjectDetectionPipeline",
221
+ "document-question-answering": "DocumentQuestionAnsweringPipeline",
222
+ "text-to-audio": "TextToAudioPipeline",
223
+ "image-to-image": "ImageToImagePipeline",
224
+ "depth-estimation": "DepthEstimationPipeline",
225
+ }
226
+
227
+ pipeline_class = pipeline_class_mapping.get(pipeline_tag)
228
+ if not pipeline_class:
229
+ return base_url
230
+
231
+ return f"{base_url}#module_pipelines.{pipeline_class}"
232
+
233
+ def _normalize_pipeline_tag(self, pipeline_tag: Optional[str]) -> Optional[str]:
234
+ """Normalize pipeline tag to match expected task names.
235
+
236
+ Some pipeline tags use abbreviations that need to be expanded
237
+ for the conversion script to recognize them.
238
+
239
+ Args:
240
+ pipeline_tag: Original pipeline tag from model metadata
241
+
242
+ Returns:
243
+ Optional[str]: Normalized task name, or None if input is None
244
+ """
245
+ if not pipeline_tag:
246
+ return None
247
+
248
+ # Map abbreviated tags to their full names
249
+ tag_synonyms = {
250
+ "vqa": "visual-question-answering",
251
+ }
252
+
253
+ return tag_synonyms.get(pipeline_tag, pipeline_tag)
254
+
255
+ # ============================================================================
256
+ # Model Conversion Methods
257
+ # ============================================================================
258
+
259
+ def setup_repository(self) -> None:
260
+ """Verify that the transformers.js repository exists.
261
+
262
+ Raises:
263
+ RuntimeError: If the repository is not found at the expected path
264
+ """
265
+ if not self.config.repo_path.exists():
266
+ raise RuntimeError(
267
+ f"Expected transformers.js repository at {self.config.repo_path} "
268
+ f"but it was not found."
269
+ )
270
+
271
+ def _run_conversion_subprocess(
272
+ self, input_model_id: str, extra_args: Optional[List[str]] = None
273
+ ) -> subprocess.CompletedProcess:
274
+ """Execute the ONNX conversion script as a subprocess.
275
+
276
+ Args:
277
+ input_model_id: Hugging Face model ID to convert
278
+ extra_args: Additional command-line arguments for the conversion script
279
+
280
+ Returns:
281
+ subprocess.CompletedProcess: Result of the subprocess execution
282
+ """
283
+ # Build the conversion command
284
+ command = [
285
+ sys.executable,
286
+ "-m",
287
+ "scripts.convert",
288
+ "--quantize",
289
+ "--model_id",
290
+ input_model_id,
291
+ ]
292
+
293
+ if extra_args:
294
+ command.extend(extra_args)
295
+
296
+ # Run conversion in the transformers.js repository directory
297
+ return subprocess.run(
298
+ command,
299
+ cwd=self.config.repo_path,
300
+ capture_output=True,
301
+ text=True,
302
+ env={
303
+ "HF_TOKEN": self.config.hf_token,
304
+ },
305
+ )
306
+
307
+ def convert_model(
308
+ self,
309
+ input_model_id: str,
310
+ trust_remote_code: bool = False,
311
+ output_attentions: bool = False,
312
+ enable_task_inference: bool = True,
313
+ ) -> Tuple[bool, Optional[str]]:
314
+ """Convert a Hugging Face model to ONNX format.
315
+
316
+ Args:
317
+ input_model_id: Hugging Face model repository ID
318
+ trust_remote_code: Whether to trust and execute remote code from the model
319
+ output_attentions: Whether to output attention weights (required for some tasks)
320
+ enable_task_inference: Whether to pass the task argument to the conversion script based on the model's pipeline tag
321
+
322
+ Returns:
323
+ Tuple containing:
324
+ - bool: True if conversion succeeded, False otherwise
325
+ - Optional[str]: Error message if failed, or conversion log if succeeded
326
+ """
327
+ try:
328
+ conversion_args: List[str] = []
329
+
330
+ # Handle trust_remote_code option (requires user token for security)
331
+ if trust_remote_code:
332
+ if not self.config.is_using_user_token:
333
+ raise Exception(
334
+ "Trust Remote Code requires your own HuggingFace token."
335
+ )
336
+ conversion_args.append("--trust_remote_code")
337
+
338
+ # Handle output_attentions option (needed for word-level timestamps in Whisper)
339
+ if output_attentions:
340
+ conversion_args.append("--output_attentions")
341
+
342
+ if enable_task_inference:
343
+ try:
344
+ info = model_info(
345
+ repo_id=input_model_id, token=self.config.hf_token
346
+ )
347
+ pipeline_tag = getattr(info, "pipeline_tag", None)
348
+ task = self._normalize_pipeline_tag(pipeline_tag)
349
+ if task:
350
+ conversion_args.extend(["--task", task])
351
+ except Exception:
352
+ pass
353
+
354
+ # Run the conversion
355
+ result = self._run_conversion_subprocess(
356
+ input_model_id, extra_args=conversion_args or None
357
+ )
358
+
359
+ # Check if conversion succeeded
360
+ if result.returncode != 0:
361
+ return False, result.stderr
362
+
363
+ return True, result.stderr
364
+
365
+ except Exception as e:
366
+ return False, str(e)
367
+
368
+ # ============================================================================
369
+ # Upload Methods
370
+ # ============================================================================
371
+
372
+ def upload_model(self, input_model_id: str, output_model_id: str) -> Optional[str]:
373
+ """Upload the converted ONNX model to Hugging Face Hub.
374
+
375
+ This method:
376
+ 1. Creates the target repository (if it doesn't exist)
377
+ 2. Generates an enhanced README with merged metadata
378
+ 3. Uploads all model files to the repository
379
+ 4. Cleans up local files after upload
380
+
381
+ Args:
382
+ input_model_id: Original model repository ID
383
+ output_model_id: Target repository ID for the ONNX model
384
+
385
+ Returns:
386
+ Optional[str]: Error message if upload failed, None if successful
387
+ """
388
+ model_folder_path = self.config.repo_path / "models" / input_model_id
389
+
390
+ try:
391
+ # Create the target repository (public by default)
392
+ self.api.create_repo(output_model_id, exist_ok=True, private=False)
393
+
394
+ # Generate and write the enhanced README
395
+ readme_path = model_folder_path / "README.md"
396
+ readme_content = self.generate_readme(input_model_id)
397
+ readme_path.write_text(readme_content, encoding="utf-8")
398
+
399
+ # Upload all files from the model folder
400
+ self.api.upload_folder(
401
+ folder_path=str(model_folder_path), repo_id=output_model_id
402
+ )
403
+
404
+ return None # Success
405
+
406
+ except Exception as e:
407
+ return str(e)
408
+ finally:
409
+ # Always clean up local files, even if upload failed
410
+ shutil.rmtree(model_folder_path, ignore_errors=True)
411
+
412
+ # ============================================================================
413
+ # README Generation Methods
414
+ # ============================================================================
415
+
416
+ def generate_readme(self, input_model_id: str) -> str:
417
+ """Generate an enhanced README for the ONNX model.
418
+
419
+ This method creates a README that:
420
+ 1. Merges metadata from the original model with ONNX-specific metadata
421
+ 2. Adds a description and link to the conversion space
422
+ 3. Includes usage instructions with links to Transformers.js docs
423
+ 4. Appends the original model's README content
424
+
425
+ Args:
426
+ input_model_id: Original model repository ID
427
+
428
+ Returns:
429
+ str: Complete README content in Markdown format with YAML frontmatter
430
+ """
431
+ # Fetch pipeline tag from model metadata (if available)
432
+ try:
433
+ info = model_info(repo_id=input_model_id, token=self.config.hf_token)
434
+ pipeline_tag = getattr(info, "pipeline_tag", None)
435
+ except Exception:
436
+ pipeline_tag = None
437
+
438
+ # Fetch and parse the original README
439
+ original_text = self._fetch_original_readme(input_model_id)
440
+ original_meta, original_body = self._extract_yaml_frontmatter(original_text)
441
+ original_body = (
442
+ original_body or self._strip_yaml_frontmatter(original_text)
443
+ ).strip()
444
+
445
+ # Merge original metadata with our ONNX-specific metadata (ours take precedence)
446
+ merged_meta = {}
447
+ if isinstance(original_meta, dict):
448
+ merged_meta.update(original_meta)
449
+ merged_meta["library_name"] = "transformers.js"
450
+ merged_meta["base_model"] = [input_model_id]
451
+ if pipeline_tag is not None:
452
+ merged_meta["pipeline_tag"] = pipeline_tag
453
+
454
+ # Generate YAML frontmatter
455
+ frontmatter_yaml = yaml.safe_dump(merged_meta, sort_keys=False).strip()
456
+ header = f"---\n{frontmatter_yaml}\n---\n\n"
457
+
458
+ # Build README sections
459
+ readme_sections: List[str] = []
460
+ readme_sections.append(header)
461
+
462
+ # Add title
463
+ model_name = input_model_id.split("/")[-1]
464
+ readme_sections.append(f"# {model_name} (ONNX)\n")
465
+
466
+ # Add description
467
+ readme_sections.append(
468
+ f"This is an ONNX version of [{input_model_id}](https://huggingface.co/{input_model_id}). "
469
+ "It was automatically converted and uploaded using "
470
+ "[this Hugging Face Space](https://huggingface.co/spaces/onnx-community/convert-to-onnx)."
471
+ )
472
+
473
+ # Add usage section with Transformers.js docs link
474
+ docs_url = self._get_pipeline_docs_url(pipeline_tag)
475
+ if docs_url:
476
+ readme_sections.append("\n## Usage with Transformers.js\n")
477
+ if pipeline_tag:
478
+ readme_sections.append(
479
+ f"See the pipeline documentation for `{pipeline_tag}`: {docs_url}"
480
+ )
481
+ else:
482
+ readme_sections.append(f"See the pipelines documentation: {docs_url}")
483
+
484
+ # Append original README content (if available)
485
+ if original_body:
486
+ readme_sections.append("\n---\n")
487
+ readme_sections.append(original_body)
488
+
489
+ return "\n\n".join(readme_sections) + "\n"
490
+
491
+
492
+ def main():
493
+ """Main application entry point for the Streamlit interface.
494
+
495
+ This function:
496
+ 1. Initializes configuration and converter
497
+ 2. Displays the UI for model input and options
498
+ 3. Handles the conversion workflow
499
+ 4. Shows progress and results to the user
500
+ """
501
+ st.write("## Convert a Hugging Face model to ONNX")
502
+
503
+ try:
504
+ # Initialize configuration and converter
505
+ config = Config.from_env()
506
+ converter = ModelConverter(config)
507
+ converter.setup_repository()
508
+
509
+ # Get model ID from user
510
+ input_model_id = st.text_input(
511
+ "Enter the Hugging Face model ID to convert. Example: `EleutherAI/pythia-14m`"
512
+ )
513
+
514
+ if not input_model_id:
515
+ return
516
+
517
+ # Optional: User token input
518
+ st.text_input(
519
+ "Optional: Your Hugging Face write token. Fill it if you want to upload the model under your account.",
520
+ type="password",
521
+ key="user_hf_token",
522
+ )
523
+
524
+ # Optional: Trust remote code toggle (requires user token)
525
+ trust_remote_code = st.toggle("Optional: Trust Remote Code.")
526
+ if trust_remote_code:
527
+ st.warning(
528
+ "This option should only be enabled for repositories you trust and in which you have read the code, as it will execute arbitrary code present in the model repository. When this option is enabled, you must use your own Hugging Face write token."
529
+ )
530
+
531
+ # Optional: Output attentions (for Whisper models)
532
+ output_attentions = False
533
+ if "whisper" in input_model_id.lower():
534
+ output_attentions = st.toggle(
535
+ "Whether to output attentions from the Whisper model. This is required for word-level (token) timestamps."
536
+ )
537
+
538
+ # Optional: Task inference toggle
539
+ enable_task_inference = st.toggle(
540
+ "Optional: Base the 'task' argument from the conversion script on the model's pipeline tag",
541
+ value=False,
542
+ help="This can make the conversion of some models work, but may cause issues for others. It's recommended to first try converting the model with this option disabled, and only enable it if the conversion fails.",
543
+ )
544
+
545
+ # Determine output repository
546
+ # If user owns the model, allow uploading to the same repo
547
+ if config.hf_username == input_model_id.split("/")[0]:
548
+ same_repo = st.checkbox(
549
+ "Upload the ONNX weights to the existing repository"
550
+ )
551
+ else:
552
+ same_repo = False
553
+
554
+ model_name = input_model_id.split("/")[-1]
555
+ output_model_id = f"{config.hf_username}/{model_name}"
556
+
557
+ # Add -ONNX suffix if creating a new repository
558
+ if not same_repo:
559
+ output_model_id += "-ONNX"
560
+
561
+ output_model_url = f"{config.hf_base_url}/{output_model_id}"
562
+
563
+ # Check if model already exists
564
+ if not same_repo and converter.api.repo_exists(output_model_id):
565
+ st.write("This model has already been converted! 🎉")
566
+ st.link_button(f"Go to {output_model_id}", output_model_url, type="primary")
567
+ return
568
+
569
+ # Show where the model will be uploaded
570
+ st.write("URL where the model will be converted and uploaded to:")
571
+ st.code(output_model_url, language="plaintext")
572
+
573
+ # Wait for user confirmation before proceeding
574
+ if not st.button(label="Proceed", type="primary"):
575
+ return
576
+
577
+ # Step 1: Convert the model to ONNX
578
+ with st.spinner("Converting model..."):
579
+ success, stderr = converter.convert_model(
580
+ input_model_id,
581
+ trust_remote_code=trust_remote_code,
582
+ output_attentions=output_attentions,
583
+ enable_task_inference=enable_task_inference,
584
+ )
585
+ if not success:
586
+ st.error(f"Conversion failed: {stderr}")
587
+ return
588
+
589
+ st.success("Conversion successful!")
590
+ st.code(stderr)
591
+
592
+ # Step 2: Upload the converted model to Hugging Face
593
+ with st.spinner("Uploading model..."):
594
+ error = converter.upload_model(input_model_id, output_model_id)
595
+ if error:
596
+ st.error(f"Upload failed: {error}")
597
+ return
598
+
599
+ st.success("Upload successful!")
600
+ st.write("You can now go and view the model on Hugging Face!")
601
+ st.link_button(f"Go to {output_model_id}", output_model_url, type="primary")
602
+
603
+ except Exception as e:
604
+ logger.exception("Application error")
605
+ st.error(f"An error occurred: {str(e)}")
606
+
607
+
608
+ if __name__ == "__main__":
609
+ main()
docker-compose.yml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ services:
2
+ app:
3
+ build: .
4
+ ports:
5
+ - "8501:8501"
6
+ environment:
7
+ - HF_TOKEN=${HF_TOKEN}
license.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ huggingface_hub==0.35.3
2
+ streamlit==1.50.0
3
+ PyYAML==6.0.2
4
+ onnxscript==0.5.4
5
+ onnxconverter_common==1.16.0
6
+ onnx_graphsurgeon==0.5.8
7
+ torch==2.5.1
8
+ torchtitan