Spaces:
Running
Running
Update app.py
Browse files2 unmodified lines3456789101112132 unmodified lines161718192021229 unmodified lines323334353637383940414243444546474849505152535455565758596061626364656667686919 unmodified lines89909192939495962 unmodified linesimport gradio as grimport AnimeGANv3_srcimport numpy as npclass AnimeGANv3:def __init__(self):# Ensure the output directory existsos.makedirs('output', exist_ok=True)def process_frame(self, frame, style_code, det_face):"""Process a single frame with AnimeGANv3."""2 unmodified linesreturn output[:, :, ::-1] # Convert back to BGR for OpenCVdef inference(self, video_path, style, if_face=None):print(video_path, style, if_face)try:# Map style names to codesstyle_codes = {9 unmodified linesstyle_code = style_codes.get(style, "U")det_face = if_face == "Yes"# Open the input videocap = cv2.VideoCapture(video_path)if not cap.isOpened():raise Exception("Could not open video file")# Get video propertiesfps = cap.get(cv2.CAP_PROP_FPS)width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))print(f"Processing {frame_count} frames at {fps} FPS, {width}x{height}")# Set up video writersave_path = "output/out.mp4"fourcc = cv2.VideoWriter_fourcc(*'mp4v') # Use 'mp4v' codec for MP4out = cv2.VideoWriter(save_path, fourcc, fps, (width, height))# Process frameswhile True:ret, frame = cap.read()if not ret:breakprocessed_frame = self.process_frame(frame, style_code, det_face)out.write(processed_frame)# Release resourcescap.release()out.release()return save_pathexcept Exception as error:print('Error:', error)return None# Create an instance of the AnimeGANv3 class19 unmodified lines'AnimeGANv3_PortraitSketch','AnimeGANv3_JP_face v1.0','AnimeGANv3_Kpop v2.0',], label='AnimeGANv3 Style', value='AnimeGANv3_Arcane'), # Changed 'default' to 'value'gr.Radio(choices=["Yes", "No"], label='Extract face', value="No"), # Also updated here],outputs=[gr.Video(label="Output Video")2 unmodified lines34567891011121314151617182 unmodified lines212223242526279 unmodified lines37383940414243444546474849505152535455565758596061626364656667686970717273747576777879808119 unmodified lines1011021031041051061071082 unmodified linesimport gradio as grimport AnimeGANv3_srcimport numpy as npimport logging# Set up logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')class AnimeGANv3:def __init__(self):# Ensure directories existos.makedirs('output', exist_ok=True)os.makedirs('frames', exist_ok=True)def process_frame(self, frame, style_code, det_face):"""Process a single frame with AnimeGANv3."""2 unmodified linesreturn output[:, :, ::-1] # Convert back to BGR for OpenCVdef inference(self, video_path, style, if_face=None):logging.info(f"Starting inference: video={video_path}, style={style}, face_detection={if_face}")try:# Map style names to codesstyle_codes = {9 unmodified linesstyle_code = style_codes.get(style, "U")det_face = if_face == "Yes"# Open the input video and extract framescap = cv2.VideoCapture(video_path)if not cap.isOpened():raise Exception("Could not open video file")fps = cap.get(cv2.CAP_PROP_FPS)frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))frames = []while cap.isOpened():ret, frame = cap.read()if not ret:breakframes.append(frame)cap.release()logging.info(f"Extracted {frame_count} frames at {fps} FPS to process")# Process each frame and save as PNG with loggingfor idx, frame in enumerate(frames):stylized_frame = self.process_frame(frame, style_code, det_face)png_filename = f'frames/frame_{idx:04d}.png'cv2.imwrite(png_filename, stylized_frame)logging.info(f"Processed and saved frame {idx + 1}/{frame_count} as {png_filename}")logging.info("All frames processed and saved as PNGs")# Combine PNGs into video using ffmpegsave_path = "output/out.mp4"os.system(f"ffmpeg -framerate {fps} -i frames/frame_%04d.png -c:v libx264 -pix_fmt yuv420p {save_path} -y")# Check if the video was createdif not os.path.exists(save_path):raise Exception("Failed to create output video with ffmpeg")logging.info(f"Video created: {save_path}")return save_pathexcept Exception as error:logging.error(f"Error: {str(error)}")return None# Create an instance of the AnimeGANv3 class19 unmodified lines'AnimeGANv3_PortraitSketch','AnimeGANv3_JP_face v1.0','AnimeGANv3_Kpop v2.0',], label='AnimeGANv3 Style', value='AnimeGANv3_Arcane'),gr.Radio(choices=["Yes", "No"], label='Extract face', value="No"),],outputs=[gr.Video(label="Output Video")
app.py+33-21