|
from diffusers_helper.hf_login import login |
|
|
|
import os |
|
import threading |
|
import time |
|
import requests |
|
from requests.adapters import HTTPAdapter |
|
from urllib3.util.retry import Retry |
|
import json |
|
|
|
os.environ['HF_HOME'] = os.path.abspath(os.path.realpath(os.path.join(os.path.dirname(__file__), './hf_download'))) |
|
|
|
|
|
translations = { |
|
"en": { |
|
"title": "FramePack - Image to Video Generation", |
|
"upload_image": "Upload Image", |
|
"prompt": "Prompt", |
|
"quick_prompts": "Quick Prompts", |
|
"start_generation": "Generate", |
|
"stop_generation": "Stop", |
|
"use_teacache": "Use TeaCache", |
|
"teacache_info": "Faster speed, but may result in slightly worse finger and hand generation.", |
|
"negative_prompt": "Negative Prompt", |
|
"seed": "Seed", |
|
"video_length": "Video Length (max 5 seconds)", |
|
"latent_window": "Latent Window Size", |
|
"steps": "Inference Steps", |
|
"steps_info": "Changing this value is not recommended.", |
|
"cfg_scale": "CFG Scale", |
|
"distilled_cfg": "Distilled CFG Scale", |
|
"distilled_cfg_info": "Changing this value is not recommended.", |
|
"cfg_rescale": "CFG Rescale", |
|
"gpu_memory": "GPU Memory Preservation (GB) (larger means slower)", |
|
"gpu_memory_info": "Set this to a larger value if you encounter OOM errors. Larger values cause slower speed.", |
|
"next_latents": "Next Latents", |
|
"generated_video": "Generated Video", |
|
"sampling_note": "Note: Due to reversed sampling, ending actions will be generated before starting actions. If the starting action is not in the video, please wait, it will be generated later.", |
|
"error_message": "Error", |
|
"processing_error": "Processing error", |
|
"network_error": "Network connection is unstable, model download timed out. Please try again later.", |
|
"memory_error": "GPU memory insufficient, please try increasing GPU memory preservation value or reduce video length.", |
|
"model_error": "Failed to load model, possibly due to network issues or high server load. Please try again later.", |
|
"partial_video": "Processing error, but partial video has been generated", |
|
"processing_interrupt": "Processing was interrupted, but partial video has been generated" |
|
}, |
|
"ja": { |
|
"title": "FramePack - 画像から動画生成", |
|
"upload_image": "画像をアップロード", |
|
"prompt": "プロンプト", |
|
"quick_prompts": "クイックプロンプト一覧", |
|
"start_generation": "生成開始", |
|
"stop_generation": "停止", |
|
"use_teacache": "TeaCacheを使用", |
|
"teacache_info": "処理速度が速くなりますが、指や手の生成品質が若干低下する可能性があります。", |
|
"negative_prompt": "ネガティブプロンプト", |
|
"seed": "シード値", |
|
"video_length": "動画の長さ(最大5秒)", |
|
"latent_window": "潜在窓サイズ", |
|
"steps": "推論ステップ数", |
|
"steps_info": "この値の変更は推奨されません。", |
|
"cfg_scale": "CFGスケール", |
|
"distilled_cfg": "蒸留CFGスケール", |
|
"distilled_cfg_info": "この値の変更は推奨されません。", |
|
"cfg_rescale": "CFGリスケール", |
|
"gpu_memory": "GPU推論保存メモリ(GB)(値が大きいほど処理が遅くなります)", |
|
"gpu_memory_info": "OOMエラーが発生した場合は、この値を大きくしてください。値が大きいほど処理が遅くなります。", |
|
"next_latents": "次の潜在変数", |
|
"generated_video": "生成された動画", |
|
"sampling_note": "注意:逆順サンプリングのため、終了動作が開始動作より先に生成されます。開始動作が動画に表示されていない場合は、しばらくお待ちください。後で生成されます。", |
|
"error_message": "エラーメッセージ", |
|
"processing_error": "処理中にエラーが発生しました", |
|
"network_error": "ネットワーク接続が不安定です。モデルのダウンロードがタイムアウトしました。後ほど再試行してください。", |
|
"memory_error": "GPUメモリが不足しています。GPU推論保存メモリの値を大きくするか、動画の長さを短くしてください。", |
|
"model_error": "モデルの読み込みに失敗しました。ネットワークの問題やサーバー負荷が高い可能性があります。後ほど再試行してください。", |
|
"partial_video": "処理中にエラーが発生しましたが、部分的な動画は生成されています", |
|
"processing_interrupt": "処理が中断されましたが、部分的な動画は生成されています" |
|
} |
|
} |
|
|
|
|
|
def get_translation(key, lang="en"): |
|
if lang in translations and key in translations[lang]: |
|
return translations[lang][key] |
|
|
|
return translations["en"].get(key, key) |
|
|
|
|
|
current_language = "en" |
|
|
|
|
|
def switch_language(): |
|
global current_language |
|
current_language = "ja" if current_language == "en" else "en" |
|
return current_language |
|
|
|
import gradio as gr |
|
import torch |
|
import traceback |
|
import einops |
|
import safetensors.torch as sf |
|
import numpy as np |
|
import math |
|
|
|
|
|
IN_HF_SPACE = os.environ.get('SPACE_ID') is not None |
|
|
|
|
|
GPU_AVAILABLE = False |
|
GPU_INITIALIZED = False |
|
last_update_time = time.time() |
|
|
|
|
|
if IN_HF_SPACE: |
|
try: |
|
import spaces |
|
print("Hugging Face Space環境内で実行中、spacesモジュールをインポートしました") |
|
|
|
|
|
try: |
|
GPU_AVAILABLE = torch.cuda.is_available() |
|
print(f"GPU利用可能: {GPU_AVAILABLE}") |
|
if GPU_AVAILABLE: |
|
print(f"GPUデバイス名: {torch.cuda.get_device_name(0)}") |
|
print(f"GPUメモリ: {torch.cuda.get_device_properties(0).total_memory / 1e9} GB") |
|
|
|
|
|
test_tensor = torch.zeros(1, device='cuda') |
|
test_tensor = test_tensor + 1 |
|
del test_tensor |
|
print("GPUテスト操作に成功しました") |
|
else: |
|
print("警告: CUDAが利用可能と報告されていますが、GPUデバイスが検出されませんでした") |
|
except Exception as e: |
|
GPU_AVAILABLE = False |
|
print(f"GPU確認中にエラーが発生しました: {e}") |
|
print("CPUモードで実行します") |
|
except ImportError: |
|
print("spacesモジュールのインポートに失敗しました。Hugging Face Space環境外かもしれません") |
|
GPU_AVAILABLE = torch.cuda.is_available() |
|
|
|
from PIL import Image |
|
from diffusers import AutoencoderKLHunyuanVideo |
|
from transformers import LlamaModel, CLIPTextModel, LlamaTokenizerFast, CLIPTokenizer |
|
from diffusers_helper.hunyuan import encode_prompt_conds, vae_decode, vae_encode, vae_decode_fake |
|
from diffusers_helper.utils import save_bcthw_as_mp4, crop_or_pad_yield_mask, soft_append_bcthw, resize_and_center_crop, state_dict_weighted_merge, state_dict_offset_merge, generate_timestamp |
|
from diffusers_helper.models.hunyuan_video_packed import HunyuanVideoTransformer3DModelPacked |
|
from diffusers_helper.pipelines.k_diffusion_hunyuan import sample_hunyuan |
|
from diffusers_helper.memory import cpu, gpu, get_cuda_free_memory_gb, move_model_to_device_with_memory_preservation, offload_model_from_device_for_memory_preservation, fake_diffusers_current_device, DynamicSwapInstaller, unload_complete_models, load_model_as_complete, IN_HF_SPACE as MEMORY_IN_HF_SPACE |
|
from diffusers_helper.thread_utils import AsyncStream, async_run |
|
from diffusers_helper.gradio.progress_bar import make_progress_bar_css, make_progress_bar_html |
|
from transformers import SiglipImageProcessor, SiglipVisionModel |
|
from diffusers_helper.clip_vision import hf_clip_vision_encode |
|
from diffusers_helper.bucket_tools import find_nearest_bucket |
|
|
|
outputs_folder = './outputs/' |
|
os.makedirs(outputs_folder, exist_ok=True) |
|
|
|
|
|
if not IN_HF_SPACE: |
|
|
|
try: |
|
if torch.cuda.is_available(): |
|
free_mem_gb = get_cuda_free_memory_gb(gpu) |
|
print(f'空きVRAM {free_mem_gb} GB') |
|
else: |
|
free_mem_gb = 6.0 |
|
print("CUDAが利用できません。デフォルトのメモリ設定を使用します") |
|
except Exception as e: |
|
free_mem_gb = 6.0 |
|
print(f"CUDAメモリ取得中にエラーが発生しました: {e}、デフォルトのメモリ設定を使用します") |
|
|
|
high_vram = free_mem_gb > 60 |
|
print(f'高VRAM モード: {high_vram}') |
|
else: |
|
|
|
print("Spaces環境でデフォルトのメモリ設定を使用します") |
|
try: |
|
if GPU_AVAILABLE: |
|
free_mem_gb = torch.cuda.get_device_properties(0).total_memory / 1e9 * 0.9 |
|
high_vram = free_mem_gb > 10 |
|
else: |
|
free_mem_gb = 6.0 |
|
high_vram = False |
|
except Exception as e: |
|
print(f"GPUメモリ取得中にエラーが発生しました: {e}") |
|
free_mem_gb = 6.0 |
|
high_vram = False |
|
|
|
print(f'GPUメモリ: {free_mem_gb:.2f} GB, 高VRAMモード: {high_vram}') |
|
|
|
|
|
models = {} |
|
cpu_fallback_mode = not GPU_AVAILABLE |
|
|
|
|
|
def load_models(): |
|
global models, cpu_fallback_mode, GPU_INITIALIZED |
|
|
|
if GPU_INITIALIZED: |
|
print("モデルはすでに読み込まれています。重複読み込みをスキップします") |
|
return models |
|
|
|
print("モデルの読み込みを開始しています...") |
|
|
|
try: |
|
|
|
device = 'cuda' if GPU_AVAILABLE and not cpu_fallback_mode else 'cpu' |
|
model_device = 'cpu' |
|
|
|
|
|
dtype = torch.float16 if GPU_AVAILABLE else torch.float32 |
|
transformer_dtype = torch.bfloat16 if GPU_AVAILABLE else torch.float32 |
|
|
|
print(f"使用デバイス: {device}, モデル精度: {dtype}, Transformer精度: {transformer_dtype}") |
|
|
|
|
|
try: |
|
text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=dtype).to(model_device) |
|
text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=dtype).to(model_device) |
|
tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer') |
|
tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2') |
|
vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=dtype).to(model_device) |
|
|
|
feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor') |
|
image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=dtype).to(model_device) |
|
|
|
transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained('lllyasviel/FramePackI2V_HY', torch_dtype=transformer_dtype).to(model_device) |
|
|
|
print("すべてのモデルの読み込みに成功しました") |
|
except Exception as e: |
|
print(f"モデル読み込み中にエラーが発生しました: {e}") |
|
print("精度を下げて再試行します...") |
|
|
|
|
|
dtype = torch.float32 |
|
transformer_dtype = torch.float32 |
|
cpu_fallback_mode = True |
|
|
|
text_encoder = LlamaModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder', torch_dtype=dtype).to('cpu') |
|
text_encoder_2 = CLIPTextModel.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='text_encoder_2', torch_dtype=dtype).to('cpu') |
|
tokenizer = LlamaTokenizerFast.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer') |
|
tokenizer_2 = CLIPTokenizer.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='tokenizer_2') |
|
vae = AutoencoderKLHunyuanVideo.from_pretrained("hunyuanvideo-community/HunyuanVideo", subfolder='vae', torch_dtype=dtype).to('cpu') |
|
|
|
feature_extractor = SiglipImageProcessor.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='feature_extractor') |
|
image_encoder = SiglipVisionModel.from_pretrained("lllyasviel/flux_redux_bfl", subfolder='image_encoder', torch_dtype=dtype).to('cpu') |
|
|
|
transformer = HunyuanVideoTransformer3DModelPacked.from_pretrained('tori29umai/FramePackI2V_HY_rotate_landscape', torch_dtype=transformer_dtype).to('cpu') |
|
|
|
print("CPUモードですべてのモデルの読み込みに成功しました") |
|
|
|
vae.eval() |
|
text_encoder.eval() |
|
text_encoder_2.eval() |
|
image_encoder.eval() |
|
transformer.eval() |
|
|
|
if not high_vram or cpu_fallback_mode: |
|
vae.enable_slicing() |
|
vae.enable_tiling() |
|
|
|
transformer.high_quality_fp32_output_for_inference = True |
|
print('transformer.high_quality_fp32_output_for_inference = True') |
|
|
|
|
|
if not cpu_fallback_mode: |
|
transformer.to(dtype=transformer_dtype) |
|
vae.to(dtype=dtype) |
|
image_encoder.to(dtype=dtype) |
|
text_encoder.to(dtype=dtype) |
|
text_encoder_2.to(dtype=dtype) |
|
|
|
vae.requires_grad_(False) |
|
text_encoder.requires_grad_(False) |
|
text_encoder_2.requires_grad_(False) |
|
image_encoder.requires_grad_(False) |
|
transformer.requires_grad_(False) |
|
|
|
if torch.cuda.is_available() and not cpu_fallback_mode: |
|
try: |
|
if not high_vram: |
|
|
|
DynamicSwapInstaller.install_model(transformer, device=device) |
|
DynamicSwapInstaller.install_model(text_encoder, device=device) |
|
else: |
|
text_encoder.to(device) |
|
text_encoder_2.to(device) |
|
image_encoder.to(device) |
|
vae.to(device) |
|
transformer.to(device) |
|
print(f"モデルを{device}デバイスに移動することに成功しました") |
|
except Exception as e: |
|
print(f"モデルを{device}に移動中にエラーが発生しました: {e}") |
|
print("CPUモードにフォールバックします") |
|
cpu_fallback_mode = True |
|
|
|
|
|
models = { |
|
'text_encoder': text_encoder, |
|
'text_encoder_2': text_encoder_2, |
|
'tokenizer': tokenizer, |
|
'tokenizer_2': tokenizer_2, |
|
'vae': vae, |
|
'feature_extractor': feature_extractor, |
|
'image_encoder': image_encoder, |
|
'transformer': transformer |
|
} |
|
|
|
GPU_INITIALIZED = True |
|
print(f"モデルの読み込みが完了しました。実行モード: {'CPU' if cpu_fallback_mode else 'GPU'}") |
|
return models |
|
except Exception as e: |
|
print(f"モデル読み込みプロセスでエラーが発生しました: {e}") |
|
traceback.print_exc() |
|
|
|
|
|
error_info = { |
|
"error": str(e), |
|
"traceback": traceback.format_exc(), |
|
"cuda_available": torch.cuda.is_available(), |
|
"device": "cpu" if cpu_fallback_mode else "cuda", |
|
} |
|
|
|
|
|
try: |
|
with open(os.path.join(outputs_folder, "error_log.txt"), "w") as f: |
|
f.write(str(error_info)) |
|
except: |
|
pass |
|
|
|
|
|
cpu_fallback_mode = True |
|
return {} |
|
|
|
|
|
|
|
if IN_HF_SPACE and 'spaces' in globals() and GPU_AVAILABLE: |
|
try: |
|
@spaces.GPU |
|
def initialize_models(): |
|
"""@spaces.GPU装飾子内でモデルを初期化""" |
|
global GPU_INITIALIZED |
|
try: |
|
result = load_models() |
|
GPU_INITIALIZED = True |
|
return result |
|
except Exception as e: |
|
print(f"spaces.GPUを使用したモデル初期化中にエラーが発生しました: {e}") |
|
traceback.print_exc() |
|
global cpu_fallback_mode |
|
cpu_fallback_mode = True |
|
|
|
return load_models() |
|
except Exception as e: |
|
print(f"spaces.GPU装飾子の作成中にエラーが発生しました: {e}") |
|
|
|
def initialize_models(): |
|
return load_models() |
|
|
|
|
|
|
|
def get_models(): |
|
"""モデルを取得し、まだ読み込まれていない場合は読み込む""" |
|
global models, GPU_INITIALIZED |
|
|
|
|
|
model_loading_key = "__model_loading__" |
|
|
|
if not models: |
|
|
|
if model_loading_key in globals(): |
|
print("モデルは現在読み込み中です。お待ちください...") |
|
|
|
import time |
|
start_wait = time.time() |
|
while not models and model_loading_key in globals(): |
|
time.sleep(0.5) |
|
|
|
if time.time() - start_wait > 60: |
|
print("モデル読み込み待機がタイムアウトしました") |
|
break |
|
|
|
if models: |
|
return models |
|
|
|
try: |
|
|
|
globals()[model_loading_key] = True |
|
|
|
if IN_HF_SPACE and 'spaces' in globals() and GPU_AVAILABLE and not cpu_fallback_mode: |
|
try: |
|
print("@spaces.GPU装飾子を使用してモデルを読み込みます") |
|
models = initialize_models() |
|
except Exception as e: |
|
print(f"GPU装飾子を使用したモデル読み込みに失敗しました: {e}") |
|
print("直接モデルを読み込みます") |
|
models = load_models() |
|
else: |
|
print("モデルを直接読み込みます") |
|
models = load_models() |
|
except Exception as e: |
|
print(f"モデル読み込み中に予期しないエラーが発生しました: {e}") |
|
traceback.print_exc() |
|
|
|
models = {} |
|
finally: |
|
|
|
if model_loading_key in globals(): |
|
del globals()[model_loading_key] |
|
|
|
return models |
|
|
|
|
|
stream = AsyncStream() |
|
|
|
|
|
@torch.no_grad() |
|
def worker(input_image, prompt, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache): |
|
global last_update_time |
|
last_update_time = time.time() |
|
|
|
|
|
total_second_length = min(total_second_length, 5.0) |
|
|
|
|
|
try: |
|
models = get_models() |
|
if not models: |
|
error_msg = "モデルの読み込みに失敗しました。詳細情報はログを確認してください" |
|
print(error_msg) |
|
stream.output_queue.push(('error', error_msg)) |
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
text_encoder = models['text_encoder'] |
|
text_encoder_2 = models['text_encoder_2'] |
|
tokenizer = models['tokenizer'] |
|
tokenizer_2 = models['tokenizer_2'] |
|
vae = models['vae'] |
|
feature_extractor = models['feature_extractor'] |
|
image_encoder = models['image_encoder'] |
|
transformer = models['transformer'] |
|
except Exception as e: |
|
error_msg = f"モデル取得中にエラーが発生しました: {e}" |
|
print(error_msg) |
|
traceback.print_exc() |
|
stream.output_queue.push(('error', error_msg)) |
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
|
|
device = 'cuda' if GPU_AVAILABLE and not cpu_fallback_mode else 'cpu' |
|
print(f"推論に使用するデバイス: {device}") |
|
|
|
|
|
if cpu_fallback_mode: |
|
print("CPUモードではより軽量なパラメータを使用します") |
|
|
|
latent_window_size = min(latent_window_size, 5) |
|
steps = min(steps, 15) |
|
total_second_length = min(total_second_length, 2.0) |
|
|
|
total_latent_sections = (total_second_length * 30) / (latent_window_size * 4) |
|
total_latent_sections = int(max(round(total_latent_sections), 1)) |
|
|
|
job_id = generate_timestamp() |
|
last_output_filename = None |
|
history_pixels = None |
|
history_latents = None |
|
total_generated_latent_frames = 0 |
|
|
|
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, '開始中 ...')))) |
|
|
|
try: |
|
|
|
if not high_vram and not cpu_fallback_mode: |
|
try: |
|
unload_complete_models( |
|
text_encoder, text_encoder_2, image_encoder, vae, transformer |
|
) |
|
except Exception as e: |
|
print(f"モデルのアンロード中にエラーが発生しました: {e}") |
|
|
|
|
|
|
|
last_update_time = time.time() |
|
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'テキストエンコーディング中 ...')))) |
|
|
|
try: |
|
if not high_vram and not cpu_fallback_mode: |
|
fake_diffusers_current_device(text_encoder, device) |
|
load_model_as_complete(text_encoder_2, target_device=device) |
|
|
|
llama_vec, clip_l_pooler = encode_prompt_conds(prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2) |
|
|
|
if cfg == 1: |
|
llama_vec_n, clip_l_pooler_n = torch.zeros_like(llama_vec), torch.zeros_like(clip_l_pooler) |
|
else: |
|
llama_vec_n, clip_l_pooler_n = encode_prompt_conds(n_prompt, text_encoder, text_encoder_2, tokenizer, tokenizer_2) |
|
|
|
llama_vec, llama_attention_mask = crop_or_pad_yield_mask(llama_vec, length=512) |
|
llama_vec_n, llama_attention_mask_n = crop_or_pad_yield_mask(llama_vec_n, length=512) |
|
except Exception as e: |
|
error_msg = f"テキストエンコーディング中にエラーが発生しました: {e}" |
|
print(error_msg) |
|
traceback.print_exc() |
|
stream.output_queue.push(('error', error_msg)) |
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
|
|
last_update_time = time.time() |
|
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, '画像処理中 ...')))) |
|
|
|
try: |
|
H, W, C = input_image.shape |
|
height, width = find_nearest_bucket(H, W, resolution=640) |
|
|
|
|
|
if cpu_fallback_mode: |
|
height = min(height, 320) |
|
width = min(width, 320) |
|
|
|
input_image_np = resize_and_center_crop(input_image, target_width=width, target_height=height) |
|
|
|
Image.fromarray(input_image_np).save(os.path.join(outputs_folder, f'{job_id}.png')) |
|
|
|
input_image_pt = torch.from_numpy(input_image_np).float() / 127.5 - 1 |
|
input_image_pt = input_image_pt.permute(2, 0, 1)[None, :, None] |
|
except Exception as e: |
|
error_msg = f"画像処理中にエラーが発生しました: {e}" |
|
print(error_msg) |
|
traceback.print_exc() |
|
stream.output_queue.push(('error', error_msg)) |
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
|
|
last_update_time = time.time() |
|
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'VAEエンコーディング中 ...')))) |
|
|
|
try: |
|
if not high_vram and not cpu_fallback_mode: |
|
load_model_as_complete(vae, target_device=device) |
|
|
|
start_latent = vae_encode(input_image_pt, vae) |
|
except Exception as e: |
|
error_msg = f"VAEエンコーディング中にエラーが発生しました: {e}" |
|
print(error_msg) |
|
traceback.print_exc() |
|
stream.output_queue.push(('error', error_msg)) |
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
|
|
last_update_time = time.time() |
|
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'CLIP Visionエンコーディング中 ...')))) |
|
|
|
try: |
|
if not high_vram and not cpu_fallback_mode: |
|
load_model_as_complete(image_encoder, target_device=device) |
|
|
|
image_encoder_output = hf_clip_vision_encode(input_image_np, feature_extractor, image_encoder) |
|
image_encoder_last_hidden_state = image_encoder_output.last_hidden_state |
|
except Exception as e: |
|
error_msg = f"CLIP Visionエンコーディング中にエラーが発生しました: {e}" |
|
print(error_msg) |
|
traceback.print_exc() |
|
stream.output_queue.push(('error', error_msg)) |
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
|
|
try: |
|
llama_vec = llama_vec.to(transformer.dtype) |
|
llama_vec_n = llama_vec_n.to(transformer.dtype) |
|
clip_l_pooler = clip_l_pooler.to(transformer.dtype) |
|
clip_l_pooler_n = clip_l_pooler_n.to(transformer.dtype) |
|
image_encoder_last_hidden_state = image_encoder_last_hidden_state.to(transformer.dtype) |
|
except Exception as e: |
|
error_msg = f"データ型変換中にエラーが発生しました: {e}" |
|
print(error_msg) |
|
traceback.print_exc() |
|
stream.output_queue.push(('error', error_msg)) |
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
|
|
last_update_time = time.time() |
|
stream.output_queue.push(('progress', (None, '', make_progress_bar_html(0, 'サンプリング開始 ...')))) |
|
|
|
rnd = torch.Generator("cpu").manual_seed(seed) |
|
num_frames = latent_window_size * 4 - 3 |
|
|
|
try: |
|
history_latents = torch.zeros(size=(1, 16, 1 + 2 + 16, height // 8, width // 8), dtype=torch.float32).cpu() |
|
history_pixels = None |
|
total_generated_latent_frames = 0 |
|
except Exception as e: |
|
error_msg = f"履歴状態の初期化中にエラーが発生しました: {e}" |
|
print(error_msg) |
|
traceback.print_exc() |
|
stream.output_queue.push(('error', error_msg)) |
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
latent_paddings = reversed(range(total_latent_sections)) |
|
|
|
if total_latent_sections > 4: |
|
|
|
|
|
|
|
|
|
|
|
latent_paddings = [3] + [2] * (total_latent_sections - 3) + [1, 0] |
|
|
|
for latent_padding in latent_paddings: |
|
last_update_time = time.time() |
|
is_last_section = latent_padding == 0 |
|
latent_padding_size = latent_padding * latent_window_size |
|
|
|
if stream.input_queue.top() == 'end': |
|
|
|
if history_pixels is not None and total_generated_latent_frames > 0: |
|
try: |
|
output_filename = os.path.join(outputs_folder, f'{job_id}_final_{total_generated_latent_frames}.mp4') |
|
save_bcthw_as_mp4(history_pixels, output_filename, fps=30) |
|
stream.output_queue.push(('file', output_filename)) |
|
except Exception as e: |
|
print(f"最終動画保存中にエラーが発生しました: {e}") |
|
|
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
print(f'latent_padding_size = {latent_padding_size}, is_last_section = {is_last_section}') |
|
|
|
try: |
|
indices = torch.arange(0, sum([1, latent_padding_size, latent_window_size, 1, 2, 16])).unsqueeze(0) |
|
clean_latent_indices_pre, blank_indices, latent_indices, clean_latent_indices_post, clean_latent_2x_indices, clean_latent_4x_indices = indices.split([1, latent_padding_size, latent_window_size, 1, 2, 16], dim=1) |
|
clean_latent_indices = torch.cat([clean_latent_indices_pre, clean_latent_indices_post], dim=1) |
|
|
|
clean_latents_pre = start_latent.to(history_latents) |
|
clean_latents_post, clean_latents_2x, clean_latents_4x = history_latents[:, :, :1 + 2 + 16, :, :].split([1, 2, 16], dim=2) |
|
clean_latents = torch.cat([clean_latents_pre, clean_latents_post], dim=2) |
|
except Exception as e: |
|
error_msg = f"サンプリングデータ準備中にエラーが発生しました: {e}" |
|
print(error_msg) |
|
traceback.print_exc() |
|
|
|
if last_output_filename: |
|
stream.output_queue.push(('file', last_output_filename)) |
|
continue |
|
|
|
if not high_vram and not cpu_fallback_mode: |
|
try: |
|
unload_complete_models() |
|
move_model_to_device_with_memory_preservation(transformer, target_device=device, preserved_memory_gb=gpu_memory_preservation) |
|
except Exception as e: |
|
print(f"transformerをGPUに移動中にエラーが発生しました: {e}") |
|
|
|
|
|
if use_teacache and not cpu_fallback_mode: |
|
try: |
|
transformer.initialize_teacache(enable_teacache=True, num_steps=steps) |
|
except Exception as e: |
|
print(f"teacache初期化中にエラーが発生しました: {e}") |
|
|
|
transformer.initialize_teacache(enable_teacache=False) |
|
else: |
|
transformer.initialize_teacache(enable_teacache=False) |
|
|
|
def callback(d): |
|
global last_update_time |
|
last_update_time = time.time() |
|
|
|
try: |
|
|
|
print(f"【デバッグ】コールバック関数: ステップ {d['i']}, 停止信号のチェック") |
|
try: |
|
queue_top = stream.input_queue.top() |
|
print(f"【デバッグ】コールバック関数: キュー先頭信号 = {queue_top}") |
|
|
|
if queue_top == 'end': |
|
print("【デバッグ】コールバック関数: 停止信号を検出、中断準備中...") |
|
try: |
|
stream.output_queue.push(('end', None)) |
|
print("【デバッグ】コールバック関数: 出力キューにend信号を正常に送信") |
|
except Exception as e: |
|
print(f"【デバッグ】コールバック関数: 出力キューにend信号送信中にエラー: {e}") |
|
|
|
print("【デバッグ】コールバック関数: KeyboardInterrupt例外を投げる準備") |
|
raise KeyboardInterrupt('ユーザーによるタスク停止') |
|
except Exception as e: |
|
print(f"【デバッグ】コールバック関数: キュー先頭信号チェック中にエラー: {e}") |
|
|
|
preview = d['denoised'] |
|
preview = vae_decode_fake(preview) |
|
|
|
preview = (preview * 255.0).detach().cpu().numpy().clip(0, 255).astype(np.uint8) |
|
preview = einops.rearrange(preview, 'b c t h w -> (b h) (t w) c') |
|
|
|
current_step = d['i'] + 1 |
|
percentage = int(100.0 * current_step / steps) |
|
hint = f'サンプリング中 {current_step}/{steps}' |
|
desc = f'総生成フレーム数: {int(max(0, total_generated_latent_frames * 4 - 3))}, 動画長: {max(0, (total_generated_latent_frames * 4 - 3) / 30) :.2f} 秒 (FPS-30). 動画を現在拡張中...' |
|
stream.output_queue.push(('progress', (preview, desc, make_progress_bar_html(percentage, hint)))) |
|
except KeyboardInterrupt as e: |
|
|
|
print(f"【デバッグ】コールバック関数: KeyboardInterruptをキャッチ: {e}") |
|
print("【デバッグ】コールバック関数: 中断例外を再スロー、サンプリング関数に伝播") |
|
raise |
|
except Exception as e: |
|
print(f"【デバッグ】コールバック関数でエラー: {e}") |
|
|
|
print(f"【デバッグ】コールバック関数: ステップ {d['i']} 完了") |
|
return |
|
|
|
try: |
|
sampling_start_time = time.time() |
|
print(f"サンプリング開始、デバイス: {device}, データ型: {transformer.dtype}, TeaCache使用: {use_teacache and not cpu_fallback_mode}") |
|
|
|
try: |
|
print("【デバッグ】sample_hunyuanサンプリングプロセス開始") |
|
generated_latents = sample_hunyuan( |
|
transformer=transformer, |
|
sampler='unipc', |
|
width=width, |
|
height=height, |
|
frames=num_frames, |
|
real_guidance_scale=cfg, |
|
distilled_guidance_scale=gs, |
|
guidance_rescale=rs, |
|
|
|
num_inference_steps=steps, |
|
generator=rnd, |
|
prompt_embeds=llama_vec, |
|
prompt_embeds_mask=llama_attention_mask, |
|
prompt_poolers=clip_l_pooler, |
|
negative_prompt_embeds=llama_vec_n, |
|
negative_prompt_embeds_mask=llama_attention_mask_n, |
|
negative_prompt_poolers=clip_l_pooler_n, |
|
device=device, |
|
dtype=transformer.dtype, |
|
image_embeddings=image_encoder_last_hidden_state, |
|
latent_indices=latent_indices, |
|
clean_latents=clean_latents, |
|
clean_latent_indices=clean_latent_indices, |
|
clean_latents_2x=clean_latents_2x, |
|
clean_latent_2x_indices=clean_latent_2x_indices, |
|
clean_latents_4x=clean_latents_4x, |
|
clean_latent_4x_indices=clean_latent_4x_indices, |
|
callback=callback, |
|
) |
|
|
|
print(f"【デバッグ】サンプリング完了、所要時間: {time.time() - sampling_start_time:.2f}秒") |
|
except KeyboardInterrupt as e: |
|
|
|
print(f"【デバッグ】KeyboardInterruptをキャッチ: {e}") |
|
print("【デバッグ】ユーザーによるサンプリングプロセス中断、中断ロジック処理中") |
|
|
|
|
|
if last_output_filename: |
|
print(f"【デバッグ】部分的に生成された動画あり: {last_output_filename}、この動画を返します") |
|
stream.output_queue.push(('file', last_output_filename)) |
|
error_msg = "ユーザーにより生成プロセスが中断されましたが、部分的な動画は生成されています" |
|
else: |
|
print("【デバッグ】部分的に生成された動画なし、中断メッセージを返します") |
|
error_msg = "ユーザーにより生成プロセスが中断され、動画は生成されていません" |
|
|
|
print(f"【デバッグ】エラーメッセージを送信: {error_msg}") |
|
stream.output_queue.push(('error', error_msg)) |
|
print("【デバッグ】end信号を送信") |
|
stream.output_queue.push(('end', None)) |
|
print("【デバッグ】中断処理完了、リターン") |
|
return |
|
except Exception as e: |
|
print(f"サンプリングプロセス中にエラーが発生しました: {e}") |
|
traceback.print_exc() |
|
|
|
|
|
if last_output_filename: |
|
stream.output_queue.push(('file', last_output_filename)) |
|
|
|
|
|
error_msg = f"サンプリングプロセス中にエラーが発生しましたが、部分的に生成された動画を返します: {e}" |
|
stream.output_queue.push(('error', error_msg)) |
|
else: |
|
|
|
error_msg = f"サンプリングプロセス中にエラーが発生し、動画を生成できませんでした: {e}" |
|
stream.output_queue.push(('error', error_msg)) |
|
|
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
try: |
|
if is_last_section: |
|
generated_latents = torch.cat([start_latent.to(generated_latents), generated_latents], dim=2) |
|
|
|
total_generated_latent_frames += int(generated_latents.shape[2]) |
|
history_latents = torch.cat([generated_latents.to(history_latents), history_latents], dim=2) |
|
except Exception as e: |
|
error_msg = f"生成された潜在変数の処理中にエラーが発生しました: {e}" |
|
print(error_msg) |
|
traceback.print_exc() |
|
|
|
if last_output_filename: |
|
stream.output_queue.push(('file', last_output_filename)) |
|
stream.output_queue.push(('error', error_msg)) |
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
if not high_vram and not cpu_fallback_mode: |
|
try: |
|
offload_model_from_device_for_memory_preservation(transformer, target_device=device, preserved_memory_gb=8) |
|
load_model_as_complete(vae, target_device=device) |
|
except Exception as e: |
|
print(f"モデルメモリ管理中にエラーが発生しました: {e}") |
|
|
|
|
|
try: |
|
real_history_latents = history_latents[:, :, :total_generated_latent_frames, :, :] |
|
except Exception as e: |
|
error_msg = f"履歴潜在変数の処理中にエラーが発生しました: {e}" |
|
print(error_msg) |
|
|
|
if last_output_filename: |
|
stream.output_queue.push(('file', last_output_filename)) |
|
continue |
|
|
|
try: |
|
vae_start_time = time.time() |
|
print(f"VAEデコード開始、潜在変数形状: {real_history_latents.shape}") |
|
|
|
if history_pixels is None: |
|
history_pixels = vae_decode(real_history_latents, vae).cpu() |
|
else: |
|
section_latent_frames = (latent_window_size * 2 + 1) if is_last_section else (latent_window_size * 2) |
|
overlapped_frames = latent_window_size * 4 - 3 |
|
|
|
current_pixels = vae_decode(real_history_latents[:, :, :section_latent_frames], vae).cpu() |
|
history_pixels = soft_append_bcthw(current_pixels, history_pixels, overlapped_frames) |
|
|
|
print(f"VAEデコード完了、所要時間: {time.time() - vae_start_time:.2f}秒") |
|
|
|
if not high_vram and not cpu_fallback_mode: |
|
try: |
|
unload_complete_models() |
|
except Exception as e: |
|
print(f"モデルのアンロード中にエラーが発生しました: {e}") |
|
|
|
output_filename = os.path.join(outputs_folder, f'{job_id}_{total_generated_latent_frames}.mp4') |
|
|
|
save_start_time = time.time() |
|
save_bcthw_as_mp4(history_pixels, output_filename, fps=30) |
|
print(f"動画保存完了、所要時間: {time.time() - save_start_time:.2f}秒") |
|
|
|
print(f'デコード完了。現在の潜在変数形状 {real_history_latents.shape}; ピクセル形状 {history_pixels.shape}') |
|
|
|
last_output_filename = output_filename |
|
stream.output_queue.push(('file', output_filename)) |
|
except Exception as e: |
|
print(f"動画のデコードまたは保存中にエラーが発生しました: {e}") |
|
traceback.print_exc() |
|
|
|
|
|
if last_output_filename: |
|
stream.output_queue.push(('file', last_output_filename)) |
|
|
|
|
|
error_msg = f"動画のデコードまたは保存中にエラーが発生しました: {e}" |
|
stream.output_queue.push(('error', error_msg)) |
|
|
|
|
|
continue |
|
|
|
if is_last_section: |
|
break |
|
except Exception as e: |
|
print(f"【デバッグ】処理中にエラーが発生しました: {e}, タイプ: {type(e)}") |
|
print(f"【デバッグ】エラー詳細:") |
|
traceback.print_exc() |
|
|
|
|
|
if isinstance(e, KeyboardInterrupt): |
|
print("【デバッグ】外部KeyboardInterrupt例外を検出") |
|
|
|
if not high_vram and not cpu_fallback_mode: |
|
try: |
|
print("【デバッグ】リソース解放のためモデルをアンロード") |
|
unload_complete_models( |
|
text_encoder, text_encoder_2, image_encoder, vae, transformer |
|
) |
|
print("【デバッグ】モデルのアンロードに成功") |
|
except Exception as unload_error: |
|
print(f"【デバッグ】モデルのアンロード中にエラー: {unload_error}") |
|
pass |
|
|
|
|
|
if last_output_filename: |
|
print(f"【デバッグ】外部例外処理: 生成済み部分動画を返す {last_output_filename}") |
|
stream.output_queue.push(('file', last_output_filename)) |
|
else: |
|
print("【デバッグ】外部例外処理: 生成済み動画が見つかりません") |
|
|
|
|
|
error_msg = f"処理中にエラーが発生しました: {e}" |
|
print(f"【デバッグ】外部例外処理: エラーメッセージを送信: {error_msg}") |
|
stream.output_queue.push(('error', error_msg)) |
|
|
|
|
|
print("【デバッグ】ワーカー関数終了、end信号を送信") |
|
stream.output_queue.push(('end', None)) |
|
return |
|
|
|
|
|
|
|
if IN_HF_SPACE and 'spaces' in globals(): |
|
@spaces.GPU |
|
def process_with_gpu(input_image, prompt, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache): |
|
global stream |
|
assert input_image is not None, '入力画像がありません!' |
|
|
|
|
|
yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True) |
|
|
|
try: |
|
stream = AsyncStream() |
|
|
|
|
|
async_run(worker, input_image, prompt, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache) |
|
|
|
output_filename = None |
|
prev_output_filename = None |
|
error_message = None |
|
|
|
|
|
while True: |
|
try: |
|
flag, data = stream.output_queue.next() |
|
|
|
if flag == 'file': |
|
output_filename = data |
|
prev_output_filename = output_filename |
|
|
|
yield output_filename, gr.update(), gr.update(), '', gr.update(interactive=False), gr.update(interactive=True) |
|
|
|
if flag == 'progress': |
|
preview, desc, html = data |
|
|
|
yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True) |
|
|
|
if flag == 'error': |
|
error_message = data |
|
print(f"エラーメッセージを受信: {error_message}") |
|
|
|
|
|
if flag == 'end': |
|
|
|
if output_filename is None and prev_output_filename is not None: |
|
output_filename = prev_output_filename |
|
|
|
|
|
if error_message: |
|
error_html = create_error_html(error_message) |
|
yield output_filename, gr.update(visible=False), gr.update(), error_html, gr.update(interactive=True), gr.update(interactive=False) |
|
else: |
|
|
|
yield output_filename, gr.update(visible=False), gr.update(), '', gr.update(interactive=True), gr.update(interactive=False) |
|
break |
|
except Exception as e: |
|
print(f"出力処理中にエラーが発生しました: {e}") |
|
|
|
current_time = time.time() |
|
if current_time - last_update_time > 60: |
|
print(f"処理がフリーズした可能性があります。{current_time - last_update_time:.1f}秒間更新がありません") |
|
|
|
|
|
if prev_output_filename: |
|
error_html = create_error_html("処理がタイムアウトしましたが、部分的な動画は生成されています", is_timeout=True) |
|
yield prev_output_filename, gr.update(visible=False), gr.update(), error_html, gr.update(interactive=True), gr.update(interactive=False) |
|
else: |
|
error_html = create_error_html(f"処理がタイムアウトしました: {e}", is_timeout=True) |
|
yield None, gr.update(visible=False), gr.update(), error_html, gr.update(interactive=True), gr.update(interactive=False) |
|
break |
|
|
|
except Exception as e: |
|
print(f"処理の開始中にエラーが発生しました: {e}") |
|
traceback.print_exc() |
|
error_msg = str(e) |
|
|
|
error_html = create_error_html(error_msg) |
|
yield None, gr.update(visible=False), gr.update(), error_html, gr.update(interactive=True), gr.update(interactive=False) |
|
|
|
process = process_with_gpu |
|
else: |
|
def process(input_image, prompt, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache): |
|
global stream |
|
assert input_image is not None, '入力画像がありません!' |
|
|
|
|
|
yield None, None, '', '', gr.update(interactive=False), gr.update(interactive=True) |
|
|
|
try: |
|
stream = AsyncStream() |
|
|
|
|
|
async_run(worker, input_image, prompt, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache) |
|
|
|
output_filename = None |
|
prev_output_filename = None |
|
error_message = None |
|
|
|
|
|
while True: |
|
try: |
|
flag, data = stream.output_queue.next() |
|
|
|
if flag == 'file': |
|
output_filename = data |
|
prev_output_filename = output_filename |
|
|
|
yield output_filename, gr.update(), gr.update(), '', gr.update(interactive=False), gr.update(interactive=True) |
|
|
|
if flag == 'progress': |
|
preview, desc, html = data |
|
|
|
yield gr.update(), gr.update(visible=True, value=preview), desc, html, gr.update(interactive=False), gr.update(interactive=True) |
|
|
|
if flag == 'error': |
|
error_message = data |
|
print(f"エラーメッセージを受信: {error_message}") |
|
|
|
|
|
if flag == 'end': |
|
|
|
if output_filename is None and prev_output_filename is not None: |
|
output_filename = prev_output_filename |
|
|
|
|
|
if error_message: |
|
error_html = create_error_html(error_message) |
|
yield output_filename, gr.update(visible=False), gr.update(), error_html, gr.update(interactive=True), gr.update(interactive=False) |
|
else: |
|
|
|
yield output_filename, gr.update(visible=False), gr.update(), '', gr.update(interactive=True), gr.update(interactive=False) |
|
break |
|
except Exception as e: |
|
print(f"出力処理中にエラーが発生しました: {e}") |
|
|
|
current_time = time.time() |
|
if current_time - last_update_time > 60: |
|
print(f"処理がフリーズした可能性があります。{current_time - last_update_time:.1f}秒間更新がありません") |
|
|
|
|
|
if prev_output_filename: |
|
error_html = create_error_html("処理がタイムアウトしましたが、部分的な動画は生成されています", is_timeout=True) |
|
yield prev_output_filename, gr.update(visible=False), gr.update(), error_html, gr.update(interactive=True), gr.update(interactive=False) |
|
else: |
|
error_html = create_error_html(f"処理がタイムアウトしました: {e}", is_timeout=True) |
|
yield None, gr.update(visible=False), gr.update(), error_html, gr.update(interactive=True), gr.update(interactive=False) |
|
break |
|
|
|
except Exception as e: |
|
print(f"処理の開始中にエラーが発生しました: {e}") |
|
traceback.print_exc() |
|
error_msg = str(e) |
|
|
|
error_html = create_error_html(error_msg) |
|
yield None, gr.update(visible=False), gr.update(), error_html, gr.update(interactive=True), gr.update(interactive=False) |
|
|
|
|
|
def end_process(): |
|
"""生成プロセスを停止する関数 - キューに'end'信号を送信して生成を中断します""" |
|
print("【デバッグ】ユーザーが停止ボタンをクリックしました。停止信号を送信中...") |
|
|
|
if 'stream' in globals() and stream is not None: |
|
|
|
try: |
|
current_top = stream.input_queue.top() |
|
print(f"【デバッグ】現在のキュー先頭信号: {current_top}") |
|
except Exception as e: |
|
print(f"【デバッグ】キュー状態確認中にエラー: {e}") |
|
|
|
|
|
try: |
|
stream.input_queue.push('end') |
|
print("【デバッグ】キューにend信号を正常に送信しました") |
|
|
|
|
|
try: |
|
current_top_after = stream.input_queue.top() |
|
print(f"【デバッグ】送信後のキュー先頭信号: {current_top_after}") |
|
except Exception as e: |
|
print(f"【デバッグ】送信後のキュー状態確認中にエラー: {e}") |
|
|
|
except Exception as e: |
|
print(f"【デバッグ】キューへのend信号送信に失敗: {e}") |
|
else: |
|
print("【デバッグ】警告: streamが初期化されていないため、停止信号を送信できません") |
|
return None |
|
|
|
|
|
quick_prompts = [ |
|
'The camera smoothly orbits around the center of the scene, keeping the center point fixed and always in view', |
|
] |
|
quick_prompts = [[x] for x in quick_prompts] |
|
|
|
|
|
|
|
def make_custom_css(): |
|
progress_bar_css = make_progress_bar_css() |
|
|
|
responsive_css = """ |
|
/* 基本レスポンシブ設定 */ |
|
#app-container { |
|
max-width: 100%; |
|
margin: 0 auto; |
|
} |
|
|
|
/* 言語切り替えボタンのスタイル */ |
|
#language-toggle { |
|
position: fixed; |
|
top: 10px; |
|
right: 10px; |
|
z-index: 1000; |
|
background-color: rgba(0, 0, 0, 0.7); |
|
color: white; |
|
border: none; |
|
border-radius: 4px; |
|
padding: 5px 10px; |
|
cursor: pointer; |
|
font-size: 14px; |
|
} |
|
|
|
/* ページタイトルのスタイル */ |
|
h1 { |
|
font-size: 2rem; |
|
text-align: center; |
|
margin-bottom: 1rem; |
|
} |
|
|
|
/* ボタンのスタイル */ |
|
.start-btn, .stop-btn { |
|
min-height: 45px; |
|
font-size: 1rem; |
|
} |
|
|
|
/* モバイルデバイスのスタイル - 小画面 */ |
|
@media (max-width: 768px) { |
|
h1 { |
|
font-size: 1.5rem; |
|
margin-bottom: 0.5rem; |
|
} |
|
|
|
/* 単一カラムレイアウト */ |
|
.mobile-full-width { |
|
flex-direction: column !important; |
|
} |
|
|
|
.mobile-full-width > .gr-block { |
|
min-width: 100% !important; |
|
flex-grow: 1; |
|
} |
|
|
|
/* 動画サイズの調整 */ |
|
.video-container { |
|
height: auto !important; |
|
} |
|
|
|
/* ボタンサイズの調整 */ |
|
.button-container button { |
|
min-height: 50px; |
|
font-size: 1rem; |
|
touch-action: manipulation; |
|
} |
|
|
|
/* スライダーの調整 */ |
|
.slider-container input[type="range"] { |
|
height: 30px; |
|
} |
|
} |
|
|
|
/* タブレットデバイスのスタイル */ |
|
@media (min-width: 769px) and (max-width: 1024px) { |
|
.tablet-adjust { |
|
width: 48% !important; |
|
} |
|
} |
|
|
|
/* ダークモードサポート */ |
|
@media (prefers-color-scheme: dark) { |
|
.dark-mode-text { |
|
color: #f0f0f0; |
|
} |
|
|
|
.dark-mode-bg { |
|
background-color: #2a2a2a; |
|
} |
|
} |
|
|
|
/* アクセシビリティの向上 */ |
|
button, input, select, textarea { |
|
font-size: 16px; /* iOSでの拡大を防止 */ |
|
} |
|
|
|
/* タッチ操作の最適化 */ |
|
button, .interactive-element { |
|
min-height: 44px; |
|
min-width: 44px; |
|
} |
|
|
|
/* コントラストの向上 */ |
|
.high-contrast { |
|
color: #fff; |
|
background-color: #000; |
|
} |
|
|
|
/* プログレスバーのスタイル強化 */ |
|
.progress-container { |
|
margin-top: 10px; |
|
margin-bottom: 10px; |
|
} |
|
|
|
/* エラーメッセージのスタイル */ |
|
#error-message { |
|
color: #ff4444; |
|
font-weight: bold; |
|
padding: 10px; |
|
border-radius: 4px; |
|
margin-top: 10px; |
|
} |
|
|
|
/* エラーコンテナの正しい表示 */ |
|
.error-message { |
|
background-color: rgba(255, 0, 0, 0.1); |
|
padding: 10px; |
|
border-radius: 4px; |
|
margin-top: 10px; |
|
border: 1px solid #ffcccc; |
|
} |
|
|
|
/* 多言語エラーメッセージの処理 */ |
|
.error-msg-en, .error-msg-ja { |
|
font-weight: bold; |
|
} |
|
|
|
/* エラーアイコン */ |
|
.error-icon { |
|
color: #ff4444; |
|
font-size: 18px; |
|
margin-right: 8px; |
|
} |
|
|
|
/* 空のエラーメッセージが背景とボーダーを表示しないことを確認 */ |
|
#error-message:empty { |
|
background-color: transparent; |
|
border: none; |
|
padding: 0; |
|
margin: 0; |
|
} |
|
|
|
/* Gradioのデフォルトエラー表示の修正 */ |
|
.error { |
|
display: none !important; |
|
} |
|
""" |
|
|
|
|
|
combined_css = progress_bar_css + responsive_css |
|
return combined_css |
|
|
|
|
|
css = make_custom_css() |
|
block = gr.Blocks(css=css).queue() |
|
with block: |
|
|
|
gr.HTML(""" |
|
<div id="app-container"> |
|
<button id="language-toggle" onclick="toggleLanguage()">日本語/English</button> |
|
</div> |
|
<script> |
|
// グローバル変数、現在の言語を保存 |
|
window.currentLang = "ja"; |
|
|
|
// 言語切り替え関数 |
|
function toggleLanguage() { |
|
window.currentLang = window.currentLang === "en" ? "ja" : "en"; |
|
|
|
// data-i18n属性を持つすべての要素を取得 |
|
const elements = document.querySelectorAll('[data-i18n]'); |
|
|
|
// 言語に基づいて切り替え |
|
elements.forEach(el => { |
|
const key = el.getAttribute('data-i18n'); |
|
const translations = { |
|
"en": { |
|
"title": "FramePack - Image to Video Generation", |
|
"upload_image": "Upload Image", |
|
"prompt": "Prompt", |
|
"quick_prompts": "Quick Prompts", |
|
"start_generation": "Generate", |
|
"stop_generation": "Stop", |
|
"use_teacache": "Use TeaCache", |
|
"teacache_info": "Faster speed, but may result in slightly worse finger and hand generation.", |
|
"negative_prompt": "Negative Prompt", |
|
"seed": "Seed", |
|
"video_length": "Video Length (max 5 seconds)", |
|
"latent_window": "Latent Window Size", |
|
"steps": "Inference Steps", |
|
"steps_info": "Changing this value is not recommended.", |
|
"cfg_scale": "CFG Scale", |
|
"distilled_cfg": "Distilled CFG Scale", |
|
"distilled_cfg_info": "Changing this value is not recommended.", |
|
"cfg_rescale": "CFG Rescale", |
|
"gpu_memory": "GPU Memory Preservation (GB) (larger means slower)", |
|
"gpu_memory_info": "Set this to a larger value if you encounter OOM errors. Larger values cause slower speed.", |
|
"next_latents": "Next Latents", |
|
"generated_video": "Generated Video", |
|
"sampling_note": "Note: Due to reversed sampling, ending actions will be generated before starting actions. If the starting action is not in the video, please wait, it will be generated later.", |
|
"error_message": "Error", |
|
"processing_error": "Processing error", |
|
"network_error": "Network connection is unstable, model download timed out. Please try again later.", |
|
"memory_error": "GPU memory insufficient, please try increasing GPU memory preservation value or reduce video length.", |
|
"model_error": "Failed to load model, possibly due to network issues or high server load. Please try again later.", |
|
"partial_video": "Processing error, but partial video has been generated", |
|
"processing_interrupt": "Processing was interrupted, but partial video has been generated" |
|
}, |
|
"ja": { |
|
"title": "FramePack - 画像から動画生成", |
|
"upload_image": "画像をアップロード", |
|
"prompt": "プロンプト", |
|
"quick_prompts": "クイックプロンプト一覧", |
|
"start_generation": "生成開始", |
|
"stop_generation": "停止", |
|
"use_teacache": "TeaCacheを使用", |
|
"teacache_info": "処理速度が速くなりますが、指や手の生成品質が若干低下する可能性があります。", |
|
"negative_prompt": "ネガティブプロンプト", |
|
"seed": "シード値", |
|
"video_length": "動画の長さ(最大5秒)", |
|
"latent_window": "潜在窓サイズ", |
|
"steps": "推論ステップ数", |
|
"steps_info": "この値の変更は推奨されません。", |
|
"cfg_scale": "CFGスケール", |
|
"distilled_cfg": "蒸留CFGスケール", |
|
"distilled_cfg_info": "この値の変更は推奨されません。", |
|
"cfg_rescale": "CFGリスケール", |
|
"gpu_memory": "GPU推論保存メモリ(GB)(値が大きいほど処理が遅くなります)", |
|
"gpu_memory_info": "OOMエラーが発生した場合は、この値を大きくしてください。値が大きいほど処理が遅くなります。", |
|
"next_latents": "次の潜在変数", |
|
"generated_video": "生成された動画", |
|
"sampling_note": "注意:逆順サンプリングのため、終了動作が開始動作より先に生成されます。開始動作が動画に表示されていない場合は、しばらくお待ちください。後で生成されます。", |
|
"error_message": "エラーメッセージ", |
|
"processing_error": "処理中にエラーが発生しました", |
|
"network_error": "ネットワーク接続が不安定です。モデルのダウンロードがタイムアウトしました。後ほど再試行してください。", |
|
"memory_error": "GPUメモリが不足しています。GPU推論保存メモリの値を大きくするか、動画の長さを短くしてください。", |
|
"model_error": "モデルの読み込みに失敗しました。ネットワークの問題やサーバー負荷が高い可能性があります。後ほど再試行してください。", |
|
"partial_video": "処理中にエラーが発生しましたが、部分的な動画は生成されています", |
|
"processing_interrupt": "処理が中断されましたが、部分的な動画は生成されています" |
|
} |
|
}; |
|
|
|
if (translations[window.currentLang] && translations[window.currentLang][key]) { |
|
// 要素の種類に基づいてテキストを設定 |
|
if (el.tagName === 'BUTTON') { |
|
el.textContent = translations[window.currentLang][key]; |
|
} else if (el.tagName === 'LABEL') { |
|
el.textContent = translations[window.currentLang][key]; |
|
} else { |
|
el.innerHTML = translations[window.currentLang][key]; |
|
} |
|
} |
|
}); |
|
|
|
// ページ上の他の要素を更新 |
|
document.querySelectorAll('.bilingual-label').forEach(el => { |
|
const enText = el.getAttribute('data-en'); |
|
const jaText = el.getAttribute('data-ja'); |
|
el.textContent = window.currentLang === 'en' ? enText : jaText; |
|
}); |
|
|
|
// エラーメッセージコンテナの処理 |
|
document.querySelectorAll('[data-lang]').forEach(el => { |
|
el.style.display = el.getAttribute('data-lang') === window.currentLang ? 'block' : 'none'; |
|
}); |
|
} |
|
|
|
// ページロード後の初期化 |
|
document.addEventListener('DOMContentLoaded', function() { |
|
// 国際化が必要な要素にdata-i18n属性を追加 |
|
setTimeout(() => { |
|
// すべてのラベルにi18n属性を追加 |
|
const labelMap = { |
|
"Upload Image": "upload_image", |
|
"画像をアップロード": "upload_image", |
|
"Prompt": "prompt", |
|
"プロンプト": "prompt", |
|
"Quick Prompts": "quick_prompts", |
|
"クイックプロンプト一覧": "quick_prompts", |
|
"Generate": "start_generation", |
|
"生成開始": "start_generation", |
|
"Stop": "stop_generation", |
|
"停止": "stop_generation", |
|
// 他のラベルマッピングを追加... |
|
}; |
|
|
|
// ラベルの処理 |
|
document.querySelectorAll('label, span, button').forEach(el => { |
|
const text = el.textContent.trim(); |
|
if (labelMap[text]) { |
|
el.setAttribute('data-i18n', labelMap[text]); |
|
} |
|
}); |
|
|
|
// 特定の要素にi18n属性を追加 |
|
const titleEl = document.querySelector('h1'); |
|
if (titleEl) titleEl.setAttribute('data-i18n', 'title'); |
|
|
|
// ラベル言語の初期化 |
|
toggleLanguage(); |
|
}, 1000); |
|
}); |
|
</script> |
|
""") |
|
|
|
|
|
gr.HTML("<h1 data-i18n='title'>FramePack - 画像から動画生成</h1>") |
|
|
|
|
|
with gr.Row(elem_classes="mobile-full-width"): |
|
with gr.Column(scale=1, elem_classes="mobile-full-width"): |
|
|
|
input_image = gr.Image( |
|
sources='upload', |
|
type="numpy", |
|
label="画像をアップロード / Upload Image", |
|
elem_id="input-image", |
|
height=320 |
|
) |
|
|
|
|
|
prompt = gr.Textbox( |
|
label="プロンプト / Prompt", |
|
value='', |
|
elem_id="prompt-input" |
|
) |
|
|
|
|
|
example_quick_prompts = gr.Dataset( |
|
samples=quick_prompts, |
|
label='クイックプロンプト一覧 / Quick Prompts', |
|
samples_per_page=1000, |
|
components=[prompt] |
|
) |
|
example_quick_prompts.click(lambda x: x[0], inputs=[example_quick_prompts], outputs=prompt, show_progress=False, queue=False) |
|
|
|
|
|
with gr.Row(elem_classes="button-container"): |
|
start_button = gr.Button( |
|
value="生成開始 / Generate", |
|
elem_classes="start-btn", |
|
elem_id="start-button", |
|
variant="primary" |
|
) |
|
|
|
end_button = gr.Button( |
|
value="停止 / Stop", |
|
elem_classes="stop-btn", |
|
elem_id="stop-button", |
|
interactive=False |
|
) |
|
|
|
|
|
with gr.Group(): |
|
use_teacache = gr.Checkbox( |
|
label='TeaCacheを使用 / Use TeaCache', |
|
value=True, |
|
info='処理速度が速くなりますが、指や手の生成品質が若干低下する可能性があります。 / Faster speed, but may result in slightly worse finger and hand generation.' |
|
) |
|
|
|
n_prompt = gr.Textbox(label="ネガティブプロンプト / Negative Prompt", value="", visible=False) |
|
|
|
seed = gr.Number( |
|
label="シード値 / Seed", |
|
value=31337, |
|
precision=0 |
|
) |
|
|
|
|
|
with gr.Group(elem_classes="slider-container"): |
|
total_second_length = gr.Slider( |
|
label="動画の長さ(最大5秒) / Video Length (max 5 seconds)", |
|
minimum=1, |
|
maximum=5, |
|
value=5, |
|
step=0.1 |
|
) |
|
|
|
latent_window_size = gr.Slider( |
|
label="潜在窓サイズ / Latent Window Size", |
|
minimum=1, |
|
maximum=33, |
|
value=9, |
|
step=1, |
|
visible=False |
|
) |
|
|
|
steps = gr.Slider( |
|
label="推論ステップ数 / Inference Steps", |
|
minimum=1, |
|
maximum=100, |
|
value=25, |
|
step=1, |
|
info='この値の変更は推奨されません。 / Changing this value is not recommended.' |
|
) |
|
|
|
cfg = gr.Slider( |
|
label="CFGスケール / CFG Scale", |
|
minimum=1.0, |
|
maximum=32.0, |
|
value=1.0, |
|
step=0.01, |
|
visible=False |
|
) |
|
|
|
gs = gr.Slider( |
|
label="蒸留CFGスケール / Distilled CFG Scale", |
|
minimum=1.0, |
|
maximum=32.0, |
|
value=10.0, |
|
step=0.01, |
|
info='この値の変更は推奨されません。 / Changing this value is not recommended.' |
|
) |
|
|
|
rs = gr.Slider( |
|
label="CFGリスケール / CFG Rescale", |
|
minimum=0.0, |
|
maximum=1.0, |
|
value=0.0, |
|
step=0.01, |
|
visible=False |
|
) |
|
|
|
gpu_memory_preservation = gr.Slider( |
|
label="GPU推論保存メモリ(GB) / GPU Memory (GB)", |
|
minimum=6, |
|
maximum=128, |
|
value=6, |
|
step=0.1, |
|
info="OOMエラーが発生した場合は、この値を大きくしてください。値が大きいほど処理が遅くなります。 / Set this to a larger value if you encounter OOM errors. Larger values cause slower speed." |
|
) |
|
|
|
|
|
with gr.Column(scale=1, elem_classes="mobile-full-width"): |
|
|
|
preview_image = gr.Image( |
|
label="プレビュー / Preview", |
|
height=200, |
|
visible=False, |
|
elem_classes="preview-container" |
|
) |
|
|
|
|
|
result_video = gr.Video( |
|
label="生成された動画 / Generated Video", |
|
autoplay=True, |
|
show_share_button=True, |
|
height=512, |
|
loop=True, |
|
elem_classes="video-container", |
|
elem_id="result-video" |
|
) |
|
|
|
|
|
gr.HTML("<div data-i18n='sampling_note' class='note'>注意:逆順サンプリングのため、終了動作が開始動作より先に生成されます。開始動作が動画に表示されていない場合は、しばらくお待ちください。後で生成されます。</div>") |
|
|
|
|
|
with gr.Group(elem_classes="progress-container"): |
|
progress_desc = gr.Markdown('', elem_classes='no-generating-animation') |
|
progress_bar = gr.HTML('', elem_classes='no-generating-animation') |
|
|
|
|
|
error_message = gr.HTML('', elem_id='error-message', visible=True) |
|
|
|
|
|
ips = [input_image, prompt, n_prompt, seed, total_second_length, latent_window_size, steps, cfg, gs, rs, gpu_memory_preservation, use_teacache] |
|
|
|
|
|
start_button.click(fn=process, inputs=ips, outputs=[result_video, preview_image, progress_desc, progress_bar, start_button, end_button]) |
|
end_button.click(fn=end_process) |
|
|
|
|
|
block.launch() |
|
|
|
|
|
def create_error_html(error_msg, is_timeout=False): |
|
"""二言語のエラーメッセージHTMLを作成""" |
|
|
|
en_msg = "" |
|
ja_msg = "" |
|
|
|
if is_timeout: |
|
en_msg = "Processing timed out, but partial video may have been generated" if "部分的な動画" in error_msg else f"Processing timed out: {error_msg}" |
|
ja_msg = "処理がタイムアウトしましたが、部分的な動画は生成されている可能性があります" if "部分的な動画" in error_msg else f"処理がタイムアウトしました: {error_msg}" |
|
elif "モデル読み込み失敗" in error_msg: |
|
en_msg = "Failed to load models. The Space may be experiencing high traffic or GPU issues." |
|
ja_msg = "モデルの読み込みに失敗しました。Spaceの利用が集中しているか、GPU関連の問題が発生している可能性があります。" |
|
elif "GPU" in error_msg or "CUDA" in error_msg or "メモリ" in error_msg or "memory" in error_msg: |
|
en_msg = "GPU memory insufficient or GPU error. Try increasing GPU memory preservation value or reduce video length." |
|
ja_msg = "GPUメモリが不足しているかGPUエラーが発生しています。GPU推論保存メモリの値を大きくするか、動画の長さを短くしてください。" |
|
elif "サンプリング中にエラー" in error_msg: |
|
if "部分" in error_msg: |
|
en_msg = "Error during sampling process, but partial video has been generated." |
|
ja_msg = "サンプリング中にエラーが発生しましたが、部分的な動画は生成されています。" |
|
else: |
|
en_msg = "Error during sampling process. Unable to generate video." |
|
ja_msg = "サンプリング中にエラーが発生し、動画を生成できませんでした。" |
|
elif "モデルダウンロードタイムアウト" in error_msg or "ネットワーク接続不安定" in error_msg or "ReadTimeoutError" in error_msg or "ConnectionError" in error_msg: |
|
en_msg = "Network connection is unstable, model download timed out. Please try again later." |
|
ja_msg = "ネットワーク接続が不安定で、モデルのダウンロードがタイムアウトしました。後ほど再試行してください。" |
|
elif "VAE" in error_msg or "デコード" in error_msg or "decode" in error_msg: |
|
en_msg = "Error during video decoding or saving process. Try again with a different seed." |
|
ja_msg = "動画のデコードまたは保存中にエラーが発生しました。別のシード値で再試行してください。" |
|
else: |
|
en_msg = f"Processing error: {error_msg}" |
|
ja_msg = f"処理中にエラーが発生しました: {error_msg}" |
|
|
|
|
|
return f""" |
|
<div class="error-message" id="custom-error-container"> |
|
<div class="error-msg-en" data-lang="en"> |
|
<span class="error-icon">⚠️</span> {en_msg} |
|
</div> |
|
<div class="error-msg-ja" data-lang="ja"> |
|
<span class="error-icon">⚠️</span> {ja_msg} |
|
</div> |
|
</div> |
|
<script> |
|
// 現在の言語に基づいて適切なエラーメッセージを表示 |
|
(function() {{ |
|
const errorContainer = document.getElementById('custom-error-container'); |
|
if (errorContainer) {{ |
|
const currentLang = window.currentLang || 'ja'; // デフォルトは日本語 |
|
const errMsgs = errorContainer.querySelectorAll('[data-lang]'); |
|
errMsgs.forEach(msg => {{ |
|
msg.style.display = msg.getAttribute('data-lang') === currentLang ? 'block' : 'none'; |
|
}}); |
|
|
|
// GradioのデフォルトエラーUIが表示されないことを確認 |
|
const defaultErrorElements = document.querySelectorAll('.error'); |
|
defaultErrorElements.forEach(el => {{ |
|
el.style.display = 'none'; |
|
}}); |
|
}} |
|
}})(); |
|
</script> |
|
""" |