File size: 11,012 Bytes
b09e573
 
 
 
 
 
 
 
 
 
 
 
 
 
66c8ea4
b09e573
 
 
66c8ea4
b09e573
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from spandrel import ModelLoader
import torch
from pathlib import Path
from PIL import Image
import gradio as App
import numpy as np
import subprocess
import logging
import spaces
import time
import os
import gc
import io
import cv2

from gradio import themes
from rich.console import Console
from rich.logging import RichHandler

# ============================== #
#          Core Settings         #
# ============================== #

Theme = themes.Citrus(primary_hue='blue', radius_size=themes.sizes.radius_xxl)
ModelDir = Path('./Models')
TempDir = Path('./Temp')
os.environ['GRADIO_TEMP_DIR'] = str(TempDir)
ModelFileType = '.pth'

# ============================== #
#        Enhanced Logging        #
# ============================== #

logging.basicConfig(level=logging.INFO, format='%(message)s', datefmt='[%X]',
					handlers=[RichHandler(console=Console(), rich_tracebacks=True)])
Logger = logging.getLogger('Video2x')
logging.getLogger('httpx').setLevel(logging.WARNING)

# ============================== #
#      Device Configuration      #
# ============================== #

@spaces.GPU
def GetDeviceName():
	Device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
	Logger.info(f'βš™οΈ Using device: {Device}')
	return Device

Device = GetDeviceName()

# ============================== #
#      Optimized Functions       #
# ============================== #

def FormatTimeEstimate(Seconds):
	Hours = int(Seconds // 3600)
	Minutes = int((Seconds % 3600) // 60)
	Seconds = int(Seconds % 60)

	if Hours > 0:
		return f'{Hours}h {Minutes}m {Seconds}s'
	elif Minutes > 0:
		return f'{Minutes}m {Seconds}s'
	else:
		return f'{Seconds}s'

def ListModels():
	Models = sorted([File.name for File in ModelDir.glob('*' + ModelFileType) if File.is_file()])
	Logger.info(f'πŸ“š Found {len(Models)} Models In Directory')
	return Models

def LoadModel(ModelName):
	if Device.type == 'cuda':
		torch.cuda.empty_cache()
	Logger.info(f'πŸ”„ Loading model: {ModelName} onto {Device}')
	Model = ModelLoader().load_from_file(ModelDir / (ModelName + ModelFileType)).to(Device).eval() # Use .to(Device)
	Logger.info('βœ… Model Loaded Successfully')
	return Model

@spaces.GPU
def ProcessSingleFrame(OriginalImage, Model, TileGridSize):
	if TileGridSize > 1:
		Logger.info(f'🧩 Processing With Tile Grid {TileGridSize}x{TileGridSize}')
		Width, Height = OriginalImage.size
		TileWidth, TileHeight = Width // TileGridSize, Height // TileGridSize
		UpscaledTilesGrid = []

		for Row in range(TileGridSize):
			CurrentRowTiles = []
			for Col in range(TileGridSize):
				Tile = OriginalImage.crop((Col * TileWidth, Row * TileHeight,
										  (Col + 1) * TileWidth, (Row + 1) * TileHeight))
				TileTensor = torch.from_numpy(np.array(Tile)).permute(2, 0, 1).unsqueeze(0).float().to(Device) / 255.0

				with torch.no_grad():
					UpscaledTileTensor = Model(TileTensor)

				UpscaledTileNumpy = UpscaledTileTensor.squeeze(0).permute(1, 2, 0).cpu().numpy()
				CurrentRowTiles.append(Image.fromarray(np.uint8(UpscaledTileNumpy.clip(0.0, 1.0) * 255.0), mode='RGB'))
				del TileTensor, UpscaledTileTensor, UpscaledTileNumpy
			UpscaledTilesGrid.append(CurrentRowTiles)

		FirstTileWidth, FirstTileHeight = UpscaledTilesGrid[0][0].size
		UpscaledImage = Image.new('RGB', (FirstTileWidth * TileGridSize, FirstTileHeight * TileGridSize))

		for Row in range(TileGridSize):
			for Col in range(TileGridSize):
				UpscaledImage.paste(UpscaledTilesGrid[Row][Col], (Col * FirstTileWidth, Row * FirstTileHeight))
	else:
		TorchImage = torch.from_numpy(np.array(OriginalImage)).permute(2, 0, 1).unsqueeze(0).float().to(Device) / 255.0
		with torch.no_grad():
			ResultTensor = Model(TorchImage)
		ResultNumpy = ResultTensor.squeeze(0).permute(1, 2, 0).cpu().numpy()
		UpscaledImage = Image.fromarray(np.uint8(ResultNumpy.clip(0.0, 1.0) * 255.0), mode='RGB')
		del TorchImage, ResultTensor, ResultNumpy

	return UpscaledImage

@spaces.GPU
def Process(VideoInputPath, ModelName, FrameRateValue, TileGridSize, FileType, Progress=App.Progress()):
	# First yield should match the order of outputs in the click function
	yield None, App.update(interactive=False, value=None)

	if not VideoInputPath or not ModelName or not FileType:
		Logger.error('β›” Missing Inputs!')
		return None, None

	VideoPath = Path(VideoInputPath)
	OutputVideoPath = VideoPath.parent / f'{VideoPath.stem}_{Path(ModelName).stem}{"_Tiled" + str(TileGridSize) if TileGridSize > 1 else ""}{FileType}'

	# Load model
	Progress(0.0, 'πŸ”„ Loading Model')
	Model = LoadModel(ModelName)

	# Extract video info
	Logger.info(f'🎬 Extracting Video Information From {VideoPath.name}')
	VideoCapture = cv2.VideoCapture(str(VideoPath))
	FrameCount = int(VideoCapture.get(cv2.CAP_PROP_FRAME_COUNT))

	if not FrameRateValue:
		FrameRateValue = VideoCapture.get(cv2.CAP_PROP_FPS)

	Logger.info(f'🎞️ Processing {FrameCount} Frames At {FrameRateValue} FPS')

	# In-memory frames processing
	FrameBuffer = []
	AllFrames = []

	# Time tracking variables
	StartTime = time.time()
	FrameProcessingTime = None

	for FrameIndex in range(FrameCount):
		FrameStartTime = time.time()

		Success, Frame = VideoCapture.read()
		if not Success:
			Logger.warning(f'⚠️ Failed To Read Frame {FrameIndex}')
			continue

		# Convert from BGR to RGB
		OriginalImage = Image.fromarray(cv2.cvtColor(Frame, cv2.COLOR_BGR2RGB))
		UpscaledImage = ProcessSingleFrame(OriginalImage, Model, TileGridSize)

		# Store for preview
		ResizedOriginalImage = OriginalImage.resize(UpscaledImage.size, Image.Resampling.LANCZOS)
		AllFrames.append((ResizedOriginalImage, UpscaledImage.copy()))

		# Save to buffer for video output
		ImageBytes = io.BytesIO()
		UpscaledImage.save(ImageBytes, format='PNG')
		FrameBuffer.append(ImageBytes.getvalue())

		# Calculate time estimates
		CurrentFrameTime = time.time() - FrameStartTime

		if FrameIndex == 0:
			FrameProcessingTime = CurrentFrameTime
			Logger.info(f'⏱️ First Frame Took {FrameProcessingTime:.2f}s To Process')

		# Calculate remaining time based on average processing time so far
		ElapsedTime = time.time() - StartTime
		AverageTimePerFrame = ElapsedTime / (FrameIndex + 1)
		RemainingFrames = FrameCount - (FrameIndex + 1)
		EstimatedRemainingTime = RemainingFrames * AverageTimePerFrame

		# Format time estimates for display
		RemainingTimeFormatted = FormatTimeEstimate(EstimatedRemainingTime)

		Progress(
			(FrameIndex + 1) / FrameCount,
			f'πŸ”„ Frame {FrameIndex+1}/{FrameCount} | ETA: {RemainingTimeFormatted}'
		)

		del OriginalImage, UpscaledImage, ImageBytes
		gc.collect()

	VideoCapture.release()

	# Write frames to temporary files for ffmpeg
	Logger.info('πŸ’Ύ Preparing Frames For Video Encoding')
	os.makedirs(TempDir, exist_ok=True)

	for Index, FrameData in enumerate(FrameBuffer):
		with open(f'{TempDir}/Frame_{Index:06d}.png', 'wb') as f:
			f.write(FrameData)

	# Create video
	Progress(1.0, 'πŸŽ₯ Encoding Video')
	Logger.info('πŸŽ₯ Encoding Final Video')
	FfmpegCmd = f'ffmpeg -y -framerate {FrameRateValue} -i "{TempDir}/Frame_%06d.png" -c:v libx264 -pix_fmt yuv420p "{OutputVideoPath}" -hide_banner -loglevel error'
	subprocess.run(FfmpegCmd, shell=True, check=True)

	# Clean up
	for File in Path(TempDir).glob('Frame_*.png'):
		File.unlink()

	Logger.info(f'πŸŽ‰ Video Saved To: {OutputVideoPath}')

	# Update UI - return values directly in the order specified in the click function
	FirstFrame = AllFrames[0] if AllFrames else None
	DownloadValue = App.update(interactive=True, value=str(OutputVideoPath))
	yield FirstFrame, DownloadValue

	# Release resources
	del Model, FrameBuffer, AllFrames
	Progress(1.0, '🧹 Cleaning Up Resources')
	gc.collect()
	if Device.type == 'cuda':
		torch.cuda.empty_cache()
		Logger.info('🧹 CUDA Memory Cleaned Up')
	Logger.info('🧹 Model Unloaded')
	Progress(1.0, 'πŸ“¦ Done!')

# ============================== #
#          Streamlined UI        #
# ============================== #

with App.Blocks(title='Video Upscaler', theme=Theme, delete_cache=(60, 600)) as Interface:
	App.Markdown('# 🎞️ Video Upscaler')
	App.Markdown('''
			  Space created by [Hyphonical](https://huggingface.co/Hyphonical), this space uses several models from [styler00dollar/VSGAN-tensorrt-docker](https://github.com/styler00dollar/VSGAN-tensorrt-docker/releases/tag/models)
			  You may always request adding more models by opening a [new discussion](https://huggingface.co/spaces/Hyphonical/Video2x/discussions/new). The main program uses spandrel to load the models and ffmpeg to process the video.
			  You may run out of time using the ZeroGPU, you could clone the space or run it locally for better performance.
			  ''')

	with App.Row():
		with App.Column(scale=1):
			with App.Group():
				InputVideo = App.Video(label='Input Video', sources=['upload'], height=300)
				ModelList = ListModels()
				ModelNames = [Path(Model).stem for Model in ModelList]
				InputModel = App.Dropdown(choices=ModelNames, label='Select Model', value=ModelNames[0] if ModelNames else None)
				with App.Row():
					InputFrameRate = App.Slider(label='Frame Rate', minimum=1, maximum=60, value=23.976, step=0.001)
					InputTileGridSize = App.Slider(label='Tile Grid Size', minimum=1, maximum=6, value=1, step=1, show_reset_button=False)
				InputFileType = App.Dropdown(choices=['.mp4', '.mkv'], label='Output File Type', value='.mkv', interactive=True)
			SubmitButton = App.Button('πŸš€ Upscale Video')

		with App.Column(scale=1, show_progress=True):
			OutputSlider = App.ImageSlider(label='Output Preview', value=None, height=300)
			DownloadOutput = App.DownloadButton(label='πŸ’Ύ Download Video', interactive=False)
			with App.Accordion(label='πŸ“œ Instructions', open=False):
				App.Markdown('''
				### How To Use The Video Upscaler

				1.  **Upload A Video:** Begin by uploading your video file using the 'Input Video' section.
				2.  **Select A Model:** Choose an appropriate upscaling model from the 'Select Model' dropdown menu.
				3.  **Adjust Settings (Optional):**
				Modify the 'Frame Rate' slider if you want to change the output video's frame rate.
				Adjust the 'Tile Grid Size' for memory optimization. Larger models might require a higher grid size, but processing could be slower.
				4.  **Start Processing:** Click the 'πŸš€ Upscale Video' button to begin the upscaling process.
				5.  **Download The Result:** Once the process is complete, download the upscaled video using the 'πŸ’Ύ Download Video' button.

				> Tip: If you get a CUDA out of memory error, try increasing the Tile Grid Size. This will split the image into smaller tiles for processing, which can help reduce memory usage.
				''')

	SubmitButton.click(fn=Process, inputs=[InputVideo, InputModel, InputFrameRate, InputTileGridSize, InputFileType],
					 outputs=[OutputSlider, DownloadOutput])

if __name__ == '__main__':
	os.makedirs(ModelDir, exist_ok=True)
	os.makedirs(TempDir, exist_ok=True)
	Logger.info('πŸš€ Starting Video Upscaler')
	Interface.launch(pwa=True)