Upload folder using huggingface_hub
Browse files19 unmodified lines2021222324252627282930313233343536373839404142434445464748495051523 unmodified lines5657585960616263641 unmodified line6667686970717273741 unmodified line767778798081824 unmodified lines87888990919293949596979827 unmodified lines1261271281291301311328 unmodified lines1411421431441451461479 unmodified lines15715815916016116216312 unmodified lines1761771781791801811821831841851864 unmodified lines19119219319419519619719819920020120220320420520620720819 unmodified linesOLLAMA_BIN = Path(IN_BIN)def start_ollama_daemon():print("⏳ Starting Ollama daemon in background...")env = os.environ.copy()subprocess.Popen([OLLAMA_BIN, "serve"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)def stop_ollama_daemon():print("⏳ Stopping Ollama daemon...")subprocess.Popen(["pkill", "ollama"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)def format_log(msg):return f"[{strftime('%H:%M:%S')}] {msg}"def push_to_ollama(gguf_path, ollama_repo, tag_suffix, api_key):"""Creates the modelfile and pushes to Ollama using OLLAMA_API_KEY env var."""ollama_tag = f"{ollama_repo}:{tag_suffix.lower()}"# Prepare Environment with API Keypush_env = os.environ.copy()if api_key:push_env["OLLAMA_API_KEY"] = api_key# 1. Write the Modelfile to diskmodelfile_path = gguf_path.parent / "Modelfile"with open(modelfile_path, "w") as f:f.write(f"FROM {gguf_path.resolve()}")3 unmodified linestry:# 2. Run 'ollama create' via CLIcreate_cmd = [OLLAMA_BIN, "create", ollama_tag, "-f", str(modelfile_path)]# We pass the env here too, just in case creation requires auth in your specific setupsubprocess.run(create_cmd, check=True, capture_output=True, env=push_env)# Clean up the temporary Modelfileif modelfile_path.exists():1 unmodified linelogs.append(format_log(f"⬆️ Pushing to registry: {ollama_tag}..."))# 3. Run 'ollama push' via CLI with the API Key in Envpush_cmd = [OLLAMA_BIN, "push", ollama_tag]push_result = subprocess.run(push_cmd, capture_output=True, text=True, env=push_env)if push_result.returncode == 0:logs.append(format_log(f"✅ Successfully pushed {ollama_tag}"))1 unmodified linelogs.append(format_log(f"❌ Push failed: {push_result.stderr}"))# Optional: Remove the local tag to save disk space in the containersubprocess.run([OLLAMA_BIN, "rm", ollama_tag], stdout=subprocess.DEVNULL, env=push_env)except subprocess.CalledProcessError as e:# Captures errors from the 'check=True' on create_cmd4 unmodified linesreturn logsdef run_conversion(hf_repo, ollama_repo, hf_token, ollama_api_key, include_bf16, progress=gr.Progress()):logs = []if not ollama_api_key:logs.append(format_log("⚠️ No OLLAMA_API_KEY provided. Push might fail if registry requires auth."))# We continue anyway, as some registries might be public/localwork_dir = Path("conversion_work_dir")download_dir = work_dir / "downloads"27 unmodified linesresult = subprocess.run(cmd, capture_output=True, text=True)if result.returncode == 0:logs.extend(push_to_ollama(bf16_path, ollama_repo, "bf16", ollama_api_key))os.remove(bf16_path)logs.append(format_log("🧹 Cleaned up BF16"))else:8 unmodified linescmd = ["python", str(CONVERT_SCRIPT), str(model_path), "--outtype", "f16", "--outfile", str(fp16_path)]subprocess.run(cmd, check=True, capture_output=True)logs.extend(push_to_ollama(fp16_path, ollama_repo, "f16", ollama_api_key))yield "\n".join(logs)# Quant Loop9 unmodified lineslogs.append(format_log(f"❌ Quantize failed: {q_result.stderr}"))continuelogs.extend(push_to_ollama(final_gguf, ollama_repo, quant, ollama_api_key))os.remove(final_gguf)logs.append(format_log(f"🧹 Cleaned up {quant}"))yield "\n".join(logs)12 unmodified linesyield "\n".join(logs)def run_pipeline(hf_repo, ollama_repo, hf_token, ollama_api_key, include_bf16, progress=gr.Progress()):print()start_ollama_daemon()# We yield from the generatorfor update in run_conversion(hf_repo, ollama_repo, hf_token, ollama_api_key, include_bf16, progress):yield updatestop_ollama_daemon()4 unmodified lineswith gr.Row():with gr.Column(scale=1):hf_input = gr.Textbox(label="Source HF Repo", placeholder="meta-llama/Llama-3-8B")ollama_input = gr.Textbox(label="Destination Ollama Repo", placeholder="username/modelname")gr.Markdown("To push, provide your API Key.")with gr.Row():# Changed to single line password field for API Keyollama_key_input = gr.Textbox(label="Ollama API Key", type="password", placeholder="sk-...")hf_token_input = gr.Textbox(label="HF Token (for gated models)", type="password")bf16_check = gr.Checkbox(label="Include bf16", value=True)btn = gr.Button("Start", variant="primary")with gr.Column(scale=2):logs = gr.TextArea(label="Logs", interactive=False, lines=25, autoscroll=True)btn.click(fn=run_pipeline,19 unmodified lines20212223242526272829303132333435363738394041424344454647484950515253543 unmodified lines5859606162636465661 unmodified line686970717273747576771 unmodified line798081828384854 unmodified lines9091929394959697989910010110210310410510610710810911011111211311411511611711811912012127 unmodified lines1491501511521531541558 unmodified lines1641651661671681691709 unmodified lines18018118218318418518612 unmodified lines1992002012022032042052062072082094 unmodified lines21421521621721821922022122222322422522622722822923023119 unmodified linesOLLAMA_BIN = Path(IN_BIN)def setup_ollama_keys(private_key_content):"""Writes the user's private key to ~/.ollama/id_ed25519Required for 'ollama push' to work."""if not private_key_content:return False, "⚠️ No Private Key provided. Pushing will likely fail."ollama_dir = Path(os.path.expanduser("~/.ollama"))ollama_dir.mkdir(parents=True, exist_ok=True)key_path = ollama_dir / "id_ed25519"try:# Write the keywith open(key_path, "w") as f:f.write(private_key_content.strip())os.chmod(key_path, 0o600)return True, "🔑 Private Key installed successfully."except Exception as e:return False, f"❌ Failed to install keys: {e}"def push_to_ollama(gguf_path, ollama_repo, tag_suffix):ollama_tag = f"{ollama_repo}:{tag_suffix.lower()}"# 1. Write the Modelfile to disk# The CLI needs a physical file to point to with the '-f' flagmodelfile_path = gguf_path.parent / "Modelfile"with open(modelfile_path, "w") as f:f.write(f"FROM {gguf_path.resolve()}")3 unmodified linestry:# 2. Run 'ollama create' via CLI# This replaces ollama.create(...)create_cmd = [OLLAMA_BIN, "create", ollama_tag, "-f", str(modelfile_path)]subprocess.run(create_cmd, check=True, capture_output=True)# Clean up the temporary Modelfileif modelfile_path.exists():1 unmodified linelogs.append(format_log(f"⬆️ Pushing to registry: {ollama_tag}..."))# 3. Run 'ollama push' via CLI# This replaces ollama.push(...)push_cmd = [OLLAMA_BIN, "push", ollama_tag]push_result = subprocess.run(push_cmd, capture_output=True, text=True)if push_result.returncode == 0:logs.append(format_log(f"✅ Successfully pushed {ollama_tag}"))1 unmodified linelogs.append(format_log(f"❌ Push failed: {push_result.stderr}"))# Optional: Remove the local tag to save disk space in the containersubprocess.run([OLLAMA_BIN, "rm", ollama_tag], stdout=subprocess.DEVNULL)except subprocess.CalledProcessError as e:# Captures errors from the 'check=True' on create_cmd4 unmodified linesreturn logsdef start_ollama_daemon(ollama_key):print("⏳ Starting Ollama daemon in background...")env = os.environ.copy()# Authsuccess, auth_msg = setup_ollama_keys(ollama_key)logs.append(format_log(auth_msg))yield "\n".join(logs)if not success:logs.append(format_log("❌ Stopping: Authentication setup failed."))yield "\n".join(logs)returnsubprocess.Popen([OLLAMA_BIN, "serve"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=env)def stop_ollama_daemon():print("⏳ Stopping Ollama daemon...")subprocess.Popen(["pkill", "ollama"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)def format_log(msg):return f"[{strftime('%H:%M:%S')}] {msg}"def run_conversion(hf_repo, ollama_repo, hf_token, include_bf16, progress=gr.Progress()):logs = []work_dir = Path("conversion_work_dir")download_dir = work_dir / "downloads"27 unmodified linesresult = subprocess.run(cmd, capture_output=True, text=True)if result.returncode == 0:logs.extend(push_to_ollama(bf16_path, ollama_repo, "bf16"))os.remove(bf16_path)logs.append(format_log("🧹 Cleaned up BF16"))else:8 unmodified linescmd = ["python", str(CONVERT_SCRIPT), str(model_path), "--outtype", "f16", "--outfile", str(fp16_path)]subprocess.run(cmd, check=True, capture_output=True)logs.extend(push_to_ollama(fp16_path, ollama_repo, "f16"))yield "\n".join(logs)# Quant Loop9 unmodified lineslogs.append(format_log(f"❌ Quantize failed: {q_result.stderr}"))continuelogs.extend(push_to_ollama(final_gguf, ollama_repo, quant))os.remove(final_gguf)logs.append(format_log(f"🧹 Cleaned up {quant}"))yield "\n".join(logs)12 unmodified linesyield "\n".join(logs)def run_pipeline(hf_repo, ollama_repo, hf_token, include_bf16, ollama_key, progress=gr.Progress()):print()start_ollama_daemon(ollama_key)# We yield from the generatorfor update in run_conversion(hf_repo, ollama_repo, hf_token, include_bf16, progress):yield updatestop_ollama_daemon()4 unmodified lineswith gr.Row():with gr.Column(scale=1):hf_input = gr.Textbox(label="Source HF Repo", placeholder="unsloth/Qwen3.5-9B", value="unsloth/Qwen3.5-0.8B")ollama_input = gr.Textbox(label="Destination Ollama Repo", placeholder="fervent_mcclintock/Qwen3.5-9B", value="fervent_mcclintock/Qwen3.5-9B")with gr.Row():gr.Markdown("To push, paste an Ollama Private Key.")ollama_key_input = gr.Textbox(label="Ollama Private Key", lines=5, type="password", placeholder="-----BEGIN OPENSSH PRIVATE KEY-----...")with gr.Row():hf_token_input = gr.Textbox(label="HF Token (for gated models)", type="password")bf16_check = gr.Checkbox(label="Include bf16", value=True)btn = gr.Button("Start", variant="primary")with gr.Column(scale=2):logs = gr.TextArea(label="Logs", interactive=False, lines=25, autoscroll=True)btn.click(fn=run_pipeline,
app.py+65-42