Spaces:
Running
Running
Update app.py
Browse files3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261273 unmodified linesimport AnimeGANv3_srcimport numpy as npimport loggingimport onnxruntime as ort # Added this import# Set up logginglogging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')class AnimeGANv3:def __init__(self):os.makedirs('output', exist_ok=True)os.makedirs('frames', exist_ok=True)logging.info(f"Available ONNX Runtime providers: {ort.get_available_providers()}")if 'CUDAExecutionProvider' in ort.get_available_providers():logging.info("Running on GPU with CUDA")else:logging.info("Running on CPU")def process_frame(self, frame, style_code, det_face):frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)output = AnimeGANv3_src.Convert(frame_rgb, style_code, det_face)return output[:, :, ::-1]def inference(self, video_path, style, if_face=None):logging.info(f"Starting inference: video={video_path}, style={style}, face_detection={if_face}")try:style_codes = {"AnimeGANv3_Arcane": "A","AnimeGANv3_Trump v1.0": "T","AnimeGANv3_Shinkai": "S","AnimeGANv3_PortraitSketch": "P","AnimeGANv3_Hayao": "H","AnimeGANv3_Disney v1.0": "D","AnimeGANv3_JP_face v1.0": "J","AnimeGANv3_Kpop v2.0": "K",}style_code = style_codes.get(style, "U")det_face = if_face == "Yes"# Open videocap = 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))logging.info(f"Extracted {frame_count} frames at {fps} FPS to process")# Process in batchesbatch_size = 50 # Adjust based on testingsave_path = "output/out.mp4"fourcc = cv2.VideoWriter_fourcc(*'mp4v')width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))out = Noneframe_idx = 0while cap.isOpened():batch_frames = []for _ in range(batch_size):ret, frame = cap.read()if not ret:breakbatch_frames.append(frame)frame_idx += 1if not batch_frames:breakfor idx, frame in enumerate(batch_frames):stylized_frame = self.process_frame(frame, style_code, det_face)if out is None: # Initialize writer on first frameout = cv2.VideoWriter(save_path, fourcc, fps, (width, height))out.write(stylized_frame)logging.info(f"Processed frame {frame_idx - len(batch_frames) + idx + 1}/{frame_count}")cap.release()if out:out.release()else:raise Exception("No frames processed")logging.info(f"Video created: {save_path}")return save_pathexcept Exception as error:logging.error(f"Error: {str(error)}")return None# Create an instanceanime_gan = AnimeGANv3()# Gradio interfacetitle = "AnimeGANv3: Video to Anime Converter"description = r"""Upload a video to convert it into anime style using AnimeGANv3.<br>Select a style and choose whether to optimize for faces.<br>credits to fine tuner Asher_Chan<a href='https://github.com/TachibanaYoshino/AnimeGANv3' target='_blank'><b>AnimeGANv3 GitHub</b></a> |<a href='https://www.patreon.com/Asher_Chan' target='_blank'><b>Patreon</b></a>"""iface = gr.Interface(fn=anime_gan.inference,inputs=[gr.Video(label="Input Video"),gr.Dropdown(choices=['AnimeGANv3_Hayao','AnimeGANv3_Shinkai','AnimeGANv3_Arcane','AnimeGANv3_Trump v1.0','AnimeGANv3_Disney v1.0','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")],title=title,description=description,allow_flagging="never")iface.launch()3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103 unmodified linesimport AnimeGANv3_srcimport numpy as npimport loggingimport onnxruntime as ortimport tempfileimport threading# Logginglogging.basicConfig(level=logging.INFO,format="%(asctime)s - %(levelname)s - %(message)s")# Check ONNX Runtime providersAVAILABLE_PROVIDERS = ort.get_available_providers()logging.info("Available ONNX Runtime providers: %s",AVAILABLE_PROVIDERS)if "CUDAExecutionProvider" in AVAILABLE_PROVIDERS:logging.info("CUDA provider is available.")else:logging.warning("CUDA provider is NOT available. ""The model may run on CPU.")class AnimeGANv3:def __init__(self):os.makedirs("output", exist_ok=True)os.makedirs("frames", exist_ok=True)self.lock = threading.Lock()logging.info("AnimeGANv3 initialized.")def process_frame(self, frame, style_code, det_face):"""Convert a single OpenCV BGR frameusing the existing AnimeGANv3 module."""frame_rgb = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)output = AnimeGANv3_src.Convert(frame_rgb,style_code,det_face)if output is None:raise RuntimeError("AnimeGANv3 returned an empty frame.")if not isinstance(output, np.ndarray):output = np.asarray(output)if output.ndim != 3 or output.shape[2] != 3:raise RuntimeError(f"Unexpected output shape: {output.shape}")# RGB -> BGRreturn cv2.cvtColor(output,cv2.COLOR_RGB2BGR)def inference(self, video_path, style, if_face="No"):if not video_path:raise gr.Error("Please upload a video first.")style_codes = {"AnimeGANv3_Arcane": "A","AnimeGANv3_Trump v1.0": "T","AnimeGANv3_Shinkai": "S","AnimeGANv3_PortraitSketch": "P","AnimeGANv3_Hayao": "H","AnimeGANv3_Disney v1.0": "D","AnimeGANv3_JP_face v1.0": "J","AnimeGANv3_Kpop v2.0": "K",}style_code = style_codes.get(style)if style_code is None:raise gr.Error("Invalid AnimeGANv3 style.")det_face = if_face == "Yes"logging.info("Starting video conversion: style=%s, face_detection=%s",style,det_face)with self.lock:cap = Noneout = Nonesave_path = Nonetry:cap = cv2.VideoCapture(video_path)if not cap.isOpened():raise RuntimeError("Could not open the uploaded video.")fps = cap.get(cv2.CAP_PROP_FPS)if not np.isfinite(fps) or fps <= 0:fps = 25.0frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))if width <= 0 or height <= 0:raise RuntimeError("Could not determine video dimensions.")logging.info("Input: %s x %s, %.2f FPS, %s frames",width,height,fps,frame_count)# Create a unique output filename.fd, save_path = tempfile.mkstemp(suffix=".mp4",prefix="animeganv3_",dir="output")os.close(fd)fourcc = cv2.VideoWriter_fourcc(*"mp4v")out = cv2.VideoWriter(save_path,fourcc,fps,(width, height))if not out.isOpened():raise RuntimeError("Could not initialize video writer.")processed = 0# Read and process frames immediately.# Avoid storing batches of frames in RAM.while True:ret, frame = cap.read()if not ret:breakstylized_frame = self.process_frame(frame,style_code,det_face)# Preserve original video dimensions.if (stylized_frame.shape[1] != widthor stylized_frame.shape[0] != height):stylized_frame = cv2.resize(stylized_frame,(width, height),interpolation=cv2.INTER_LINEAR)out.write(stylized_frame)processed += 1# Log progress occasionally, not every frame.if processed % 100 == 0:logging.info("Processed %s / %s frames",processed,frame_count)if processed == 0:raise RuntimeError("No video frames were processed.")logging.info("Conversion complete: %s frames",processed)return save_pathexcept gr.Error:raiseexcept Exception as error:logging.exception("AnimeGANv3 conversion failed.")if save_path and os.path.exists(save_path):try:os.remove(save_path)except OSError:passraise gr.Error(f"Video conversion failed: {error}")finally:if cap is not None:cap.release()if out is not None:out.release()anime_gan = AnimeGANv3()title = "AnimeGANv3: Video to Anime Converter"description = r"""Upload a video to convert it into anime style using AnimeGANv3.<br>Select a style and choose whether to optimize for faces.<br>Credits to fine tuner Asher_Chan<br><a href="https://github.com/TachibanaYoshino/AnimeGANv3"target="_blank"><b>AnimeGANv3 GitHub</b></a> |<a href="https://www.patreon.com/Asher_Chan"target="_blank"><b>Patreon</b></a>"""iface = gr.Interface(fn=anime_gan.inference,inputs=[gr.Video(label="Input Video"),gr.Dropdown(choices=["AnimeGANv3_Hayao","AnimeGANv3_Shinkai","AnimeGANv3_Arcane","AnimeGANv3_Trump v1.0","AnimeGANv3_Disney v1.0","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")],title=title,description=description,allow_flagging="never")if __name__ == "__main__":iface.queue().launch()
app.py+269-86