likhonsheikhdev commited on
Commit
6f7e476
·
verified ·
1 Parent(s): df9c750

Create app py

Browse files
Files changed (1) hide show
  1. app py +147 -0
app py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from safetensors.torch import save_file as torch_save_file
4
+ import tensorflow as tf
5
+ from safetensors.keras import save_model as keras_save_model
6
+ import os
7
+ import tempfile
8
+
9
+ def convert_to_safetensors(framework, model_file):
10
+ """
11
+ Convert uploaded model files to SafeTensors format
12
+ """
13
+ if not model_file:
14
+ return gr.Error("Please upload a model file.")
15
+
16
+ # Create a temporary output file
17
+ output_filename = "model.safetensors"
18
+
19
+ try:
20
+ if framework == "PyTorch":
21
+ # Load PyTorch model weights safely
22
+ state_dict = torch.load(
23
+ model_file,
24
+ map_location='cpu',
25
+ weights_only=True
26
+ )
27
+
28
+ # Handle case where full model is loaded instead of just state_dict
29
+ if hasattr(state_dict, 'state_dict'):
30
+ state_dict = state_dict.state_dict()
31
+ elif isinstance(state_dict, torch.nn.Module):
32
+ state_dict = state_dict.state_dict()
33
+
34
+ # Save to SafeTensors format
35
+ torch_save_file(state_dict, output_filename)
36
+
37
+ return output_filename
38
+
39
+ elif framework == "TensorFlow":
40
+ # Load TensorFlow/Keras model
41
+ model = tf.keras.models.load_model(model_file)
42
+
43
+ # Save to SafeTensors format
44
+ keras_save_model(model, output_filename)
45
+
46
+ return output_filename
47
+
48
+ else:
49
+ return gr.Error("Please select a valid framework (PyTorch or TensorFlow).")
50
+
51
+ except Exception as e:
52
+ error_msg = f"{framework} Conversion Error: {str(e)}"
53
+
54
+ if framework == "PyTorch":
55
+ error_msg += "\n\nTips:\n• Ensure the file is a valid PyTorch model (.pt, .pth)\n• Model should contain state_dict or be loadable with torch.load()"
56
+ elif framework == "TensorFlow":
57
+ error_msg += "\n\nTips:\n• Ensure the file is a valid TensorFlow model (.h5, SavedModel)\n• For SavedModel format, upload as a zip file containing the model directory"
58
+
59
+ return gr.Error(error_msg)
60
+
61
+ # Create the Gradio interface
62
+ with gr.Blocks(
63
+ title="SafeTensors Model Converter",
64
+ theme=gr.themes.Soft()
65
+ ) as iface:
66
+
67
+ gr.Markdown("""
68
+ # 🔒 No-Code SafeTensors Model Creator
69
+
70
+ Convert your machine learning models to the secure **SafeTensors** format with zero coding required!
71
+
72
+ ## Why SafeTensors?
73
+ - **Security**: Prevents arbitrary code execution during model loading
74
+ - **Speed**: Faster loading times compared to pickle-based formats
75
+ - **Memory Efficiency**: Zero-copy deserialization
76
+ - **Cross-Platform**: Works across different ML frameworks
77
+
78
+ ## Supported Formats
79
+ - **PyTorch**: `.pt`, `.pth` files containing model weights
80
+ - **TensorFlow**: `.h5` files or SavedModel directories (as zip)
81
+ """)
82
+
83
+ with gr.Row():
84
+ with gr.Column():
85
+ framework_dropdown = gr.Dropdown(
86
+ choices=["PyTorch", "TensorFlow"],
87
+ label="🔧 Select Framework",
88
+ info="Choose the framework your model was trained with",
89
+ value="PyTorch"
90
+ )
91
+
92
+ model_upload = gr.File(
93
+ label="📁 Upload Model File",
94
+ file_types=[".pt", ".pth", ".h5", ".zip"],
95
+ info="Upload your model file (.pt/.pth for PyTorch, .h5 for TensorFlow)"
96
+ )
97
+
98
+ convert_btn = gr.Button(
99
+ "🚀 Convert to SafeTensors",
100
+ variant="primary",
101
+ size="lg"
102
+ )
103
+
104
+ with gr.Column():
105
+ output_file = gr.File(
106
+ label="💾 Download SafeTensors File",
107
+ info="Your converted model will appear here"
108
+ )
109
+
110
+ gr.Markdown("""
111
+ ### 📋 Usage Instructions
112
+ 1. **Select Framework**: Choose PyTorch or TensorFlow
113
+ 2. **Upload Model**: Select your model file from your computer
114
+ 3. **Convert**: Click the convert button
115
+ 4. **Download**: Get your secure SafeTensors file
116
+
117
+ ### ⚠️ Important Notes
118
+ - Only model weights are converted (no training code)
119
+ - Original model architecture code is still needed for inference
120
+ - Conversion preserves all tensor data and metadata
121
+ """)
122
+
123
+ # Set up the conversion event
124
+ convert_btn.click(
125
+ fn=convert_to_safetensors,
126
+ inputs=[framework_dropdown, model_upload],
127
+ outputs=output_file,
128
+ show_progress=True
129
+ )
130
+
131
+ gr.Markdown("""
132
+ ---
133
+
134
+ ### 🛡️ Security Benefits
135
+ SafeTensors format eliminates security risks associated with pickle-based model formats by:
136
+ - Storing only tensor data (no executable code)
137
+ - Using a simple, well-defined file format
138
+ - Enabling safe model sharing and deployment
139
+
140
+ ### 🔗 Learn More
141
+ - [SafeTensors Documentation](https://huggingface.co/docs/safetensors)
142
+ - [Hugging Face Model Hub](https://huggingface.co/models)
143
+ """)
144
+
145
+ # For Hugging Face Spaces deployment
146
+ if __name__ == "__main__":
147
+ iface.launch()