Python
further ace step loading optim
DeepBeepMeepbb12bd3ed620
diff --git a/shared/gradio/audio_gallery.py b/shared/gradio/audio_gallery.pyindex 1fd9a7f..9fb444d 100644--- a/shared/gradio/audio_gallery.py+++ b/shared/gradio/audio_gallery.py@@ -4,6 +4,7 @@ from datetime import datetimeimport osimport jsonimport uuid+from collections import OrderedDictdef _get_selected_idx(audio_infos, selected_idx):@@ -30,6 +31,9 @@ class AudioGallery:update_only: If True, only render the inner HTML/Audio (internal use)"""+ _timestamp_cache = OrderedDict()+ _timestamp_cache_max_entries = 50+def __init__(self, audio_paths=None, selected_index=-1, max_thumbnails=10, height=400, label="Audio Gallery", update_only=False):self.audio_paths = audio_paths or []self.selected_index = selected_index@@ -392,6 +396,43 @@ AG.tryInstall();except Exception:return "0:00"+ @classmethod+ def _get_cached_creation_datetime(cls, audio_path):+ try:+ stat = os.stat(audio_path)+ cache_key = (audio_path, int(stat.st_size), int(stat.st_mtime))+ except Exception:+ return None++ cached_dt = cls._timestamp_cache.get(cache_key)+ if cached_dt is not None:+ cls._timestamp_cache.move_to_end(cache_key)+ return cached_dt++ dt = None+ try:+ from shared.utils.audio_metadata import read_audio_metadata, resolve_audio_creation_datetime+ wangp_metadata = read_audio_metadata(audio_path)+ dt = resolve_audio_creation_datetime(audio_path, wangp_metadata=wangp_metadata)+ except Exception:+ dt = None++ if dt is None:+ try:+ if os.name == "nt":+ ts = os.path.getctime(audio_path)+ else:+ stat = os.stat(audio_path)+ ts = stat.st_birthtime if hasattr(stat, "st_birthtime") else stat.st_mtime+ dt = datetime.fromtimestamp(ts)+ except Exception:+ return None++ cls._timestamp_cache[cache_key] = dt+ while len(cls._timestamp_cache) > cls._timestamp_cache_max_entries:+ cls._timestamp_cache.popitem(last=False)+ return dt+def _format_duration(self, seconds):"""Format duration in seconds to MM:SS format."""mins = int(seconds // 60)@@ -404,16 +445,17 @@ AG.tryInstall();basename = p.nameif not_found:- mtime = ""+ timestamp = ""date_str = "Deleted"time_str = "00:00:00"duration = "0:00"else:- # Get modification time- mtime = os.path.getmtime(audio_path)- dt = datetime.fromtimestamp(mtime)+ dt = self._get_cached_creation_datetime(audio_path)+ if dt is None:+ dt = datetime.fromtimestamp(os.path.getmtime(audio_path))date_str = dt.strftime("%Y-%m-%d")time_str = dt.strftime("%H:%M:%S")+ timestamp = dt.timestamp()# Get durationduration = self._get_audio_duration(audio_path)@@ -424,7 +466,7 @@ AG.tryInstall();"time": time_str,"duration": duration,"path": audio_path,- "timestamp": mtime,+ "timestamp": timestamp,}def _create_thumbnail_html(self, info, index, is_selected):diff --git a/shared/llm_engines/nanovllm/utils/loader.py b/shared/llm_engines/nanovllm/utils/loader.pyindex 92bf8b1..0a5b490 100644--- a/shared/llm_engines/nanovllm/utils/loader.py+++ b/shared/llm_engines/nanovllm/utils/loader.py@@ -187,7 +187,8 @@ def load_model(file_weights = weight_store._file_to_weight_names.get(file, [])if not file_weights:continue- with safe_open(file, "pt", "cpu", writable_tensors=False) as f:+ with safe_open(file, "pt", "cuda", writable_tensors = False, streaming = True) as f:+ file_weights = f.reorder_for_streaming(file_weights)for weight_name in file_weights:tensor = f.get_tensor(weight_name)if clone_loaded_tensors:@@ -196,6 +197,7 @@ def load_model(_apply_weight(model, packed_modules_mapping, weight_name, tensor)finally:del tensor+ f = Noneif torch.cuda.is_available():torch.cuda.synchronize()gc.collect()diff --git a/shared/utils/audio_metadata.py b/shared/utils/audio_metadata.pyindex 300818f..1257245 100644--- a/shared/utils/audio_metadata.py+++ b/shared/utils/audio_metadata.py@@ -2,6 +2,8 @@ import structfrom typing import Optionalimport jsonimport os+import re+from datetime import datetimedef write_wav_text_chunk(in_path: str, out_path: str, text: str,fourcc: bytes = b'json', encoding: str = 'utf-8') -> None:@@ -155,3 +157,193 @@ def read_audio_metadata(path):if not raw:return Nonereturn json.loads(raw)+++_CREATION_KEYS = (+ "creation_date",+ "creation_datetime",+ "created_at",+ "created_on",+ "creation_timestamp",+ "created_timestamp",+)+_DATE_KEY_PARTS = ("date", "time", "created", "timestamp")+_DATE_KEY_EXCLUDE = ("generation_time", "pause_seconds", "duration_seconds", "video_length")+++def _parse_datetime_value(value):+ if value is None:+ return None+ if isinstance(value, datetime):+ return value+ if isinstance(value, (int, float)):+ if 1900 <= value <= 3000:+ try:+ return datetime(int(value), 1, 1)+ except Exception:+ return None+ if value <= 0:+ return None+ try:+ return datetime.fromtimestamp(float(value))+ except Exception:+ return None++ text = str(value).strip()+ if not text:+ return None+ if re.fullmatch(r"\d{10}(\.\d+)?", text) or re.fullmatch(r"\d{13}", text):+ try:+ ts = float(text)+ if ts > 1_000_000_000_000:+ ts /= 1000.0+ return datetime.fromtimestamp(ts)+ except Exception:+ pass+ if text.endswith("Z"):+ text = text[:-1] + "+00:00"+ if re.match(r"^\d{4}:\d{2}:\d{2}\s", text):+ text = text.replace(":", "-", 2)++ for fmt in (+ "%Y-%m-%d %H:%M:%S",+ "%Y-%m-%d %H:%M",+ "%Y-%m-%d",+ "%Y/%m/%d %H:%M:%S",+ "%Y/%m/%d",+ "%Y-%m-%d-%Hh%Mm%Ss",+ "%Y%m%d",+ "%Y",+ ):+ try:+ return datetime.strptime(text, fmt)+ except Exception:+ pass+ try:+ return datetime.fromisoformat(text)+ except Exception:+ return None+++def _iter_tag_values(value):+ if value is None:+ return+ if hasattr(value, "text"):+ txt = value.text+ if isinstance(txt, (list, tuple)):+ for item in txt:+ yield item+ else:+ yield txt+ return+ if isinstance(value, (list, tuple, set)):+ for item in value:+ yield from _iter_tag_values(item)+ return+ yield value+++def extract_creation_datetime_from_metadata(metadata):+ if not isinstance(metadata, dict):+ return None+ for key in _CREATION_KEYS:+ dt = _parse_datetime_value(metadata.get(key))+ if dt is not None:+ return dt++ extra_info = metadata.get("extra_info")+ if isinstance(extra_info, dict):+ for key in _CREATION_KEYS:+ dt = _parse_datetime_value(extra_info.get(key))+ if dt is not None:+ return dt++ for source in (metadata, extra_info if isinstance(extra_info, dict) else {}):+ for key, value in source.items():+ lkey = str(key).strip().lower()+ if any(part in lkey for part in _DATE_KEY_EXCLUDE):+ continue+ if not any(part in lkey for part in _DATE_KEY_PARTS):+ continue+ dt = _parse_datetime_value(value)+ if dt is not None:+ return dt+ return None+++def _extract_native_audio_datetime(path):+ try:+ from mutagen import File+ except Exception:+ return None+ try:+ audio = File(path, easy=False)+ except Exception:+ return None+ tags = None if audio is None else getattr(audio, "tags", None)+ if tags is None:+ return None++ if hasattr(tags, "getall"):+ for frame_name in ("TDRC", "TDEN", "TORY", "TYER", "TDAT", "TIME"):+ try:+ frames = tags.getall(frame_name)+ except Exception:+ frames = []+ for frame in frames:+ for item in _iter_tag_values(frame):+ dt = _parse_datetime_value(item)+ if dt is not None:+ return dt+ try:+ txxx_frames = tags.getall("TXXX")+ except Exception:+ txxx_frames = []+ for frame in txxx_frames:+ desc = str(getattr(frame, "desc", "")).lower()+ if not any(part in desc for part in _DATE_KEY_PARTS):+ continue+ for item in _iter_tag_values(frame):+ dt = _parse_datetime_value(item)+ if dt is not None:+ return dt++ items = tags.items() if hasattr(tags, "items") else []+ for key, value in items:+ lkey = str(key).lower()+ if any(part in lkey for part in _DATE_KEY_EXCLUDE):+ continue+ if not any(part in lkey for part in _DATE_KEY_PARTS + ("icrd", "\xa9day", "year")):+ continue+ for item in _iter_tag_values(value):+ dt = _parse_datetime_value(item)+ if dt is not None:+ return dt+ return None+++def _get_file_creation_datetime(path):+ if os.name == "nt":+ return datetime.fromtimestamp(os.path.getctime(path))+ stat = os.stat(path)+ ts = stat.st_birthtime if hasattr(stat, "st_birthtime") else stat.st_mtime+ return datetime.fromtimestamp(ts)+++def resolve_audio_creation_datetime(path, wangp_metadata=None):+ metadata = wangp_metadata+ if metadata is None:+ try:+ metadata = read_audio_metadata(path)+ except Exception:+ metadata = None++ dt = extract_creation_datetime_from_metadata(metadata)+ if dt is not None:+ return dt++ dt = _extract_native_audio_datetime(path)+ if dt is not None:+ return dt++ return _get_file_creation_datetime(path)diff --git a/wgp.py b/wgp.pyindex e44c2e6..d1ad05e 100644--- a/wgp.py+++ b/wgp.py@@ -41,7 +41,7 @@ from shared.utils.utils import calculate_new_dimensions, get_outpainting_frame_lfrom shared.utils.utils import has_video_file_extension, has_image_file_extension, has_audio_file_extensionfrom shared.utils.audio_video import extract_audio_tracks, combine_video_with_audio_tracks, combine_and_concatenate_video_with_audio_tracks, cleanup_temp_audio_files, save_video, save_imagefrom shared.utils.audio_video import save_image_metadata, read_image_metadata, extract_audio_track_to_wav, write_wav_file, save_audio_file, get_audio_codec_extension-from shared.utils.audio_metadata import save_audio_metadata, read_audio_metadata+from shared.utils.audio_metadata import save_audio_metadata, read_audio_metadata, extract_creation_datetime_from_metadata, resolve_audio_creation_datetimefrom shared.utils.video_metadata import save_video_metadatafrom shared.match_archi import match_nvidia_architecturefrom shared.attention import get_attention_modes, get_supported_attention_modes@@ -4125,6 +4125,22 @@ all_process_map_video_guide = { "B": "face", "H" : "bbox"}all_process_map_video_guide.update(process_map_video_guide)processes_names = { "pose": "Open Pose", "depth": "Depth Mask", "scribble" : "Shapes", "flow" : "Flow Map", "gray" : "Gray Levels", "inpaint" : "Inpaint Mask", "identity": "Identity Mask", "raw" : "Raw Format", "canny" : "Canny Edges", "face": "Face Movements", "bbox": "BBox"}++def resolve_media_creation_date(file_name, configs=None):+ creation_dt = extract_creation_datetime_from_metadata(configs) if isinstance(configs, dict) else None+ if creation_dt is None and has_audio_file_extension(file_name):+ try:+ creation_dt = resolve_audio_creation_datetime(file_name, wangp_metadata=configs if isinstance(configs, dict) else None)+ except Exception:+ creation_dt = None+ if creation_dt is None:+ creation_dt = get_file_creation_date(file_name)+ creation_date = str(creation_dt)+ if "." in creation_date:+ creation_date = creation_date[:creation_date.rfind(".")]+ return creation_date++def update_video_prompt_type(state, any_video_guide = False, any_video_mask = False, any_background_image_ref = False, process_type = None, default_update = ""):letters = default_updatesettings = get_current_model_settings(state)@@ -4257,8 +4273,7 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, audvalues += misc_valueslabels += misc_labels- video_creation_date = "Deleted" if is_deleted else str(get_file_creation_date(file_name))- if "." in video_creation_date: video_creation_date = video_creation_date[:video_creation_date.rfind(".")]+ video_creation_date = "Deleted" if is_deleted else resolve_media_creation_date(file_name, configs)if is_audio:passelif is_image:@@ -4366,8 +4381,7 @@ def select_video(state, current_gallery_tab, input_file_list, file_selected, audand (any_letters(video_video_prompt_type, "VFK") ) :video_video_guide_outpainting = video_video_guide_outpainting.split(" ")video_outpainting = f"Top={video_video_guide_outpainting[0]}%, Bottom={video_video_guide_outpainting[1]}%, Left={video_video_guide_outpainting[2]}%, Right={video_video_guide_outpainting[3]}%"- video_creation_date = str(get_file_creation_date(file_name))- if "." in video_creation_date: video_creation_date = video_creation_date[:video_creation_date.rfind(".")]+ video_creation_date = resolve_media_creation_date(file_name, configs)video_generation_time = format_generation_time(float(configs.get("generation_time", "0")))video_activated_loras = configs.get("activated_loras", [])video_loras_multipliers = configs.get("loras_multipliers", "")@@ -6886,6 +6900,8 @@ def generate_video(if prompt_enhancer_image_caption_model != None and prompt_enhancer !=None and len(prompt_enhancer)>0 and enhancer_mode != 1:configs["enhanced_prompt"] = "\n".join(prompts)configs["generation_time"] = round(end_time-start_time)+ configs["creation_date"] = datetime.fromtimestamp(end_time).isoformat(timespec="seconds")+ configs["creation_timestamp"] = int(end_time)# if sample_is_image: configs["is_image"] = Truemetadata_choice = server_config.get("metadata_type","metadata")video_path = [video_path] if not isinstance(video_path, list) else video_path