import streamlit as st from fastai.vision import open_image, load_learner, show_image import PIL.Image from PIL import Image from io import BytesIO import requests import torch.nn as nn import os import tempfile import shutil # Define the FeatureLoss class class FeatureLoss(nn.Module): def __init__(self, m_feat, layer_ids, layer_wgts): super().__init__() self.m_feat = m_feat self.loss_features = [self.m_feat[i] for i in layer_ids] self.hooks = hook_outputs(self.loss_features, detach=False) self.wgts = layer_wgts self.metric_names = ['pixel',] + [f'feat_{i}' for i in range(len(layer_ids))] + [f'gram_{i}' for i in range(len(layer_ids))] def make_features(self, x, clone=False): self.m_feat(x) return [(o.clone() if clone else o) for o in self.hooks.stored] def forward(self, input, target): out_feat = self.make_features(target, clone=True) in_feat = self.make_features(input) self.feat_losses = [base_loss(input, target)] self.feat_losses += [base_loss(f_in, f_out) * w for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)] self.feat_losses += [base_loss(gram_matrix(f_in), gram_matrix(f_out)) * w**2 * 5e3 for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)] self.metrics = dict(zip(self.metric_names, self.feat_losses)) return sum(self.feat_losses) def __del__(self): self.hooks.remove() def add_margin(pil_img, top, right, bottom, left, color): width, height = pil_img.size new_width = width + right + left new_height = height + top + bottom result = Image.new(pil_img.mode, (new_width, new_height), color) result.paste(pil_img, (left, top)) return result def inference(image_path_or_url, learn): if image_path_or_url.startswith('http://') or image_path_or_url.startswith('https://'): response = requests.get(image_path_or_url) img = PIL.Image.open(BytesIO(response.content)).convert("RGB") else: img = PIL.Image.open(image_path_or_url).convert("RGB") im_new = add_margin(img, 250, 250, 250, 250, (255, 255, 255)) im_new.save("test.jpg", quality=95) img = open_image("test.jpg") p, img_hr, b = learn.predict(img) return img_hr # Streamlit application st.title("Image Inference with Fastai") # Download the model file from the Hugging Face repository model_url = "https://huggingface.co/Hammad712/image2sketch/resolve/main/image2sketch.pkl" model_file_path = 'image2sketch.pkl' if not os.path.exists(model_file_path): with st.spinner('Downloading model...'): response = requests.get(model_url) with open(model_file_path, 'wb') as f: f.write(response.content) st.success('Model downloaded successfully!') # Create a temporary directory for the model with tempfile.TemporaryDirectory() as tmpdirname: shutil.move(model_file_path, os.path.join(tmpdirname, 'export.pkl')) learn = load_learner(tmpdirname) # Input for image URL or path image_path_or_url = st.text_input("Enter image path or URL", "") # Run inference button if st.button("Run Inference"): if image_path_or_url: with st.spinner('Processing...'): high_res_image = inference(image_path_or_url, learn) st.image(high_res_image, caption='High Resolution Image', use_column_width=True) else: st.error("Please enter a valid image path or URL.")