Janeka commited on
Commit
330ebbf
·
verified ·
1 Parent(s): ee56820

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -91
app.py CHANGED
@@ -1,107 +1,59 @@
1
  import gradio as gr
2
  import numpy as np
3
- import onnxruntime as ort
4
- from PIL import Image
5
  import cv2
 
6
  import os
7
- import requests
8
- import hashlib
9
-
10
- # Configuration - UPDATED MODEL URL
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 for verification
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 and retries"""
25
- print("Downloading model...")
26
- for attempt in range(3): # Retry up to 3 times
27
- try:
28
- # Use a mirror URL if primary fails
29
- urls = [
30
- MODEL_URL,
31
- "https://huggingface.co/spaces/akhaliq/Real-ESRGAN/resolve/main/realesr-general-x4v3.onnx"
32
- ]
33
-
34
- for url in urls:
35
- try:
36
- response = requests.get(url, stream=True, timeout=30)
37
- response.raise_for_status()
38
-
39
- # Save in chunks
40
- with open(MODEL_PATH, "wb") as f:
41
- for chunk in response.iter_content(chunk_size=8192):
42
- f.write(chunk)
43
-
44
- # Verify download
45
- if verify_file(MODEL_PATH, EXPECTED_MD5):
46
- print("Model downloaded and verified successfully!")
47
- return
48
- os.remove(MODEL_PATH)
49
- except Exception:
50
- continue
51
-
52
- raise ValueError("All download attempts failed")
53
- except Exception as e:
54
- if attempt == 2: # Final attempt
55
- raise gr.Error(f"Model download failed after 3 attempts: {str(e)}")
56
- print(f"Attempt {attempt + 1} failed, retrying...")
57
 
58
- # Download model if missing or corrupted
59
- if not verify_file(MODEL_PATH, EXPECTED_MD5):
60
- download_model()
61
-
62
- # Initialize ONNX Runtime (CPU only for free tier)
63
- try:
64
- ort_session = ort.InferenceSession(
65
- MODEL_PATH,
66
- providers=['CPUExecutionProvider'] # Only use CPU on free tier
67
- )
68
- print("Model loaded successfully!")
69
- except Exception as e:
70
- raise gr.Error(f"Model loading failed: {str(e)}\nTry deleting the space and recreating it.")
71
-
72
- def enhance(image):
73
- """Image enhancement function"""
74
  try:
75
- # Convert and resize
76
- img = np.array(image)
77
- if max(img.shape) > 512: # Free tier memory limit
78
- scale = 512 / max(img.shape)
79
- img = cv2.resize(img, (0,0), fx=scale, fy=scale)
 
 
 
80
 
81
- # Preprocess
82
- img = img.astype(np.float32) / 255.0
83
- img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
84
- img = np.transpose(img, (2, 0, 1))
85
- img = np.expand_dims(img, axis=0)
86
 
87
- # Inference
88
- output = ort_session.run(None, {'input': img})[0]
 
 
 
 
 
89
 
90
- # Postprocess
91
- output = output.squeeze().transpose(1, 2, 0)
92
- output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
93
- output = (output * 255).clip(0, 255).astype(np.uint8)
94
- return Image.fromarray(output)
95
  except Exception as e:
96
  raise gr.Error(f"Enhancement failed: {str(e)}")
97
 
98
- # Create interface
99
  demo = gr.Interface(
100
- fn=enhance,
101
- inputs=gr.Image(type="pil"),
102
- outputs=gr.Image(type="pil"),
103
- title="Image Enhancement",
104
- allow_flagging="never"
 
 
 
 
 
 
 
105
  )
106
 
107
  demo.launch()
 
1
  import gradio as gr
2
  import numpy as np
 
 
3
  import cv2
4
+ from PIL import Image
5
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ def enhance_image(
8
+ input_img,
9
+ contrast=1.2,
10
+ brightness=10,
11
+ sharpness=2.0,
12
+ denoise_strength=10
13
+ ):
14
+ """Enhance image using OpenCV operations"""
 
 
 
 
 
 
 
 
15
  try:
16
+ # Convert to OpenCV format
17
+ img = np.array(input_img)
18
+
19
+ # Contrast and brightness adjustment
20
+ img = cv2.convertScaleAbs(img, alpha=contrast, beta=brightness)
21
+
22
+ # Denoising
23
+ img = cv2.fastNlMeansDenoisingColored(img, None, denoise_strength, denoise_strength, 7, 21)
24
 
25
+ # Sharpening
26
+ kernel = np.array([[-1,-1,-1],
27
+ [-1,9,-1],
28
+ [-1,-1,-1]])
29
+ img = cv2.filter2D(img, -1, kernel)
30
 
31
+ # Color correction
32
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2LAB)
33
+ l, a, b = cv2.split(img)
34
+ clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
35
+ l = clahe.apply(l)
36
+ img = cv2.merge((l,a,b))
37
+ img = cv2.cvtColor(img, cv2.COLOR_LAB2RGB)
38
 
39
+ return Image.fromarray(img)
 
 
 
 
40
  except Exception as e:
41
  raise gr.Error(f"Enhancement failed: {str(e)}")
42
 
43
+ # Create interface with adjustable parameters
44
  demo = gr.Interface(
45
+ fn=enhance_image,
46
+ inputs=[
47
+ gr.Image(type="pil", label="Input Image"),
48
+ gr.Slider(0.5, 2.0, value=1.2, label="Contrast"),
49
+ gr.Slider(0, 30, value=10, label="Brightness"),
50
+ gr.Slider(0.5, 3.0, value=2.0, label="Sharpness"),
51
+ gr.Slider(0, 20, value=10, label="Denoise Strength")
52
+ ],
53
+ outputs=gr.Image(type="pil", label="Enhanced Image"),
54
+ title="Image Enhancement Tool",
55
+ allow_flagging="never",
56
+ examples=["example.jpg"] if os.path.exists("example.jpg") else None
57
  )
58
 
59
  demo.launch()