rahul7star commited on
Commit
34b694d
Β·
verified Β·
1 Parent(s): 08aff6a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -148
app.py CHANGED
@@ -1,164 +1,207 @@
1
  import os
2
  import subprocess
3
  import streamlit as st
4
- from huggingface_hub import snapshot_download, login, HfApi
5
 
6
- if "quantized_model_path" not in st.session_state:
7
- st.session_state.quantized_model_path = None
8
- if "upload_to_hf" not in st.session_state:
9
- st.session_state.upload_to_hf = False
10
 
11
- def check_directory_path(directory_name: str) -> str:
12
- if os.path.exists(directory_name):
13
- path = os.path.abspath(directory_name)
14
- return str(path)
15
 
 
 
 
16
 
 
17
 
18
- models_list=['rahul7star/Qwen3-4B-Thinking-2509-Genius-Coder-AI-Full']
19
- # Define quantization types
20
- QUANT_TYPES = ["Q2_K", "Q3_K_l", "Q3_K_M", "Q3_K_S", "Q4_0", "Q4_1", "Q4_K_M", "Q4_K_S", "Q5_0", "Q5_1", "Q5_K_M", "Q5_K_S", "Q6_K", "Q8_0", "BF16", "F16", "F32"]
 
 
 
21
 
22
- model_dir_path = check_directory_path("/app/llama.cpp")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  def download_model(hf_model_name, output_dir="/tmp/models"):
25
- """
26
- Downloads a Hugging Face model and saves it locally.
27
- """
28
- st.write(f"πŸ“₯ Downloading `{hf_model_name}` from Hugging Face...")
29
- os.makedirs(output_dir, exist_ok=True)
30
- snapshot_download(repo_id=hf_model_name, local_dir=output_dir, local_dir_use_symlinks=False)
31
- st.success("βœ… Model downloaded successfully!")
32
-
33
- def convert_to_gguf(model_dir, output_file):
34
- """
35
- Converts a Hugging Face model to GGUF format.
36
- """
37
- st.write(f"πŸ”„ Converting `{model_dir}` to GGUF format...")
38
- os.makedirs(os.path.dirname(output_file), exist_ok=True)
39
  cmd = [
40
- "python3", "/app/llama.cpp/convert_hf_to_gguf.py", model_dir,
41
- "--outfile", output_file
 
 
 
42
  ]
43
- process = subprocess.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
44
- if process.returncode == 0:
45
- st.success(f"βœ… Conversion complete: `{output_file}`")
46
- else:
47
- st.error(f"❌ Conversion failed: {process.stderr}")
48
-
49
- def quantize_llama(model_path, quantized_output_path, quant_type):
50
- """
51
- Quantizes a GGUF model.
52
- """
53
- st.write(f"⚑ Quantizing `{model_path}` with `{quant_type}` precision...")
54
- os.makedirs(os.path.dirname(quantized_output_path), exist_ok=True)
55
- quantize_path = "/app/llama.cpp/build/bin/llama-quantize"
56
-
57
  cmd = [
58
- "/app/llama.cpp/build/bin/llama-quantize",
59
- model_path,
60
- quantized_output_path,
61
  quant_type
62
  ]
63
-
64
- process = subprocess.run(cmd, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
65
-
66
- if process.returncode == 0:
67
- st.success(f"βœ… Quantized model saved at `{quantized_output_path}`")
68
- else:
69
- st.error(f"❌ Quantization failed: {process.stderr}")
70
-
71
- def automate_llama_quantization(hf_model_name, quant_type):
72
- """
73
- Orchestrates the entire quantization process.
74
- """
75
- output_dir = "/tmp/models"
76
- gguf_file = os.path.join(output_dir, f"{hf_model_name.replace('/', '_')}.gguf")
77
- quantized_file = gguf_file.replace(".gguf", f"-{quant_type}.gguf")
78
-
79
- progress_bar = st.progress(0)
80
-
81
- # Step 1: Download
82
- st.write("### Step 1: Downloading Model")
83
- download_model(hf_model_name, output_dir)
84
- progress_bar.progress(33)
85
-
86
- # Step 2: Convert to GGUF
87
- st.write("### Step 2: Converting Model to GGUF Format")
88
- convert_to_gguf(output_dir, gguf_file)
89
- progress_bar.progress(66)
90
-
91
- # Step 3: Quantize Model
92
- st.write("### Step 3: Quantizing Model")
93
- quantize_llama(gguf_file, quantized_file, quant_type.lower())
94
- progress_bar.progress(100)
95
-
96
- st.success(f"πŸŽ‰ All steps completed! Quantized model available at: `{quantized_file}`")
97
- return quantized_file
98
-
99
- def upload_to_huggingface(file_path, repo_id, token):
100
- """
101
- Uploads a file to Hugging Face Hub.
102
- """
103
- try:
104
- # Log in to Hugging Face
105
- login(token=token)
106
-
107
- # Initialize HfApi
108
- api = HfApi()
109
-
110
- # Create the repository if it doesn't exist
111
- api.create_repo(repo_id, exist_ok=True, repo_type="model")
112
-
113
- # Upload the file
114
- api.upload_file(
115
- path_or_fileobj=file_path,
116
- path_in_repo=os.path.basename(file_path),
117
- repo_id=repo_id,
118
- )
119
- st.success(f"βœ… File uploaded to Hugging Face: {repo_id}")
120
-
121
- # Reset session state and rerun
122
- st.session_state.quantized_model_path = None
123
- st.session_state.upload_to_hf = False
124
- st.rerun()
125
- except Exception as e:
126
- st.error(f"❌ Failed to upload file: {e}")
127
-
128
- st.title("πŸ¦™ LLaMA Model Quantization (llama.cpp)")
129
-
130
-
131
- selected_model = st.selectbox("Select the Hugging Face Model", models_list, index=None)
132
- hf_model_name = selected_model if selected_model else st.text_input("Enter Hugging Face Model (If not there in the above list)")
133
-
134
- quant_type = st.selectbox("Select Quantization Type", QUANT_TYPES)
135
- start_button = st.button("πŸš€ Start Quantization")
136
-
137
- if start_button:
138
- if hf_model_name and quant_type:
139
- with st.spinner("Processing..."):
140
- st.session_state.quantized_model_path = automate_llama_quantization(hf_model_name, quant_type)
141
- else:
142
- st.warning("Please select/enter the necessary fields.")
143
-
144
- if st.session_state.quantized_model_path:
145
- with open(st.session_state.quantized_model_path, "rb") as f:
146
- if st.download_button("⬇️ Download Quantized Model", f, file_name=os.path.basename(st.session_state.quantized_model_path)):
147
- st.session_state.quantized_model_path = None
148
- st.session_state.upload_to_hf = False
149
- st.rerun()
150
-
151
- # Checkbox for upload section
152
- st.session_state.upload_to_hf = st.checkbox("Upload to Hugging Face", value=st.session_state.upload_to_hf)
153
-
154
- if st.session_state.upload_to_hf:
155
- st.write("### Upload to Hugging Face")
156
- repo_id = st.text_input("Enter Hugging Face Repository ID (e.g., 'username/repo-name')")
157
- hf_token = st.text_input("Enter Hugging Face Token", type="password")
158
-
159
- if st.button("πŸ“€ Upload to Hugging Face"):
160
- if repo_id and hf_token:
161
- with st.spinner("Uploading..."):
162
- upload_to_huggingface(st.session_state.quantized_model_path, repo_id, hf_token)
163
- else:
164
- st.warning("Please provide a valid repository ID and Hugging Face token.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import subprocess
3
  import streamlit as st
4
+ from huggingface_hub import snapshot_download, HfApi
5
 
6
+ # ============================================================
7
+ # SESSION STATE
8
+ # ============================================================
 
9
 
10
+ if "quantized_models" not in st.session_state:
11
+ st.session_state.quantized_models = []
 
 
12
 
13
+ # ============================================================
14
+ # CONFIG
15
+ # ============================================================
16
 
17
+ MODELS_LIST = ['rahul7star/Qwen3-4B-Thinking-2509-Genius-Coder-AI-Full']
18
 
19
+ QUANT_TYPES = [
20
+ "Q2_K", "Q3_K_l", "Q3_K_M", "Q3_K_S",
21
+ "Q4_0", "Q4_1", "Q4_K_M", "Q4_K_S",
22
+ "Q5_0", "Q5_1", "Q5_K_M", "Q5_K_S",
23
+ "Q6_K", "Q8_0", "BF16", "F16", "F32"
24
+ ]
25
 
26
+ LLAMA_CPP_PATH = "/app/llama.cpp"
27
+ CONVERT_SCRIPT = f"{LLAMA_CPP_PATH}/convert_hf_to_gguf.py"
28
+ QUANTIZE_BIN = f"{LLAMA_CPP_PATH}/build/bin/llama-quantize"
29
+
30
+ # ============================================================
31
+ # UTILS
32
+ # ============================================================
33
+
34
+ def check_dependencies():
35
+ if not os.path.exists(CONVERT_SCRIPT):
36
+ st.error("❌ convert_hf_to_gguf.py not found")
37
+ st.stop()
38
+ if not os.path.exists(QUANTIZE_BIN):
39
+ st.error("❌ llama-quantize binary not found")
40
+ st.stop()
41
 
42
  def download_model(hf_model_name, output_dir="/tmp/models"):
43
+ st.write(f"πŸ“₯ Downloading `{hf_model_name}` ...")
44
+ model_path = snapshot_download(
45
+ repo_id=hf_model_name,
46
+ local_dir=output_dir,
47
+ local_dir_use_symlinks=False
48
+ )
49
+ st.success("βœ… Model downloaded")
50
+ return model_path
51
+
52
+ def convert_to_gguf(model_path, output_file):
53
+ st.write("πŸ”„ Converting to GGUF...")
 
 
 
54
  cmd = [
55
+ "python3",
56
+ CONVERT_SCRIPT,
57
+ model_path,
58
+ "--outfile",
59
+ output_file
60
  ]
61
+ result = subprocess.run(cmd, capture_output=True, text=True)
62
+ if result.returncode != 0:
63
+ st.error(result.stderr)
64
+ raise RuntimeError("Conversion failed")
65
+ st.success("βœ… GGUF created")
66
+
67
+ def quantize_model(gguf_file, quant_type):
68
+ output_file = gguf_file.replace(".gguf", f"-{quant_type}.gguf")
69
+
70
+ st.write(f"⚑ Quantizing β†’ {quant_type}")
 
 
 
 
71
  cmd = [
72
+ QUANTIZE_BIN,
73
+ gguf_file,
74
+ output_file,
75
  quant_type
76
  ]
77
+
78
+ result = subprocess.run(cmd, capture_output=True, text=True)
79
+
80
+ if result.returncode != 0:
81
+ st.error(result.stderr)
82
+ return None
83
+
84
+ st.success(f"βœ… {quant_type} done")
85
+ return output_file
86
+
87
+ def upload_to_huggingface(file_path, repo_id):
88
+ hf_token = os.getenv("HF_TOKEN")
89
+
90
+ if not hf_token:
91
+ st.error("❌ HF_TOKEN not found in environment variables")
92
+ return
93
+
94
+ api = HfApi(token=hf_token)
95
+
96
+ api.create_repo(repo_id, exist_ok=True, repo_type="model")
97
+
98
+ api.upload_file(
99
+ path_or_fileobj=file_path,
100
+ path_in_repo=os.path.basename(file_path),
101
+ repo_id=repo_id,
102
+ )
103
+
104
+ st.success(f"πŸš€ Uploaded to https://huggingface.co/{repo_id}")
105
+
106
+ # ============================================================
107
+ # UI
108
+ # ============================================================
109
+
110
+ st.title("πŸ¦™ LLaMA.cpp Multi-Quantization Tool")
111
+
112
+ check_dependencies()
113
+
114
+ # Model selection
115
+ selected_model = st.selectbox(
116
+ "Select Hugging Face Model",
117
+ MODELS_LIST,
118
+ index=None
119
+ )
120
+
121
+ hf_model_name = selected_model or st.text_input(
122
+ "Or Enter Custom HF Model ID"
123
+ )
124
+
125
+ # Multi-checkbox quant selection
126
+ st.subheader("Select Quantization Types")
127
+
128
+ selected_quants = []
129
+ cols = st.columns(4)
130
+
131
+ for i, quant in enumerate(QUANT_TYPES):
132
+ with cols[i % 4]:
133
+ if st.checkbox(quant):
134
+ selected_quants.append(quant)
135
+
136
+ # Start button
137
+ if st.button("πŸš€ Start Quantization"):
138
+
139
+ if not hf_model_name:
140
+ st.warning("Please enter a model name")
141
+ st.stop()
142
+
143
+ if not selected_quants:
144
+ st.warning("Select at least one quant type")
145
+ st.stop()
146
+
147
+ with st.spinner("Processing..."):
148
+ try:
149
+ base_dir = "/tmp/models"
150
+ os.makedirs(base_dir, exist_ok=True)
151
+
152
+ model_path = download_model(hf_model_name, base_dir)
153
+
154
+ gguf_file = os.path.join(
155
+ base_dir,
156
+ hf_model_name.replace("/", "_") + ".gguf"
157
+ )
158
+
159
+ convert_to_gguf(model_path, gguf_file)
160
+
161
+ st.session_state.quantized_models = []
162
+
163
+ for quant in selected_quants:
164
+ quant_file = quantize_model(gguf_file, quant)
165
+ if quant_file:
166
+ st.session_state.quantized_models.append(quant_file)
167
+
168
+ st.success("πŸŽ‰ All quantizations completed")
169
+
170
+ except Exception as e:
171
+ st.error(f"❌ Error: {str(e)}")
172
+
173
+ # ============================================================
174
+ # DOWNLOAD + UPLOAD SECTION
175
+ # ============================================================
176
+
177
+ if st.session_state.quantized_models:
178
+
179
+ st.subheader("πŸ“¦ Generated Models")
180
+
181
+ for file_path in st.session_state.quantized_models:
182
+
183
+ with open(file_path, "rb") as f:
184
+ st.download_button(
185
+ label=f"⬇️ Download {os.path.basename(file_path)}",
186
+ data=f,
187
+ file_name=os.path.basename(file_path),
188
+ key=file_path
189
+ )
190
+
191
+ st.divider()
192
+
193
+ st.subheader("πŸš€ Upload to Hugging Face")
194
+
195
+ repo_id = st.text_input(
196
+ "Target Repository (e.g. username/model-quant)"
197
+ )
198
+
199
+ if st.button("πŸ“€ Upload All to HF"):
200
+ if not repo_id:
201
+ st.warning("Enter repository ID")
202
+ else:
203
+ with st.spinner("Uploading..."):
204
+ for file_path in st.session_state.quantized_models:
205
+ upload_to_huggingface(file_path, repo_id)
206
+
207
+ st.success("βœ… All files uploaded successfully")