Spaces:
Build error
Build error
File size: 10,789 Bytes
550ded0 120bfbe 550ded0 d53cd93 550ded0 b370a5f 550ded0 27d7eac 550ded0 27d7eac 550ded0 27d7eac 550ded0 27d7eac 550ded0 a6e977d 550ded0 d53cd93 550ded0 cdd7e4a 550ded0 | 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 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 | import streamlit as st
import os
# Set the title of the app
import torch
import torch.nn as nn
import torchvision.transforms as transforms
from torchvision.models import vgg19,vgg16
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
import os
import torch.nn.functional as F
import pandas as pd
import torch.optim as optim
import neural_style
import argparse
import os
import sys
import time
import re
# from PIL import ImageFilter, ImageResampling
import numpy as np
import torch
from torch.optim import Adam
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision import transforms
import torch.onnx
import utils
from transformer_net import TransformerNet
from vgg import Vgg16
from torch.utils.data import Dataset, DataLoader
st.set_page_config(layout='wide')
st.title("Neural Style transfer ")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def stylize_onnx(content_image, args):
"""
Read ONNX model and run it using onnxruntime
"""
# assert not args["export_onnx"]
import onnxruntime
ort_session = onnxruntime.InferenceSession(args["model"])
def to_numpy(tensor):
return (
tensor.detach().cpu().numpy()
if tensor.requires_grad
else tensor.cpu().numpy()
)
ort_inputs = {ort_session.get_inputs()[0].name: to_numpy(content_image)}
ort_outs = ort_session.run(None, ort_inputs)
img_out_y = ort_outs[0]
return torch.from_numpy(img_out_y)
def stylize(device,args):
content_image = utils.load_image(args['content_image'], scale=args['content_scale'])
content_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: x.mul(255))
])
content_image = content_transform(content_image)
content_image = content_image.unsqueeze(0).to(device)
if args['model'].endswith(".onnx"):
output = stylize_onnx(content_image, args)
else:
with torch.no_grad():
style_model = TransformerNet()
state_dict = torch.load( args['model'])
# remove saved deprecated running_* keys in InstanceNorm from the checkpoint
for k in list(state_dict.keys()):
if re.search(r'in\d+\.running_(mean|var)$', k):
del state_dict[k]
style_model.load_state_dict(state_dict)
style_model.to(device)
style_model.eval()
if args['export_onnx'] != False:
assert args['export_onnx_name'].endswith(".onnx"), "Export model file should end with .onnx"
output = torch.onnx.export(
style_model, content_image, args['export_onnx_name'], opset_version=11,
)
else:
output = style_model(content_image).cpu()
utils.save_image(args['output_image'], output[0])
return True
# args = {
# "content_image":"hemant_content3.jpg",
# "content_scale":0.95,
# "model":"epoch_100_Fri_Apr_19_00_29_00_2024_10_100000.model",
# "export_onnx": False,
# "export_onnx_name":"natural_art_style.onnx",
# "output_image":"./kavitha/hemanth_style13.jpg"
# }
# stylize(device,args)
def run_model(args):
# Function to run the model
# This is where you can place your model execution code
st.write("Running the model...")
# Simulate model running (you can replace this with your actual model code)
import time
result = stylize(device,args) # Simulate model running for 2 seconds
st.success("Model has run successfully!")
if result:
st.subheader('Output Image')
width = 400
height = 400
st.image(args["output_image"], caption='Final output',width=width)
# if result:
# width = 400
# height = 400
# st.image(args["output_image"], caption='Final output',width=width)
# def app():
# # Streamlit app title
# args = {
# }
# # Allow user to upload an image file
# uploaded_file = st.file_uploader('Upload a JPEG image', type=['jpg', 'jpeg'])
# # Check if a file has been uploaded
# if uploaded_file is not None:
# # Verify the uploaded file's format (extension)
# file_extension = uploaded_file.name.split('.')[-1].lower()
# if file_extension in ['jpg', 'jpeg']:
# # Specify the directory path where the image will be stored
# directory_path = 'C:\\Users\\Kavitha padala\\Desktop\\HemanthDL\\examples\\fast_neural_style\\neural_style\\images\\content_images'
# # Create the directory if it doesn't exist
# if not os.path.exists(directory_path):
# os.makedirs(directory_path)
# file_name = "content_image"
# # Generate the full path for the image file
# file_path = os.path.join(directory_path, file_name+"."+ file_extension)
# # Save the uploaded image to the specified directory
# with open(file_path, 'wb') as f:
# f.write(uploaded_file.getbuffer())
# model_sets = ['women_style_art_model_best1.model', 'women_style_art_model_best1.model']
# # Create a select box to allow users to choose one model set
# selected_model_set = st.selectbox(
# 'Choose a model set:', # Label for the select box
# model_sets # List of model sets
# )
# output_image_name = "style_image.jpg"
# args["content_image"] = file_path
# args["model"] = selected_model_set
# args["content_scale"] = 0.95
# args["output_image"] = "C:\\Users\\Kavitha padala\\Desktop\\HemanthDL\\examples\\fast_neural_style\\neural_style\\images\\style_images\\" + output_image_name
# args["export_onnx"] = False
# if st.button('Run Model'):
# run_model(args)
# # Display the selected model set
# st.write(f'You selected: {selected_model_set}')
# else:
# # If the file is not in the correct format, display an error message
# st.error('Please upload a JPG image file.')
# if __name__ == "__main__":
# app()
# def display_image():
# def run_style_transfer(content_image, style_image, model):
# # Placeholder function to run the style transfer model
# # Replace this function with your actual model execution code
# st.write(f"Running model: {model}")
# # Simulate processing (you can replace this with your actual model code)
# import time
# time.sleep(3)
# # For demonstration, we'll just return the style image as the output
# # (You would return the styled image as the final output in your actual model code)
# return style_image
def app():
# Streamlit app title
# Create a layout with three columns
left_col, middle_col, right_col = st.columns([1, 1, 2])
args = {}
result = False;
# Middle column: Display title
# Left column: Ask user to upload an image
with left_col:
st.subheader('Upload Image')
uploaded_image = st.file_uploader('Choose an image', type=['jpg', 'jpeg'])
if uploaded_image is not None:
# Verify the uploaded file's format (extension)
file_extension = uploaded_image.name.split('.')[-1].lower()
if file_extension in ['jpg', 'jpeg']:
# Specify the directory path where the image will be stored
directory_path = 'uploads'
# Create the directory if it doesn't exist
if not os.path.exists(directory_path):
os.makedirs(directory_path)
file_name = "content_image"
# Generate the full path for the image file
file_path = os.path.join(directory_path, file_name+"."+ file_extension)
args["content_image"] = file_path
# Save the uploaded image to the specified directory
with open(file_path, 'wb') as f:
f.write(uploaded_image.getbuffer())
st.image(uploaded_image,width=256)
# Right column top: Allow user to select a model and display style image
with middle_col:
# Define a list of models
style_images = ['Art Style', 'Women Art','glass art']
st.subheader('Style model')
# Create a select box to choose a model
selected_image = st.selectbox('Choose a model will be selected :', style_images)
models_dict = {
'Art Style':'art_style.model',
'Women Art':'women_style.model',
'glass art':'glass_art.model'
}
output_image_name = "style_image.jpg"
args["model"] = models_dict[selected_image]
args["content_scale"] = 0.95
args["output_image"] = output_image_name
args["export_onnx"] = False
# Left column: After clicking "Run Model" button, display the final output style transfer image
with right_col:
if uploaded_image is not None and selected_image in models_dict:
# Get the selected style image
# style_image_path = style_images[selected_model]
# # Load the uploaded image and style image
# content_image = uploaded_image
# style_image = style_image_path
if st.button('Run Model'):
result = run_model(args)
# Create a button to run the model
# if st.button('Run Model'):
# # Run style transfer model
# final_output = run_style_transfer(content_image, style_image, selected_model)
# # Resize the final output image
# # You can specify the desired width and height for the resized image
# width = 400 # Replace with your desired width
# height = 400 # Replace with your desired height
# # Display the final output image with specified width and height
# st.subheader('Final Output')
# st.image(final_output, caption='Styled Image', width=width, height=height)
if __name__ == "__main__":
app()
|