zerovic commited on
Commit
ffc6340
·
verified ·
1 Parent(s): e10ba58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +26 -20
app.py CHANGED
@@ -1,17 +1,15 @@
1
  import sys
2
  import importlib
 
 
3
 
4
  # =================================================================
5
  # CRITICAL PYTHON 3.13 / GRADIO SDK CONFLICT MONKEY-PATCHES
6
- # Executed by intercepting and adjusting real modules dynamically.
7
  # =================================================================
8
 
9
  # 1. Safely inject HfFolder directly into the real huggingface_hub without blocking other imports
10
  try:
11
- # Force load the actual installed huggingface_hub package first
12
  real_hf_hub = importlib.import_module('huggingface_hub')
13
-
14
- # If the real package is missing HfFolder (Python 3.13 / hub 0.26+ issue), inject a compliant stub
15
  if not hasattr(real_hf_hub, 'HfFolder'):
16
  class MockHfFolder:
17
  @classmethod
@@ -22,9 +20,7 @@ try:
22
  def delete_token(cls): pass
23
 
24
  real_hf_hub.HfFolder = MockHfFolder
25
- # Ensure it's globally visible across all sub-module reference caches
26
  sys.modules['huggingface_hub'].HfFolder = MockHfFolder
27
- print("Successfully injected missing HfFolder component into huggingface_hub.")
28
  except Exception as patch_err_1:
29
  print(f"Pre-import HfFolder patch skipped or failed: {patch_err_1}")
30
 
@@ -44,22 +40,20 @@ except Exception as patch_err_2:
44
  print(f"Schema serialization engine patch deferred: {patch_err_2}")
45
  # =================================================================
46
 
47
- import os
48
  import cv2
49
  import gradio as gr
50
  import numpy as np
51
  import onnxruntime as ort
52
- from huggingface_hub import hf_hub_download
53
 
54
- # Map open model checkpoints using verified community organization targets
55
  MODELS = {
56
  "RealESRGAN_x2plus (Faster 2x)": {
57
- "repo_id": "onnx-community/RealESRGAN_x2plus_onnx",
58
- "filename": "model.onnx",
59
  },
60
  "RealESRGAN_x4plus (General 4x)": {
61
- "repo_id": "onnx-community/RealESRGAN_x4plus_onnx",
62
- "filename": "model.onnx",
63
  }
64
  }
65
 
@@ -69,9 +63,8 @@ ort_session = None
69
 
70
  def load_model(model_choice):
71
  """
72
- Switches the active ONNX runtime model configuration.
73
- Uses the native hf_hub_download wrapper which works seamlessly
74
- when hitting official community/organization repos.
75
  """
76
  global current_model_name, ort_session
77
 
@@ -79,9 +72,22 @@ def load_model(model_choice):
79
  return ort_session
80
 
81
  cfg = MODELS[model_choice]
82
-
83
- print(f"Loading weights for {model_choice}...")
84
- model_path = hf_hub_download(repo_id=cfg["repo_id"], filename=cfg["filename"])
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
  # Configure ONNX runtime parameters optimized for CPU processing execution
87
  session_options = ort.SessionOptions()
@@ -140,7 +146,7 @@ def upscale_image(input_img, model_choice):
140
  # Define the user interface layout
141
  with gr.Blocks(title="AI Lightweight Image Upscaler (ONNX)") as demo:
142
  gr.Markdown("# 🖼️ AI Image Resizer & Upscaler (ONNX Engine)")
143
- gr.Markdown("Running locally on Hugging Face Free CPU hardware using official `onnx-community` model tracks.")
144
 
145
  with gr.Row():
146
  with gr.Column():
 
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
 
8
  # =================================================================
9
 
10
  # 1. Safely inject HfFolder directly into the real huggingface_hub without blocking other imports
11
  try:
 
12
  real_hf_hub = importlib.import_module('huggingface_hub')
 
 
13
  if not hasattr(real_hf_hub, 'HfFolder'):
14
  class MockHfFolder:
15
  @classmethod
 
20
  def delete_token(cls): pass
21
 
22
  real_hf_hub.HfFolder = MockHfFolder
 
23
  sys.modules['huggingface_hub'].HfFolder = MockHfFolder
 
24
  except Exception as patch_err_1:
25
  print(f"Pre-import HfFolder patch skipped or failed: {patch_err_1}")
26
 
 
40
  print(f"Schema serialization engine patch deferred: {patch_err_2}")
41
  # =================================================================
42
 
 
43
  import cv2
44
  import gradio as gr
45
  import numpy as np
46
  import onnxruntime as ort
 
47
 
48
+ # Explicit public direct mirror links bypassing authenticated API wrappers
49
  MODELS = {
50
  "RealESRGAN_x2plus (Faster 2x)": {
51
+ "url": "https://huggingface.co/onnx-community/RealESRGAN_x2plus_onnx/resolve/main/model.onnx",
52
+ "local_name": "RealESRGAN_x2plus.onnx"
53
  },
54
  "RealESRGAN_x4plus (General 4x)": {
55
+ "url": "https://huggingface.co/onnx-community/RealESRGAN_x4plus_onnx/resolve/main/model.onnx",
56
+ "local_name": "RealESRGAN_x4plus.onnx"
57
  }
58
  }
59
 
 
63
 
64
  def load_model(model_choice):
65
  """
66
+ Downloads model weights directly via open browser mirrors into the transient container space
67
+ to completely circumvent the 401 unauthenticated API token requirements.
 
68
  """
69
  global current_model_name, ort_session
70
 
 
72
  return ort_session
73
 
74
  cfg = MODELS[model_choice]
75
+ cache_dir = "/tmp/models"
76
+ os.makedirs(cache_dir, exist_ok=True)
77
+ model_path = os.path.join(cache_dir, cfg["local_name"])
78
+
79
+ # Download only if the model file is not already cached locally
80
+ if not os.path.exists(model_path):
81
+ print(f"Downloading weights for {model_choice} directly via public mirror stream...")
82
+ try:
83
+ # Custom User-Agent prevents generic scraper blockades on CDN edges
84
+ opener = urllib.request.build_opener()
85
+ opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)')]
86
+ urllib.request.install_opener(opener)
87
+ urllib.request.urlretrieve(cfg["url"], model_path)
88
+ print(f"Successfully cached model file locally at: {model_path}")
89
+ except Exception as dl_err:
90
+ raise RuntimeError(f"Direct weight initialization stream failed: {dl_err}")
91
 
92
  # Configure ONNX runtime parameters optimized for CPU processing execution
93
  session_options = ort.SessionOptions()
 
146
  # Define the user interface layout
147
  with gr.Blocks(title="AI Lightweight Image Upscaler (ONNX)") as demo:
148
  gr.Markdown("# 🖼️ AI Image Resizer & Upscaler (ONNX Engine)")
149
+ gr.Markdown("Running locally on Hugging Face Free CPU hardware using direct public weight streams.")
150
 
151
  with gr.Row():
152
  with gr.Column():