zerovic commited on
Commit
6d69bf6
·
verified ·
1 Parent(s): 19736de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -35
app.py CHANGED
@@ -1,7 +1,6 @@
1
  import sys
2
  import importlib
3
  import os
4
- import urllib.request
5
 
6
  # =================================================================
7
  # CRITICAL PYTHON 3.13 / GRADIO SDK CONFLICT MONKEY-PATCHES
@@ -13,7 +12,7 @@ try:
13
  if not hasattr(real_hf_hub, 'HfFolder'):
14
  class MockHfFolder:
15
  @classmethod
16
- def get_token(cls): return None
17
  @classmethod
18
  def save_token(cls, token): pass
19
  @classmethod
@@ -44,18 +43,17 @@ import cv2
44
  import gradio as gr
45
  import numpy as np
46
  import onnxruntime as ort
 
47
 
48
- # Public Hugging Face CDN URL patterns bypassing authenticated internal Space routing loops
49
  MODELS = {
50
  "RealESRGAN_x2plus (Faster 2x)": {
51
- "url": "https://huggingface.co/onnx-community/RealESRGAN_x2plus_onnx/blob/main/model.onnx",
52
- "cdn_url": "https://huggingface.co/onnx-community/RealESRGAN_x2plus_onnx/resolve/main/model.onnx",
53
- "local_name": "RealESRGAN_x2plus.onnx"
54
  },
55
  "RealESRGAN_x4plus (General 4x)": {
56
- "url": "https://huggingface.co/onnx-community/RealESRGAN_x4plus_onnx/blob/main/model.onnx",
57
- "cdn_url": "https://huggingface.co/onnx-community/RealESRGAN_x4plus_onnx/resolve/main/model.onnx",
58
- "local_name": "RealESRGAN_x4plus.onnx"
59
  }
60
  }
61
 
@@ -65,8 +63,9 @@ ort_session = None
65
 
66
  def load_model(model_choice):
67
  """
68
- Downloads model weights cleanly using standard streams while managing custom headers
69
- to prevent the Hugging Face gateway from blocking the local container context.
 
70
  """
71
  global current_model_name, ort_session
72
 
@@ -74,29 +73,17 @@ def load_model(model_choice):
74
  return ort_session
75
 
76
  cfg = MODELS[model_choice]
77
- cache_dir = "/tmp/models"
78
- os.makedirs(cache_dir, exist_ok=True)
79
- model_path = os.path.join(cache_dir, cfg["local_name"])
80
-
81
- # Download only if the model file is not already cached locally
82
- if not os.path.exists(model_path):
83
- print(f"Downloading weights for {model_choice} via open CDN routing stream...")
84
- try:
85
- # We configure standard user agents and referers to completely satisfy the Hugging Face
86
- # cloud edge firewall rules, allowing tokenless open downloads inside the Space sandbox.
87
- req = urllib.request.Request(
88
- cfg["cdn_url"],
89
- headers={
90
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
91
- 'Accept': '*/*',
92
- 'Connection': 'keep-alive'
93
- }
94
- )
95
- with urllib.request.urlopen(req) as response, open(model_path, 'wb') as out_file:
96
- out_file.write(response.read())
97
- print(f"Successfully cached model file locally at: {model_path}")
98
- except Exception as dl_err:
99
- raise RuntimeError(f"Direct weight initialization stream failed: {dl_err}")
100
 
101
  # Configure ONNX runtime parameters optimized for CPU processing execution
102
  session_options = ort.SessionOptions()
@@ -155,7 +142,7 @@ def upscale_image(input_img, model_choice):
155
  # Define the user interface layout
156
  with gr.Blocks(title="AI Lightweight Image Upscaler (ONNX)") as demo:
157
  gr.Markdown("# 🖼️ AI Image Resizer & Upscaler (ONNX Engine)")
158
- gr.Markdown("Running locally on Hugging Face Free CPU hardware using direct public weight streams.")
159
 
160
  with gr.Row():
161
  with gr.Column():
 
1
  import sys
2
  import importlib
3
  import os
 
4
 
5
  # =================================================================
6
  # CRITICAL PYTHON 3.13 / GRADIO SDK CONFLICT MONKEY-PATCHES
 
12
  if not hasattr(real_hf_hub, 'HfFolder'):
13
  class MockHfFolder:
14
  @classmethod
15
+ def get_token(cls): return os.environ.get("HF_TOKEN")
16
  @classmethod
17
  def save_token(cls, token): pass
18
  @classmethod
 
43
  import gradio as gr
44
  import numpy as np
45
  import onnxruntime as ort
46
+ from huggingface_hub import hf_hub_download
47
 
48
+ # Map open model checkpoints using verified community organization targets
49
  MODELS = {
50
  "RealESRGAN_x2plus (Faster 2x)": {
51
+ "repo_id": "onnx-community/RealESRGAN_x2plus_onnx",
52
+ "filename": "model.onnx",
 
53
  },
54
  "RealESRGAN_x4plus (General 4x)": {
55
+ "repo_id": "onnx-community/RealESRGAN_x4plus_onnx",
56
+ "filename": "model.onnx",
 
57
  }
58
  }
59
 
 
63
 
64
  def load_model(model_choice):
65
  """
66
+ Switches the active ONNX runtime model configuration.
67
+ Uses the native hf_hub_download wrapper with the system-mounted HF_TOKEN
68
+ to seamlessly authenticate against the Hugging Face CDN gateway.
69
  """
70
  global current_model_name, ort_session
71
 
 
73
  return ort_session
74
 
75
  cfg = MODELS[model_choice]
76
+
77
+ print(f"Loading weights for {model_choice} using system environment authorization...")
78
+
79
+ # Retrieve the auto-mounted internal space authorization token if present
80
+ token = os.environ.get("HF_TOKEN")
81
+
82
+ model_path = hf_hub_download(
83
+ repo_id=cfg["repo_id"],
84
+ filename=cfg["filename"],
85
+ token=token
86
+ )
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
  # Configure ONNX runtime parameters optimized for CPU processing execution
89
  session_options = ort.SessionOptions()
 
142
  # Define the user interface layout
143
  with gr.Blocks(title="AI Lightweight Image Upscaler (ONNX)") as demo:
144
  gr.Markdown("# 🖼️ AI Image Resizer & Upscaler (ONNX Engine)")
145
+ gr.Markdown("Running locally on Hugging Face Free CPU hardware using official `onnx-community` model tracks.")
146
 
147
  with gr.Row():
148
  with gr.Column():