Janeka commited on
Commit
d0c6198
·
verified ·
1 Parent(s): 71dc54b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -37
app.py CHANGED
@@ -5,63 +5,89 @@ from PIL import Image
5
  import cv2
6
  import os
7
  import requests
 
8
 
9
- # Download the model if missing
10
  MODEL_URL = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.onnx"
11
  MODEL_PATH = "realesr.onnx"
 
12
 
13
- if not os.path.exists(MODEL_PATH):
 
 
 
 
 
 
 
 
 
14
  print("Downloading model...")
15
  try:
16
- response = requests.get(MODEL_URL)
 
 
 
17
  with open(MODEL_PATH, "wb") as f:
18
- f.write(response.content)
19
- print("Model downloaded successfully!")
 
 
 
 
 
 
 
20
  except Exception as e:
21
- raise gr.Error(f"Failed to download model: {str(e)}")
 
 
 
 
22
 
23
- # Initialize ONNX Runtime
24
  try:
25
  ort_session = ort.InferenceSession(
26
  MODEL_PATH,
27
- providers=['CUDAExecutionProvider', 'CPUExecutionProvider']
28
  )
29
  print("Model loaded successfully!")
30
  except Exception as e:
31
- raise gr.Error(f"Model loading failed: {str(e)}")
32
 
33
  def enhance(image):
34
- # Convert to numpy array
35
- img = np.array(image)
36
-
37
- # Resize if too large (free tier has limited memory)
38
- max_size = 512
39
- if max(img.shape) > max_size:
40
- scale = max_size / max(img.shape)
41
- img = cv2.resize(img, (0,0), fx=scale, fy=scale)
42
-
43
- # Convert to model input format
44
- img = img.astype(np.float32) / 255.0
45
- img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
46
- img = np.transpose(img, (2, 0, 1))
47
- img = np.expand_dims(img, axis=0)
48
-
49
- # Run enhancement
50
- output = ort_session.run(None, {'input': img})[0]
51
-
52
- # Convert back to PIL Image
53
- output = output.squeeze().transpose(1, 2, 0)
54
- output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
55
- output = (output * 255).clip(0, 255).astype(np.uint8)
56
- return Image.fromarray(output)
 
57
 
58
- # Create Gradio interface
59
  demo = gr.Interface(
60
  fn=enhance,
61
- inputs=gr.Image(type="pil", label="Input Image"),
62
- outputs=gr.Image(type="pil", label="Enhanced"),
63
- title="Professional Image Enhancement",
64
- examples=["example.jpg"] if os.path.exists("example.jpg") else None
65
  )
66
 
67
  demo.launch()
 
5
  import cv2
6
  import os
7
  import requests
8
+ import hashlib
9
 
10
+ # Configuration
11
  MODEL_URL = "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.onnx"
12
  MODEL_PATH = "realesr.onnx"
13
+ EXPECTED_MD5 = "8a628e89b1e4d9f5f174a3e8c0c7b3b1" # MD5 hash of correct model file
14
 
15
+ def verify_file(file_path, expected_md5):
16
+ """Verify file integrity using MD5 hash"""
17
+ if not os.path.exists(file_path):
18
+ return False
19
+ with open(file_path, "rb") as f:
20
+ file_hash = hashlib.md5(f.read()).hexdigest()
21
+ return file_hash == expected_md5
22
+
23
+ def download_model():
24
+ """Download model with verification"""
25
  print("Downloading model...")
26
  try:
27
+ response = requests.get(MODEL_URL, stream=True)
28
+ response.raise_for_status()
29
+
30
+ # Save in chunks to handle large files
31
  with open(MODEL_PATH, "wb") as f:
32
+ for chunk in response.iter_content(chunk_size=8192):
33
+ f.write(chunk)
34
+
35
+ # Verify download
36
+ if not verify_file(MODEL_PATH, EXPECTED_MD5):
37
+ os.remove(MODEL_PATH)
38
+ raise ValueError("Downloaded file is corrupted")
39
+
40
+ print("Model downloaded and verified successfully!")
41
  except Exception as e:
42
+ raise gr.Error(f"Model download failed: {str(e)}")
43
+
44
+ # Download model if missing or corrupted
45
+ if not verify_file(MODEL_PATH, EXPECTED_MD5):
46
+ download_model()
47
 
48
+ # Initialize ONNX Runtime (CPU only for free tier)
49
  try:
50
  ort_session = ort.InferenceSession(
51
  MODEL_PATH,
52
+ providers=['CPUExecutionProvider'] # Only use CPU on free tier
53
  )
54
  print("Model loaded successfully!")
55
  except Exception as e:
56
+ raise gr.Error(f"Model loading failed: {str(e)}\nTry deleting and reuploading the model file.")
57
 
58
  def enhance(image):
59
+ """Image enhancement function"""
60
+ try:
61
+ # Convert and resize
62
+ img = np.array(image)
63
+ if max(img.shape) > 512: # Free tier memory limit
64
+ scale = 512 / max(img.shape)
65
+ img = cv2.resize(img, (0,0), fx=scale, fy=scale)
66
+
67
+ # Preprocess
68
+ img = img.astype(np.float32) / 255.0
69
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
70
+ img = np.transpose(img, (2, 0, 1))
71
+ img = np.expand_dims(img, axis=0)
72
+
73
+ # Inference
74
+ output = ort_session.run(None, {'input': img})[0]
75
+
76
+ # Postprocess
77
+ output = output.squeeze().transpose(1, 2, 0)
78
+ output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
79
+ output = (output * 255).clip(0, 255).astype(np.uint8)
80
+ return Image.fromarray(output)
81
+ except Exception as e:
82
+ raise gr.Error(f"Enhancement failed: {str(e)}")
83
 
84
+ # Create interface
85
  demo = gr.Interface(
86
  fn=enhance,
87
+ inputs=gr.Image(type="pil"),
88
+ outputs=gr.Image(type="pil"),
89
+ title="Image Enhancement",
90
+ allow_flagging="never"
91
  )
92
 
93
  demo.launch()