Spaces:
Sleeping
Sleeping
File size: 6,454 Bytes
621ca38 60db6f5 621ca38 313799b 60db6f5 621ca38 fdee071 621ca38 60db6f5 621ca38 fdee071 621ca38 60db6f5 43ab1c5 60db6f5 621ca38 fdee071 621ca38 43ab1c5 60db6f5 43ab1c5 60db6f5 fdee071 60db6f5 43ab1c5 60db6f5 fdee071 621ca38 60db6f5 621ca38 60db6f5 43ab1c5 60db6f5 43ab1c5 60db6f5 43ab1c5 60db6f5 43ab1c5 60db6f5 527c1a8 60db6f5 43ab1c5 60db6f5 621ca38 60db6f5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 |
import streamlit as st
import os
import subprocess
import cv2
import matplotlib.pyplot as plt
import glob
import psutil
import time
def modify_degradations_py():
file_path = '/usr/local/lib/python3.10/site-packages/basicsr/data/degradations.py'
with open(file_path, 'r') as f:
lines = f.readlines()
# Find the line containing 'from torchvision.transforms.functional_tensor import rgb_to_grayscale'
for i, line in enumerate(lines):
if 'from torchvision.transforms.functional_tensor import rgb_to_grayscale' in line:
# Replace it with 'from torchvision.transforms.functional import rgb_to_grayscale'
lines[i] = 'from torchvision.transforms.functional import rgb_to_grayscale\n'
break
with open(file_path, 'w') as f:
f.writelines(lines)
# Call the function to modify the file
modify_degradations_py()
# Page configuration
st.set_page_config(
page_title="Image Enhancer",
page_icon="🖼️",
layout="wide",
initial_sidebar_state="expanded"
)
# Function to display images side by side
def display(img1, img2):
try:
fig = plt.figure(figsize=(25, 10))
ax1 = fig.add_subplot(1, 2, 1)
plt.title('Input image', fontsize=16)
ax1.axis('off')
ax2 = fig.add_subplot(1, 2, 2)
plt.title('Enhanced output', fontsize=16)
ax2.axis('off')
ax1.imshow(img1)
ax2.imshow(img2)
st.pyplot(fig, use_container_width=True)
plt.close(fig)
except Exception as e:
st.error(f"Error displaying images: {str(e)}")
# Function to read an image
def imread(img_path):
try:
if not os.path.exists(img_path):
st.error(f"Image not found: {img_path}")
return None
img = cv2.imread(img_path)
if img is None:
st.error(f"Failed to load image: {img_path}")
return None
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
return img
except Exception as e:
st.error(f"Error reading image: {str(e)}")
return None
# Function to clean up directories
def cleanup_directories():
directories = ['inputs/upload', 'results']
for directory in directories:
if os.path.exists(directory):
try:
for file in glob.glob(os.path.join(directory, '**/*'), recursive=True):
if os.path.isfile(file):
os.remove(file)
except Exception as e:
st.sidebar.warning(f"Cleanup warning: {str(e)}")
# Function to run shell commands
def run_shell_commands():
try:
directories = [
"results/cropped_faces",
"results/restored_faces",
"results/restored_imgs",
"results/cmp"
]
for directory in directories:
os.makedirs(directory, exist_ok=True)
command = "python inference_gfpgan.py -i inputs/upload -o results -v 1.3 -s 2 --bg_upsampler realesrgan"
process = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=300)
if process.returncode != 0:
st.error(f"Enhancement failed: {process.stderr}")
return False
return True
except subprocess.TimeoutExpired:
st.error("Process timed out after 5 minutes")
return False
except Exception as e:
st.error(f"Process error: {str(e)}")
return False
# Memory monitoring
def check_memory():
memory = psutil.Process().memory_info().rss / 1024 / 1024
st.sidebar.text(f"Memory usage: {memory:.2f} MB")
# Main app
def main():
st.title('Image Enhancer')
st.write('Upload an image to enhance its quality')
st.write('Please wait 30-40 seconds after uploading 🙂')
# Sidebar information
st.sidebar.title("App Info")
st.sidebar.write("This app enhances image quality using AI")
check_memory()
# Clean up before starting
cleanup_directories()
# File uploader with progress bar
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
try:
# Show processing status
status = st.empty()
progress_bar = st.progress(0)
status.info("Starting process...")
# Create input directory
input_path = os.path.join('inputs', 'upload')
os.makedirs(input_path, exist_ok=True)
# Save uploaded file
file_path = os.path.join(input_path, uploaded_file.name)
with open(file_path, 'wb') as f:
f.write(uploaded_file.getbuffer())
progress_bar.progress(25)
status.info("File uploaded successfully. Processing image...")
# Run enhancement
if run_shell_commands():
progress_bar.progress(75)
status.success("Processing complete!")
# Display results
input_folder = 'results/cropped_faces'
result_folder = 'results/restored_faces'
input_list = sorted(glob.glob(os.path.join(input_folder, '*')))
output_list = sorted(glob.glob(os.path.join(result_folder, '*')))
if not input_list or not output_list:
st.warning("No faces detected in the image.")
else:
for input_path, output_path in zip(input_list, output_list):
img_input = imread(input_path)
img_output = imread(output_path)
if img_input is not None and img_output is not None:
display(img_input, img_output)
progress_bar.progress(100)
else:
status.error("Failed to process image.")
except Exception as e:
st.error(f"Error: {str(e)}")
finally:
# Cleanup
cleanup_directories()
# Clear status and progress
time.sleep(2)
status.empty()
progress_bar.empty()
check_memory()
if __name__ == "__main__":
try:
main()
except Exception as e:
st.error(f"Application error: {str(e)}") |