Update app.py
Browse files
app.py
CHANGED
@@ -7,7 +7,7 @@ from pathlib import Path
|
|
7 |
from typing import Optional, Tuple
|
8 |
from urllib.request import urlopen, urlretrieve
|
9 |
|
10 |
-
import
|
11 |
from huggingface_hub import HfApi, whoami
|
12 |
|
13 |
logging.basicConfig(level=logging.INFO)
|
@@ -28,9 +28,10 @@ class Config:
|
|
28 |
repo_path: Path = Path("./transformers.js")
|
29 |
|
30 |
@classmethod
|
31 |
-
def from_env(cls
|
32 |
"""Create config from environment variables and secrets."""
|
33 |
-
system_token =
|
|
|
34 |
if user_token:
|
35 |
hf_username = whoami(token=user_token)["name"]
|
36 |
else:
|
@@ -118,22 +119,19 @@ class ModelConverter:
|
|
118 |
return False, str(e)
|
119 |
|
120 |
def upload_model(self, input_model_id: str) -> Optional[str]:
|
121 |
-
"""Upload the
|
122 |
try:
|
123 |
-
|
124 |
-
onnx_folder_path =
|
125 |
|
126 |
-
#
|
127 |
-
onnx_folder_path.
|
|
|
128 |
|
129 |
-
#
|
130 |
-
for file in model_folder_path.iterdir():
|
131 |
-
if file.is_file() and file.suffix == ".onnx":
|
132 |
-
file.rename(onnx_folder_path / file.name)
|
133 |
-
|
134 |
-
# Upload the onnx folder to the same model path
|
135 |
self.api.upload_folder(
|
136 |
-
folder_path=str(onnx_folder_path),
|
|
|
137 |
)
|
138 |
return None
|
139 |
except Exception as e:
|
@@ -141,48 +139,63 @@ class ModelConverter:
|
|
141 |
finally:
|
142 |
import shutil
|
143 |
|
144 |
-
|
|
|
|
|
145 |
|
|
|
|
|
|
|
146 |
|
147 |
-
def convert_and_upload_model(input_model_id: str, user_hf_token: str = None):
|
148 |
-
"""Function to handle model conversion and upload."""
|
149 |
try:
|
150 |
-
config = Config.from_env(
|
151 |
converter = ModelConverter(config)
|
152 |
converter.setup_repository()
|
153 |
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
success, stderr = converter.convert_model(input_model_id)
|
158 |
-
if not success:
|
159 |
-
return f"Conversion failed: {stderr}"
|
160 |
|
161 |
-
|
162 |
-
|
163 |
-
if error:
|
164 |
-
return f"Upload failed: {error}"
|
165 |
|
166 |
-
|
167 |
-
|
168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
169 |
|
170 |
except Exception as e:
|
171 |
logger.exception("Application error")
|
172 |
-
|
173 |
-
|
174 |
|
175 |
-
# Gradio Interface
|
176 |
-
iface = gr.Interface(
|
177 |
-
fn=convert_and_upload_model,
|
178 |
-
inputs=[
|
179 |
-
gr.Textbox(label="Hugging Face Model ID", placeholder="Enter the Hugging Face model ID to convert. Example: `EleutherAI/pythia-14m`"),
|
180 |
-
gr.Textbox(label="Hugging Face Write Token (Optional)", type="password", placeholder="Fill it if you want to upload the model under your account.")
|
181 |
-
],
|
182 |
-
outputs=gr.Textbox(label="Output"),
|
183 |
-
title="Convert a Hugging Face model to ONNX",
|
184 |
-
description="This tool converts a Hugging Face model to ONNX format and uploads it to the same model path under an `onnx/` folder."
|
185 |
-
)
|
186 |
|
187 |
if __name__ == "__main__":
|
188 |
-
|
|
|
7 |
from typing import Optional, Tuple
|
8 |
from urllib.request import urlopen, urlretrieve
|
9 |
|
10 |
+
import streamlit as st
|
11 |
from huggingface_hub import HfApi, whoami
|
12 |
|
13 |
logging.basicConfig(level=logging.INFO)
|
|
|
28 |
repo_path: Path = Path("./transformers.js")
|
29 |
|
30 |
@classmethod
|
31 |
+
def from_env(cls) -> "Config":
|
32 |
"""Create config from environment variables and secrets."""
|
33 |
+
system_token = st.secrets.get("HF_TOKEN")
|
34 |
+
user_token = st.session_state.get("user_hf_token")
|
35 |
if user_token:
|
36 |
hf_username = whoami(token=user_token)["name"]
|
37 |
else:
|
|
|
119 |
return False, str(e)
|
120 |
|
121 |
def upload_model(self, input_model_id: str) -> Optional[str]:
|
122 |
+
"""Upload the ONNX folder to the same model path on Hugging Face."""
|
123 |
try:
|
124 |
+
# Define the ONNX folder path
|
125 |
+
onnx_folder_path = self.config.repo_path / "models" / input_model_id / "onnx"
|
126 |
|
127 |
+
# Ensure the ONNX folder exists
|
128 |
+
if not onnx_folder_path.exists():
|
129 |
+
return "ONNX folder not found. Conversion may have failed."
|
130 |
|
131 |
+
# Upload the ONNX folder to the same model path
|
|
|
|
|
|
|
|
|
|
|
132 |
self.api.upload_folder(
|
133 |
+
folder_path=str(onnx_folder_path),
|
134 |
+
repo_id=input_model_id
|
135 |
)
|
136 |
return None
|
137 |
except Exception as e:
|
|
|
139 |
finally:
|
140 |
import shutil
|
141 |
|
142 |
+
# Clean up the ONNX folder after upload
|
143 |
+
shutil.rmtree(onnx_folder_path, ignore_errors=True)
|
144 |
+
|
145 |
|
146 |
+
def main():
|
147 |
+
"""Main application entry point."""
|
148 |
+
st.write("## Convert a Hugging Face model to ONNX")
|
149 |
|
|
|
|
|
150 |
try:
|
151 |
+
config = Config.from_env()
|
152 |
converter = ModelConverter(config)
|
153 |
converter.setup_repository()
|
154 |
|
155 |
+
input_model_id = st.text_input(
|
156 |
+
"Enter the Hugging Face model ID to convert. Example: `EleutherAI/pythia-14m`"
|
157 |
+
)
|
|
|
|
|
|
|
158 |
|
159 |
+
if not input_model_id:
|
160 |
+
return
|
|
|
|
|
161 |
|
162 |
+
st.text_input(
|
163 |
+
f"Optional: Your Hugging Face write token. Fill it if you want to upload the model under your account.",
|
164 |
+
type="password",
|
165 |
+
key="user_hf_token",
|
166 |
+
)
|
167 |
+
|
168 |
+
output_model_url = f"{config.hf_base_url}/{input_model_id}"
|
169 |
+
|
170 |
+
st.write(f"URL where the ONNX folder will be uploaded:")
|
171 |
+
st.code(output_model_url, language="plaintext")
|
172 |
+
|
173 |
+
if not st.button(label="Proceed", type="primary"):
|
174 |
+
return
|
175 |
+
|
176 |
+
with st.spinner("Converting model..."):
|
177 |
+
success, stderr = converter.convert_model(input_model_id)
|
178 |
+
if not success:
|
179 |
+
st.error(f"Conversion failed: {stderr}")
|
180 |
+
return
|
181 |
+
|
182 |
+
st.success("Conversion successful!")
|
183 |
+
st.code(stderr)
|
184 |
+
|
185 |
+
with st.spinner("Uploading ONNX folder..."):
|
186 |
+
error = converter.upload_model(input_model_id)
|
187 |
+
if error:
|
188 |
+
st.error(f"Upload failed: {error}")
|
189 |
+
return
|
190 |
+
|
191 |
+
st.success("Upload successful!")
|
192 |
+
st.write("The ONNX folder has been uploaded to the existing model on Hugging Face!")
|
193 |
+
st.link_button(f"Go to {input_model_id}", output_model_url, type="primary")
|
194 |
|
195 |
except Exception as e:
|
196 |
logger.exception("Application error")
|
197 |
+
st.error(f"An error occurred: {str(e)}")
|
|
|
198 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
199 |
|
200 |
if __name__ == "__main__":
|
201 |
+
main()
|