import gradio as gr import torch import torch.nn as nn import torchvision.transforms as transforms from PIL import Image # ========================================== # 1. MODEL ARCHITECTURE (Same as training) # ========================================== class ESPCN(nn.Module): def __init__(self, upscale_factor): super(ESPCN, self).__init__() self.conv1 = nn.Conv2d(3, 64, kernel_size=5, padding=2) self.conv2 = nn.Conv2d(64, 64, kernel_size=3, padding=1) self.conv3 = nn.Conv2d(64, 32, kernel_size=3, padding=1) self.conv4 = nn.Conv2d(32, 3 * (upscale_factor ** 2), kernel_size=3, padding=1) self.pixel_shuffle = nn.PixelShuffle(upscale_factor) self.relu = nn.ReLU() def forward(self, x): x = self.relu(self.conv1(x)) x = self.relu(self.conv2(x)) x = self.relu(self.conv3(x)) x = self.pixel_shuffle(self.conv4(x)) return x # ========================================== # 2. LOAD THE TRAINED MODEL (On CPU) # ========================================== # Device ko CPU set kar rahe hain taaki HF Spaces ke free tier me bina GPU ke chale device = torch.device("cpu") model = ESPCN(upscale_factor=4) # Yahan hum .pth file load kar rahe hain try: model.load_state_dict(torch.load("universal_sr_model.pth", map_location=device)) model.eval() print("Model loaded successfully!") except Exception as e: print(f"Error loading model: {e}") # ========================================== # 3. INFERENCE FUNCTION FOR GRADIO # ========================================== def enhance_image(img): if img is None: return None # Image ko RGB me ensure karna img = img.convert('RGB') # Image ko tensor me convert karna aur batch dimension add karna input_tensor = transforms.ToTensor()(img).unsqueeze(0).to(device) # Model se pass karna (no gradients needed for fast inference) with torch.no_grad(): output_tensor = model(input_tensor) # Output tensor ko wapas image me convert karna output_tensor = output_tensor.squeeze().clamp(0, 1) output_img = transforms.ToPILImage()(output_tensor) return output_img # ========================================== # 4. GRADIO INTERFACE SETUP # ========================================== # UI design setup iface = gr.Interface( fn=enhance_image, inputs=gr.Image(type="pil", label="Upload Unclear/Low-Res Image"), outputs=gr.Image(type="pil", label="4x Enhanced High-Res Image"), title="🌟 AI Super Resolution (4x Upscaler)", description="Apni unclear ya chhoti image upload karein aur hamara custom ESPCN model use 4x bada aur sharp kar dega. Yeh model scratch se train kiya gaya hai!", # 'allow_flagging' line hata di gayi hai taaki latest Gradio me crash na ho flagging_mode="never" ) # App launch karna if __name__ == "__main__": iface.launch()