File size: 8,074 Bytes
aa91c42
fa2c889
aa91c42
 
fa2c889
8016ac3
dac8b6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8016ac3
aa91c42
 
dac8b6e
aa91c42
dac8b6e
 
 
 
 
 
aa91c42
 
dac8b6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34d2b7b
dac8b6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8016ac3
47f95ed
dac8b6e
47f95ed
 
 
dac8b6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8016ac3
47f95ed
8016ac3
dac8b6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa91c42
 
 
 
dac8b6e
aa91c42
dac8b6e
 
 
aa91c42
dac8b6e
 
 
 
 
 
 
aa91c42
fa2c889
aa91c42
fa2c889
 
dac8b6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa91c42
dac8b6e
aa91c42
 
fa2c889
dac8b6e
aa91c42
 
 
fa2c889
 
dac8b6e
 
 
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
import os
import cv2
import gradio as gr
import AnimeGANv3_src
import numpy as np
import logging
import onnxruntime as ort
import tempfile
import threading

# Logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(levelname)s - %(message)s"
)

# Check ONNX Runtime providers
AVAILABLE_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 frame
        using 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 -> BGR
        return 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 = None
            out = None
            save_path = None

            try:
                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.0

                frame_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:
                        break

                    stylized_frame = self.process_frame(
                        frame,
                        style_code,
                        det_face
                    )

                    # Preserve original video dimensions.
                    if (
                        stylized_frame.shape[1] != width
                        or 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_path

            except gr.Error:
                raise

            except Exception as error:
                logging.exception(
                    "AnimeGANv3 conversion failed."
                )

                if save_path and os.path.exists(save_path):
                    try:
                        os.remove(save_path)
                    except OSError:
                        pass

                raise 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()