Spaces:
Runtime error
Runtime error
Commit ·
31dffb9
1
Parent(s): 56d1e92
init
Browse filesFiles changed (16)
- .gitattributes+4
- .gitignoreAdded+5
- README.md+4-3
- __lib__/__init__.pyAdded
- __lib__/app.pyAdded+1834
- __lib__/i18n/__init__.pyAdded+36
- __lib__/i18n/en.pycAdded
- __lib__/nfsw.pycAdded
- __lib__/util.pycAdded
- app.pyAdded+60
- datas/cat01.webpAdded
- datas/panda01.jpegAdded
- datas/panda01m.jpegAdded
- labels.jsonAdded+4
- pipeline.pyAdded+1934
- requirements.txtAdded+10
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353637383932 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.png filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text
12345*.jpg*.pnghf_cache/models/__pycache__/12345678910111213---title: Omni Image Editoremoji: 💻colorFrom: graycolorTo: pinksdk: gradiosdk_version: 6.1.0app_file: app.pypinned: falselicense: mitshort_description: Image edit, text to image, face swap, image upscale---1234567891011121314---title: Omni Image Editoremoji: 🖼️colorFrom: bluecolorTo: pinksdk: gradiosdk_version: 5.44.1app_file: app.pypinned: falselicense: mitpython_version: "3.13"short_description: Image edit, text to image, face swap, image upscale---
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834import gradio as grimport threadingimport osimport shutilimport tempfileimport timeimport jsonimport utilfrom util import (process_image_edit, process_text_to_image, process_image_upscale, process_face_swap, process_multi_image_edit, process_watermark_removal, download_and_check_result_nsfw, GoodWebsiteUrl, RateLimitConfig, create_mask_from_layers, TASK_LOCK_MINUTES, PRINT_STATS_INTERVAL)from nfsw import NSFWDetector
# 创建全局配置实例rate_limit_config = RateLimitConfig()
# =============================================================================# i18n 翻译系统 - Load from encrypted modules# =============================================================================import sysfrom pathlib import Path
# Add i18n module to path_i18n_module_path = Path(__file__).parent / "__lib__" / "i18n"if str(_i18n_module_path) not in sys.path: sys.path.insert(0, str(_i18n_module_path))
# Import encrypted i18n loaderfrom i18n import translations as _translationstranslations = _translations
def load_translations(): """Compatibility function - translations are already loaded""" return translations
def t(key, lang="en"): default_en = translations.get("en", {}) lang_dict = translations.get(lang) or default_en if key in lang_dict: return lang_dict[key] return default_en.get(key, key)
def has_active_task(client_ip): """ 检查IP是否有正在进行的任务(3分钟内) Returns: tuple: (has_active, remaining_seconds) """ if client_ip not in util.IP_Active_Tasks: return False, 0 start_time = util.IP_Active_Tasks[client_ip] elapsed = time.time() - start_time lock_seconds = TASK_LOCK_MINUTES * 60 if elapsed < lock_seconds: remaining = lock_seconds - elapsed return True, remaining else: # 任务锁定已过期,清除 del util.IP_Active_Tasks[client_ip] return False, 0
def set_active_task(client_ip, active=True): """ 设置或清除IP的活动任务状态 """ if active: util.IP_Active_Tasks[client_ip] = time.time() print(f"🔒 Task locked for IP: {client_ip}") else: if client_ip in util.IP_Active_Tasks: del util.IP_Active_Tasks[client_ip] # 记录任务完成时间 util.IP_Last_Task_Time[client_ip] = time.time() print(f"🔓 Task unlocked for IP: {client_ip}")
country_dict = { "zh": ["中国"], "hi": ["印度"], "fi": ["芬兰"], "en": ["美国", "澳大利亚", "英国", "加拿大", "新西兰", "爱尔兰"], "es": ["西班牙", "墨西哥", "阿根廷", "哥伦比亚", "智利", "秘鲁"], "pt": ["葡萄牙", "巴西"], "fr": ["法国", "摩纳哥"], "de": ["德国", "奥地利"], "it": ["意大利", "圣马力诺", "梵蒂冈"], "ja": ["日本"], "ru": ["俄罗斯"], "uk": ["乌克兰"], "ar": ["沙特阿拉伯", "埃及", "阿拉伯联合酋长国", "摩洛哥"], "nl": ["荷兰"], "no": ["挪威"], "sv": ["瑞典"], "id": ["印度尼西亚"], "vi": ["越南"], "he": ["以色列"], "tr": ["土耳其"], "da": ["丹麦"],}
def query_ip_country(client_ip): """查询IP地址地理信息""" if client_ip in util.IP_Country_Cache: return util.IP_Country_Cache[client_ip] if not client_ip or client_ip in ["127.0.0.1", "localhost", "::1"]: default_geo = {"country": "Unknown", "region": "Unknown", "city": "Unknown"} util.IP_Country_Cache[client_ip] = default_geo return default_geo try: import requests from requests.exceptions import Timeout, ConnectionError, RequestException api_url = f"https://api.vore.top/api/IPdata?ip={client_ip}" response = requests.get(api_url, timeout=3) if response.status_code == 200: data = response.json() if data.get("code") == 200 and "ipdata" in data: ipdata = data["ipdata"] geo_info = { "country": ipdata.get("info1", "Unknown"), "region": ipdata.get("info2", "Unknown"), "city": ipdata.get("info3", "Unknown") } util.IP_Country_Cache[client_ip] = geo_info return geo_info except Exception as e: print(f"Error querying IP {client_ip}: {e}") default_geo = {"country": "Unknown", "region": "Unknown", "city": "Unknown"} util.IP_Country_Cache[client_ip] = default_geo return default_geo
def get_lang_from_country(country): """根据国家获取语言代码""" if not country or country == "Unknown": return "en" for lang, countries in country_dict.items(): if country in countries: return lang return "en"
def get_lang_from_ip(client_ip): """根据IP获取语言""" geo_info = query_ip_country(client_ip) return get_lang_from_country(geo_info.get("country", "Unknown"))
def get_ip_generation_count(client_ip): """获取IP生成次数""" return util.IP_Generation_Count.get(client_ip, 0)
def increment_ip_generation_count(client_ip): """增加IP生成次数""" if client_ip not in util.IP_Generation_Count: util.IP_Generation_Count[client_ip] = 0 util.IP_Generation_Count[client_ip] += 1 return util.IP_Generation_Count[client_ip]
def get_ip_phase(client_ip): """获取IP当前阶段""" count = get_ip_generation_count(client_ip) geo_info = util.IP_Country_Cache.get(client_ip, {"country": "Unknown"}) country = geo_info.get("country", "Unknown") config = rate_limit_config.get_country_config(country) max_limit = config.get("max_limit", rate_limit_config.BLOCKED_LIMIT) if config.get("is_restricted"): if count >= max_limit: return 'blocked' elif count >= max(0, max_limit - 2): return 'rate_limit_3' elif count >= max(0, max_limit - 3): return 'rate_limit_2' elif count >= max(0, max_limit - 4): return 'rate_limit_1' else: return 'free' free_limit = config.get("free_phase_limit", rate_limit_config.FREE_PHASE_LIMIT) if count < free_limit: return 'free' elif count < rate_limit_config.SLOW_PHASE_1_LIMIT: return 'rate_limit_1' elif count < rate_limit_config.SLOW_PHASE_2_LIMIT: return 'rate_limit_2' elif count < max_limit: return 'rate_limit_3' else: return 'blocked'
def check_rate_limit_for_phase(client_ip, phase): """检查阶段的速率限制""" if phase not in ['rate_limit_1', 'rate_limit_2', 'rate_limit_3']: return False, 0, 0 if phase == 'rate_limit_1': window_minutes = rate_limit_config.PHASE_1_WINDOW_MINUTES elif phase == 'rate_limit_2': window_minutes = rate_limit_config.PHASE_2_WINDOW_MINUTES else: window_minutes = rate_limit_config.PHASE_3_WINDOW_MINUTES current_time = time.time() window_key = f"{client_ip}_{phase}" if window_key in util.IP_Rate_Limit_Track: track_data = util.IP_Rate_Limit_Track[window_key] if current_time - track_data['start_time'] > window_minutes * 60: util.IP_Rate_Limit_Track[window_key] = { 'count': 0, 'start_time': current_time, 'last_generation': current_time } else: util.IP_Rate_Limit_Track[window_key] = { 'count': 0, 'start_time': current_time, 'last_generation': current_time } track_data = util.IP_Rate_Limit_Track[window_key] if track_data['count'] >= rate_limit_config.MAX_IMAGES_PER_WINDOW: elapsed = current_time - track_data['start_time'] wait_time = (window_minutes * 60) - elapsed wait_minutes = max(0, wait_time / 60) return True, wait_minutes, track_data['count'] return False, 0, track_data['count']
def update_country_stats(client_ip): """更新国家使用统计""" geo_info = util.IP_Country_Cache.get(client_ip, {"country": "Unknown"}) country = geo_info["country"] if country not in util.Country_Usage_Stats: util.Country_Usage_Stats[country] = 0 util.Country_Usage_Stats[country] += 1 util.Total_Request_Count += 1 if util.Total_Request_Count % PRINT_STATS_INTERVAL == 0: print("\n" + "="*60) print(f"📊 国家使用统计 (总请求数: {util.Total_Request_Count})") print("="*60) sorted_stats = sorted(util.Country_Usage_Stats.items(), key=lambda x: x[1], reverse=True) for country_name, count in sorted_stats: percentage = (count / util.Total_Request_Count) * 100 print(f" {country_name}: {count} 次 ({percentage:.1f}%)") print("="*60 + "\n")
def record_generation_attempt(client_ip, phase): """记录生成尝试""" increment_ip_generation_count(client_ip) update_country_stats(client_ip) if phase in ['rate_limit_1', 'rate_limit_2', 'rate_limit_3']: window_key = f"{client_ip}_{phase}" current_time = time.time() if window_key in util.IP_Rate_Limit_Track: util.IP_Rate_Limit_Track[window_key]['count'] += 1 util.IP_Rate_Limit_Track[window_key]['last_generation'] = current_time else: util.IP_Rate_Limit_Track[window_key] = { 'count': 1, 'start_time': current_time, 'last_generation': current_time }
def apply_gaussian_blur_to_image_url(image_url, blur_strength=50): """对图片URL应用高斯模糊""" try: import requests from PIL import Image, ImageFilter import io response = requests.get(image_url, timeout=30) if response.status_code != 200: return None image_data = io.BytesIO(response.content) image = Image.open(image_data) blurred_image = image.filter(ImageFilter.GaussianBlur(radius=blur_strength)) return blurred_image except Exception as e: print(f"⚠️ Failed to apply Gaussian blur: {e}") return None
# Initialize NSFW detectortry: nsfw_detector = NSFWDetector() print("✅ NSFW detector initialized successfully")except Exception as e: print(f"❌ NSFW detector initialization failed: {e}") nsfw_detector = None
# =============================================================================# 通用NSFW检测函数# =============================================================================def check_nsfw_for_input(input_image, country, current_count, client_ip): """ 检测输入图片是否为NSFW内容 返回: (is_nsfw, should_check) - 是否为NSFW,是否需要检测 """ if input_image is None: return False, False if not rate_limit_config.should_enable_nsfw(country, current_count): return False, False if nsfw_detector is None: return False, False try: nsfw_result = nsfw_detector.predict_pil_label_only(input_image) if nsfw_result.lower() == "nsfw": print(f"🔍 Input NSFW detected: ❌❌❌ - IP: {client_ip}") return True, True return False, True except Exception as e: print(f"⚠️ NSFW detection failed: {e}") return False, True
def check_nsfw_for_result(result_url, country, current_count): """ 检测结果图片是否为NSFW内容 返回: is_nsfw """ if nsfw_detector is None: return False if not rate_limit_config.should_enable_nsfw(country, current_count): return False try: is_nsfw, _ = download_and_check_result_nsfw(result_url, nsfw_detector) return is_nsfw except Exception: return False
def create_nsfw_blurred_response(result_url, redirect_url, lang): """ 创建NSFW模糊处理后的响应HTML 返回: (result_html, action_html) 或 None 如果模糊失败 """ blurred_image = apply_gaussian_blur_to_image_url(result_url) if blurred_image is None: return None blurred_html = pil_image_to_base64_html(blurred_image) nsfw_button_html = f""" <div style='display: flex; justify-content: center; gap: 15px; margin: 10px 0 5px 0; padding: 0px;'> <a href='{redirect_url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; text-align: center; min-width: 200px; box-shadow: 0 4px 15px rgba(255, 107, 107, 0.4); transition: all 0.3s ease; border: none; '>🔒 Unlock Full Image - Visit Website</a> </div> """ return blurred_html, nsfw_button_html
# =============================================================================# 通用处理函数# =============================================================================def create_blocked_button_html(url): """创建封锁状态的按钮HTML""" return f""" <div style='display: flex; justify-content: center; gap: 15px; margin: 10px 0 5px 0; padding: 0px;'> <a href='{url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; text-align: center; min-width: 200px; box-shadow: 0 4px 15px rgba(231, 76, 60, 0.4); transition: all 0.3s ease; border: none; '>🚀 Unlimited Generation</a> </div> """
def create_rate_limit_button_html(url): """创建限速状态的按钮HTML""" return f""" <div style='display: flex; justify-content: center; gap: 15px; margin: 10px 0 5px 0; padding: 0px;'> <a href='{url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; text-align: center; min-width: 200px; box-shadow: 0 4px 15px rgba(243, 156, 18, 0.4); transition: all 0.3s ease; border: none; '>⏰ Skip Wait - Unlimited Generation</a> </div> """
def create_task_locked_button_html(url, remaining_seconds): """创建任务锁定状态的按钮HTML""" remaining_minutes = int(remaining_seconds / 60) + 1 return f""" <div style='display: flex; justify-content: center; gap: 15px; margin: 10px 0 5px 0; padding: 0px;'> <a href='{url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; text-align: center; min-width: 200px; box-shadow: 0 4px 15px rgba(243, 156, 18, 0.4); transition: all 0.3s ease; border: none; '>⏰ Process Multiple Tasks</a> </div> """
def create_like_tip_html(): """创建点击红心提示HTML""" return """ <div style='display: flex; justify-content: center; margin: 15px 0 5px 0; padding: 0px;'> <div style=' display: inline-flex; align-items: center; justify-content: center; padding: 12px 24px; background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%); color: white; border-radius: 10px; font-weight: 600; font-size: 14px; text-align: center; max-width: 400px; box-shadow: 0 3px 12px rgba(255, 107, 107, 0.3); border: none; '>👉 Click the ❤️ Like button to unlock more free trial attempts!</div> </div> """
def create_result_image_html(image_url, max_height=500): """创建结果图片HTML(直接从源站加载,不经过HF Space服务器)""" if not image_url: return "" return f""" <div style='display: flex; justify-content: center; align-items: center; padding: 10px; background-color: #f8f9fa; border-radius: 10px;'> <img src='{image_url}' style='max-width: 100%; max-height: {max_height}px; object-fit: contain; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);' alt='Result Image' /> </div> """
def pil_image_to_base64_html(pil_image, max_height=500): """将PIL Image转为base64嵌入HTML(不经过服务器中转)""" import io import base64 try: if pil_image is None: return "" # 转为JPEG格式 img_buffer = io.BytesIO() if pil_image.mode != 'RGB': pil_image = pil_image.convert('RGB') pil_image.save(img_buffer, format='JPEG', quality=85) img_data = img_buffer.getvalue() # 编码为base64 img_base64 = base64.b64encode(img_data).decode('utf-8') return f""" <div style='display: flex; justify-content: center; align-items: center; padding: 10px; background-color: #f8f9fa; border-radius: 10px;'> <img src='data:image/jpeg;base64,{img_base64}' style='max-width: 100%; max-height: {max_height}px; object-fit: contain; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);' alt='Blurred Result' /> </div> """ except Exception as e: print(f"⚠️ Failed to convert PIL to base64 HTML: {e}") return ""
def create_action_buttons_html(task_uuid, input_image_url, result_url, prompt, lang, show_like_tip): """创建操作按钮HTML""" action_buttons_html = "" if task_uuid and lang not in ["zh", "hi", "ru"]: task_detail_url = f"https://omnicreator.net/my-creations/task/{task_uuid}" from urllib.parse import quote encoded_prompt = quote(prompt.strip()) if prompt else "" encoded_result_url = quote(result_url) if result_url else "" i2v_url = f"https://omnicreator.net/image-to-video?input_image={input_image_url}&end_image={result_url}&prompt={encoded_prompt}" face_swap_url = f"https://omnicreator.net/face-swap?user_image={encoded_result_url}" action_buttons_html = f""" <div style='display: flex; justify-content: center; gap: 15px; margin: 10px 0 5px 0; padding: 0px; flex-wrap: wrap;'> <a href='{i2v_url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; text-align: center; min-width: 160px; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4); transition: all 0.3s ease; border: none; '>🎥 Convert to Video</a> <a href='{face_swap_url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; text-align: center; min-width: 160px; box-shadow: 0 4px 15px rgba(245, 87, 108, 0.4); transition: all 0.3s ease; border: none; '>🧍 Swap Face</a> <a href='{task_detail_url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; text-align: center; min-width: 160px; box-shadow: 0 4px 15px rgba(17, 153, 142, 0.4); transition: all 0.3s ease; border: none; '>💾 Download HD Image</a> </div> """ if show_like_tip or lang in ["zh", "hi", "ru"]: action_buttons_html += create_like_tip_html() return action_buttons_html
# =============================================================================# 单图编辑接口# =============================================================================def edit_image_interface(input_image, prompt, lang, request: gr.Request, progress=gr.Progress()): """单图编辑接口""" try: client_ip = request.client.host x_forwarded_for = dict(request.headers).get('x-forwarded-for') if x_forwarded_for: client_ip = x_forwarded_for if client_ip not in util.IP_Dict: util.IP_Dict[client_ip] = 0 util.IP_Dict[client_ip] += 1
if input_image is None: return "", None, t("error_upload_first", lang), gr.update(visible=False) if not prompt or prompt.strip() == "": return "", None, t("error_enter_prompt", lang), gr.update(visible=False) if len(prompt.strip()) <= 3: return "", None, t("error_prompt_too_short", lang), gr.update(visible=False) except Exception as e: return "", None, t("error_request_processing", lang), gr.update(visible=False) geo_info = util.IP_Country_Cache.get(client_ip, {"country": "Unknown"}) country = geo_info.get("country", "Unknown") current_phase = get_ip_phase(client_ip) current_count = get_ip_generation_count(client_ip) is_restricted = rate_limit_config.is_restricted_country(country) show_like_tip = rate_limit_config.should_show_like_tip(country, current_count) redirect_url = rate_limit_config.get_redirect_url(country, lang) # 检查是否有活动任务(3分钟内) is_active, remaining_seconds = has_active_task(client_ip) if is_active: return "", None, f"⏰ You have a task in progress. Please wait until it is finished before submitting a new task.", gr.update(value=create_task_locked_button_html(redirect_url, remaining_seconds), visible=True) # 检查是否被封锁 if current_phase == 'blocked': return "", None, t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) # 检查速率限制 if current_phase in ['rate_limit_1', 'rate_limit_2', 'rate_limit_3']: is_limited, wait_minutes, window_count = check_rate_limit_for_phase(client_ip, current_phase) if is_limited: wait_minutes_int = int(wait_minutes) + 1 return "", None, t("error_free_limit_wait", lang).format(wait_minutes_int=wait_minutes_int), gr.update(value=create_rate_limit_button_html(redirect_url), visible=True) # NSFW检测 is_nsfw_task, _ = check_nsfw_for_input(input_image, country, current_count, client_ip) def progress_callback(message): try: if progress is not None: if "Queue:" in message or "tasks ahead" in message: progress(0.1, desc=message) elif "Processing" in message or "AI is processing" in message: progress(0.7, desc=message) elif "Generating" in message or "Almost done" in message: progress(0.9, desc=message) else: progress(0.5, desc=message) except Exception: pass try: # 设置任务锁定 set_active_task(client_ip, True) task_priority = 1 if current_count < rate_limit_config.HIGH_PRIORITY_COUNT else 0 record_generation_attempt(client_ip, current_phase) input_image_url, result_url, message, task_uuid = process_image_edit(input_image, prompt.strip(), None, progress_callback, priority=task_priority, client_ip=client_ip) if message and message.startswith("HF_LIMIT_EXCEEDED:"): return "", None, t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if result_url: # 检查结果图片NSFW if check_nsfw_for_result(result_url, country, current_count): is_nsfw_task = True # 应用模糊处理 if is_nsfw_task: nsfw_response = create_nsfw_blurred_response(result_url, redirect_url, lang) if nsfw_response: blurred_html, nsfw_button_html = nsfw_response set_active_task(client_ip, False) # 解锁任务 # 返回None作为URL,防止用户通过"Use as Input"绕过NSFW检测 return blurred_html, None, t("warning_content_filter", lang), gr.update(value=nsfw_button_html, visible=True) # 正常情况:返回HTML显示图片 result_html = create_result_image_html(result_url) action_html = create_action_buttons_html(task_uuid, input_image_url, result_url, prompt, lang, show_like_tip) set_active_task(client_ip, False) # 解锁任务 return result_html, result_url, t("status_completed_message", lang).format(message=message), gr.update(value=action_html, visible=True) else: set_active_task(client_ip, False) # 解锁任务 return "", None, t("error_processing_failed", lang).format(message=message), gr.update(visible=False) except Exception as e: set_active_task(client_ip, False) # 解锁任务 return "", None, t("error_processing_exception", lang).format(error=str(e)), gr.update(visible=False)
# =============================================================================# 多图编辑接口# =============================================================================def multi_image_edit_interface(input_image1, input_image2, input_image3, prompt, aspect_ratio, lang, request: gr.Request, progress=gr.Progress()): """多图编辑接口""" try: client_ip = request.client.host x_forwarded_for = dict(request.headers).get('x-forwarded-for') if x_forwarded_for: client_ip = x_forwarded_for images = [img for img in [input_image1, input_image2, input_image3] if img is not None] if len(images) < 2: return "", t("error_multi_image_required", lang), gr.update(visible=False) if not prompt or prompt.strip() == "": return "", t("error_enter_prompt", lang), gr.update(visible=False) if len(prompt.strip()) <= 3: return "", t("error_prompt_too_short", lang), gr.update(visible=False) except Exception as e: return "", t("error_request_processing", lang), gr.update(visible=False) geo_info = util.IP_Country_Cache.get(client_ip, {"country": "Unknown"}) country = geo_info.get("country", "Unknown") country_config = rate_limit_config.get_country_config(country) current_phase = get_ip_phase(client_ip) current_count = get_ip_generation_count(client_ip) show_like_tip = rate_limit_config.should_show_like_tip(country, current_count) redirect_url = rate_limit_config.get_redirect_url(country, lang) # 检查是否有活动任务(3分钟内) is_active, remaining_seconds = has_active_task(client_ip) if is_active: return "", f"⏰ You have a task in progress. Please wait until it is finished before submitting a new task.", gr.update(value=create_task_locked_button_html(redirect_url, remaining_seconds), visible=True) # 根据用户次数和国家配置决定是否使用高速高清模式 high_speed_hd_count = country_config.get("high_speed_hd_count", rate_limit_config.HIGH_SPEED_HD_COUNT) use_high_speed_mode = current_count < high_speed_hd_count # 检查是否被封锁 if current_phase == 'blocked': return "", t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if current_phase in ['rate_limit_1', 'rate_limit_2', 'rate_limit_3']: is_limited, wait_minutes, _ = check_rate_limit_for_phase(client_ip, current_phase) if is_limited: wait_minutes_int = int(wait_minutes) + 1 return "", t("error_free_limit_wait", lang).format(wait_minutes_int=wait_minutes_int), gr.update(value=create_rate_limit_button_html(redirect_url), visible=True) # NSFW检测 - 检测所有输入图片 is_nsfw_task = False for img in images: if img is not None: nsfw_detected, _ = check_nsfw_for_input(img, country, current_count, client_ip) if nsfw_detected: is_nsfw_task = True break # 决定任务参数(在progress_callback之前定义) if use_high_speed_mode: task_priority = 1 is_sr = 1 # 启用超分 mode_info = "🚀 High-Speed + HD Mode" else: task_priority = 0 is_sr = 0 # 关闭超分 mode_info = "⏱️ Low Resolution Mode | Visit https://omnicreator.net for High-Speed HD generation" def progress_callback(message): try: if progress is not None: progress(0.5, desc=f"{mode_info} | {message}") except Exception: pass try: # 设置任务锁定 set_active_task(client_ip, True) record_generation_attempt(client_ip, current_phase) input_url, result_url, message, task_uuid = process_multi_image_edit(images, prompt.strip(), progress_callback, priority=task_priority, client_ip=client_ip, is_sr=is_sr) if message and message.startswith("HF_LIMIT_EXCEEDED:"): set_active_task(client_ip, False) # 解锁任务 return "", t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if result_url: # 检查结果图片NSFW if check_nsfw_for_result(result_url, country, current_count): is_nsfw_task = True # 应用模糊处理 if is_nsfw_task: nsfw_response = create_nsfw_blurred_response(result_url, redirect_url, lang) if nsfw_response: blurred_html, nsfw_button_html = nsfw_response set_active_task(client_ip, False) return blurred_html, t("warning_content_filter", lang), gr.update(value=nsfw_button_html, visible=True) result_html = create_result_image_html(result_url) action_html = create_action_buttons_html(task_uuid, input_url, result_url, prompt, lang, show_like_tip) # 添加模式提示信息 if use_high_speed_mode: mode_tip = "🚀 Generated with High-Speed + HD Mode" else: mode_tip = "⏱️ Generated with Low Resolution Mode | Visit https://omnicreator.net for High-Speed HD generation" status_message = f"{mode_tip}\n{t('status_completed_message', lang).format(message=message)}" set_active_task(client_ip, False) # 解锁任务 return result_html, status_message, gr.update(value=action_html, visible=True) else: set_active_task(client_ip, False) # 解锁任务 return "", t("error_processing_failed", lang).format(message=message), gr.update(visible=False) except Exception as e: set_active_task(client_ip, False) # 解锁任务 return "", t("error_processing_exception", lang).format(error=str(e)), gr.update(visible=False)
# =============================================================================# 文生图接口# =============================================================================def text_to_image_interface(prompt, aspect_ratio, lang, request: gr.Request, progress=gr.Progress()): """文生图接口""" try: client_ip = request.client.host x_forwarded_for = dict(request.headers).get('x-forwarded-for') if x_forwarded_for: client_ip = x_forwarded_for if not prompt or prompt.strip() == "": return "", t("error_enter_prompt", lang), gr.update(visible=False) if len(prompt.strip()) <= 3: return "", t("error_prompt_too_short", lang), gr.update(visible=False) except Exception as e: return "", t("error_request_processing", lang), gr.update(visible=False) geo_info = util.IP_Country_Cache.get(client_ip, {"country": "Unknown"}) country = geo_info.get("country", "Unknown") country_config = rate_limit_config.get_country_config(country) current_phase = get_ip_phase(client_ip) current_count = get_ip_generation_count(client_ip) show_like_tip = rate_limit_config.should_show_like_tip(country, current_count) redirect_url = rate_limit_config.get_redirect_url(country, lang) # 检查是否有活动任务(3分钟内) is_active, remaining_seconds = has_active_task(client_ip) if is_active: return "", f"⏰ You have a task in progress. Please wait until it is finished before submitting a new task.", gr.update(value=create_task_locked_button_html(redirect_url, remaining_seconds), visible=True) # 根据用户次数和国家配置决定是否使用高速高清模式 high_speed_hd_count = country_config.get("high_speed_hd_count", rate_limit_config.HIGH_SPEED_HD_COUNT) use_high_speed_mode = current_count < high_speed_hd_count # 检查是否被封锁 if current_phase == 'blocked': return "", t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if current_phase in ['rate_limit_1', 'rate_limit_2', 'rate_limit_3']: is_limited, wait_minutes, _ = check_rate_limit_for_phase(client_ip, current_phase) if is_limited: wait_minutes_int = int(wait_minutes) + 1 return "", t("error_free_limit_wait", lang).format(wait_minutes_int=wait_minutes_int), gr.update(value=create_rate_limit_button_html(redirect_url), visible=True) # 决定任务参数(在progress_callback之前定义,以便在回调中使用) if use_high_speed_mode: task_priority = 1 is_sr = 1 # 启用超分 target_area = 800 * 800 # 高清分辨率 mode_info = "🚀 High-Speed + HD Mode (800×800)" else: task_priority = 0 is_sr = 0 # 关闭超分 target_area = 576 * 576 # 标准分辨率 mode_info = "⏱️ Low Resolution Mode (576×576) | Visit https://omnicreator.net for High-Speed HD generation" def progress_callback(message): try: if progress is not None: # 添加模式提示 progress(0.5, desc=f"{mode_info} | {message}") except Exception: pass try: # 设置任务锁定 set_active_task(client_ip, True) record_generation_attempt(client_ip, current_phase) result_url, message, task_uuid = process_text_to_image(prompt.strip(), aspect_ratio, progress_callback, priority=task_priority, client_ip=client_ip, is_sr=is_sr, target_area=target_area) if message and message.startswith("HF_LIMIT_EXCEEDED:"): set_active_task(client_ip, False) return "", t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if result_url: # 检查结果图片NSFW is_nsfw_task = check_nsfw_for_result(result_url, country, current_count) # 应用模糊处理 if is_nsfw_task: nsfw_response = create_nsfw_blurred_response(result_url, redirect_url, lang) if nsfw_response: blurred_html, nsfw_button_html = nsfw_response set_active_task(client_ip, False) return blurred_html, t("warning_content_filter", lang), gr.update(value=nsfw_button_html, visible=True) result_html = create_result_image_html(result_url) # 为T2I生成3个操作按钮 action_html = "" if task_uuid and lang not in ["zh", "hi", "ru"]: task_detail_url = f"https://omnicreator.net/my-creations/task/{task_uuid}" from urllib.parse import quote encoded_prompt = quote(prompt.strip()) if prompt else "" encoded_result_url = quote(result_url) if result_url else "" i2v_url = f"https://omnicreator.net/image-to-video?input_image={encoded_result_url}&prompt={encoded_prompt}" face_swap_url = f"https://omnicreator.net/face-swap?user_image={encoded_result_url}" action_html = f""" <div style='display: flex; justify-content: center; gap: 15px; margin: 10px 0 5px 0; padding: 0px; flex-wrap: wrap;'> <a href='{i2v_url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; min-width: 160px; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4); '>🎥 Convert to Video</a> <a href='{face_swap_url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; min-width: 160px; box-shadow: 0 4px 15px rgba(245, 87, 108, 0.4); '>🧍 Swap Face</a> <a href='{task_detail_url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; min-width: 160px; box-shadow: 0 4px 15px rgba(17, 153, 142, 0.4); '>💾 Download HD Image</a> </div> """ if show_like_tip or lang in ["zh", "hi", "ru"]: action_html += create_like_tip_html() # 添加模式提示信息 if use_high_speed_mode: mode_tip = "🚀 Generated with High-Speed + HD Mode (800×800)" else: mode_tip = "⏱️ Generated with Low Resolution Mode (576×576) | Visit https://omnicreator.net for High-Speed HD generation" status_message = f"{mode_tip}\n{t('status_completed_message', lang).format(message=message)}" set_active_task(client_ip, False) # 解锁任务 return result_html, status_message, gr.update(value=action_html, visible=True) else: set_active_task(client_ip, False) # 解锁任务 return "", t("error_processing_failed", lang).format(message=message), gr.update(visible=False) except Exception as e: set_active_task(client_ip, False) # 解锁任务 return "", t("error_processing_exception", lang).format(error=str(e)), gr.update(visible=False)
# =============================================================================# 图片放大接口# =============================================================================def image_upscale_interface(input_image, lang, request: gr.Request, progress=gr.Progress()): """图片放大接口""" try: client_ip = request.client.host x_forwarded_for = dict(request.headers).get('x-forwarded-for') if x_forwarded_for: client_ip = x_forwarded_for if input_image is None: return "", t("error_upload_first", lang), gr.update(visible=False) except Exception as e: return "", t("error_request_processing", lang), gr.update(visible=False) geo_info = util.IP_Country_Cache.get(client_ip, {"country": "Unknown"}) country = geo_info.get("country", "Unknown") current_phase = get_ip_phase(client_ip) current_count = get_ip_generation_count(client_ip) show_like_tip = rate_limit_config.should_show_like_tip(country, current_count) redirect_url = rate_limit_config.get_redirect_url(country, lang) # 检查是否有活动任务(3分钟内) is_active, remaining_seconds = has_active_task(client_ip) if is_active: return "", f"⏰ You have a task in progress. Please wait until it is finished before submitting a new task.", gr.update(value=create_task_locked_button_html(redirect_url, remaining_seconds), visible=True) # 检查是否被封锁 if current_phase == 'blocked': return "", t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if current_phase in ['rate_limit_1', 'rate_limit_2', 'rate_limit_3']: is_limited, wait_minutes, _ = check_rate_limit_for_phase(client_ip, current_phase) if is_limited: wait_minutes_int = int(wait_minutes) + 1 return "", t("error_free_limit_wait", lang).format(wait_minutes_int=wait_minutes_int), gr.update(value=create_rate_limit_button_html(redirect_url), visible=True) # NSFW检测 is_nsfw_task, _ = check_nsfw_for_input(input_image, country, current_count, client_ip) def progress_callback(message): try: if progress is not None: progress(0.5, desc=message) except Exception: pass try: # 设置任务锁定 set_active_task(client_ip, True) task_priority = 1 if current_count < rate_limit_config.HIGH_PRIORITY_COUNT else 0 record_generation_attempt(client_ip, current_phase) input_url, result_url, message, task_uuid = process_image_upscale(input_image, progress_callback, priority=task_priority, client_ip=client_ip) if message and message.startswith("HF_LIMIT_EXCEEDED:"): set_active_task(client_ip, False) return "", t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if result_url: # 检查结果图片NSFW if check_nsfw_for_result(result_url, country, current_count): is_nsfw_task = True # 应用模糊处理 if is_nsfw_task: nsfw_response = create_nsfw_blurred_response(result_url, redirect_url, lang) if nsfw_response: blurred_html, nsfw_button_html = nsfw_response set_active_task(client_ip, False) return blurred_html, t("warning_content_filter", lang), gr.update(value=nsfw_button_html, visible=True) result_html = create_result_image_html(result_url) action_html = "" if task_uuid and lang not in ["zh", "hi", "ru"]: task_detail_url = f"https://omnicreator.net/my-creations/task/{task_uuid}" action_html = f""" <div style='display: flex; justify-content: center; gap: 15px; margin: 10px 0 5px 0; padding: 0px;'> <a href='{task_detail_url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; text-align: center; min-width: 160px; box-shadow: 0 4px 15px rgba(17, 153, 142, 0.4); transition: all 0.3s ease; border: none; '>💾 Download HD Image</a> </div> """ if show_like_tip or lang in ["zh", "hi", "ru"]: action_html += create_like_tip_html() set_active_task(client_ip, False) # 解锁任务 return result_html, t("status_completed_message", lang).format(message=message), gr.update(value=action_html, visible=bool(action_html)) else: set_active_task(client_ip, False) # 解锁任务 return "", t("error_processing_failed", lang).format(message=message), gr.update(visible=False) except Exception as e: set_active_task(client_ip, False) # 解锁任务 return "", t("error_processing_exception", lang).format(error=str(e)), gr.update(visible=False)
# =============================================================================# 换脸接口# =============================================================================def face_swap_interface(target_editor, source_face_image, lang, request: gr.Request, progress=gr.Progress()): """换脸接口 - 支持从ImageEditor提取mask""" try: client_ip = request.client.host x_forwarded_for = dict(request.headers).get('x-forwarded-for') if x_forwarded_for: client_ip = x_forwarded_for # 从ImageEditor提取图片和mask target_image = None mask_image = None if target_editor is None: return "", t("error_upload_target_image", lang), gr.update(visible=False) # ImageEditor返回字典格式: {"background": PIL, "layers": [PIL], "composite": PIL} if isinstance(target_editor, dict): target_image = target_editor.get("background") layers = target_editor.get("layers", []) # 从layers提取mask if layers and len(layers) > 0: from util import create_mask_from_layers mask_image = create_mask_from_layers(target_image, layers) else: # 兼容直接传入PIL Image的情况 target_image = target_editor if target_image is None: return "", t("error_upload_target_image", lang), gr.update(visible=False) if source_face_image is None: return "", t("error_upload_source_face", lang), gr.update(visible=False) except Exception as e: return "", t("error_request_processing", lang), gr.update(visible=False) geo_info = util.IP_Country_Cache.get(client_ip, {"country": "Unknown"}) country = geo_info.get("country", "Unknown") current_phase = get_ip_phase(client_ip) current_count = get_ip_generation_count(client_ip) show_like_tip = rate_limit_config.should_show_like_tip(country, current_count) redirect_url = rate_limit_config.get_redirect_url(country, lang) # 检查活动任务 is_active, remaining_seconds = has_active_task(client_ip) if is_active: return "", f"⏰ Task in progress. Wait {int(remaining_seconds/60)+1} min.", gr.update(value=create_task_locked_button_html(redirect_url, remaining_seconds), visible=True) # 检查是否被封锁 if current_phase == 'blocked': return "", t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if current_phase in ['rate_limit_1', 'rate_limit_2', 'rate_limit_3']: is_limited, wait_minutes, _ = check_rate_limit_for_phase(client_ip, current_phase) if is_limited: return "", t("error_free_limit_wait", lang).format(wait_minutes_int=int(wait_minutes)+1), gr.update(value=create_rate_limit_button_html(redirect_url), visible=True) # NSFW检测 - 检测target和source图片 is_nsfw_task, _ = check_nsfw_for_input(target_image, country, current_count, client_ip) if not is_nsfw_task: is_nsfw_task, _ = check_nsfw_for_input(source_face_image, country, current_count, client_ip) def progress_callback(message): try: if progress is not None: progress(0.5, desc=message) except Exception: pass try: set_active_task(client_ip, True) task_priority = 1 if current_count < rate_limit_config.HIGH_PRIORITY_COUNT else 0 record_generation_attempt(client_ip, current_phase) input_url, result_url, message, task_uuid = process_face_swap(target_image, source_face_image, mask_image, progress_callback, priority=task_priority, client_ip=client_ip) if message and message.startswith("HF_LIMIT_EXCEEDED:"): set_active_task(client_ip, False) return "", t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if result_url: # 检查结果图片NSFW if check_nsfw_for_result(result_url, country, current_count): is_nsfw_task = True # 应用模糊处理 if is_nsfw_task: nsfw_response = create_nsfw_blurred_response(result_url, redirect_url, lang) if nsfw_response: blurred_html, nsfw_button_html = nsfw_response set_active_task(client_ip, False) return blurred_html, t("warning_content_filter", lang), gr.update(value=nsfw_button_html, visible=True) result_html = create_result_image_html(result_url) action_html = "" if task_uuid and lang not in ["zh", "hi", "ru"]: task_detail_url = f"https://omnicreator.net/my-creations/task/{task_uuid}" action_html = f""" <div style='display: flex; justify-content: center; gap: 15px; margin: 10px 0 5px 0; padding: 0px;'> <a href='{task_detail_url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; text-align: center; min-width: 160px; box-shadow: 0 4px 15px rgba(17, 153, 142, 0.4); transition: all 0.3s ease; border: none; '>💾 Download HD Image</a> </div> """ if show_like_tip or lang in ["zh", "hi", "ru"]: action_html += create_like_tip_html() set_active_task(client_ip, False) return result_html, t("status_completed_message", lang).format(message=message), gr.update(value=action_html, visible=bool(action_html)) else: set_active_task(client_ip, False) return "", t("error_processing_failed", lang).format(message=message), gr.update(visible=False) except Exception as e: set_active_task(client_ip, False) return "", t("error_processing_exception", lang).format(error=str(e)), gr.update(visible=False)
# =============================================================================# 去水印接口# =============================================================================def watermark_removal_interface(input_image, force_removal, lang, request: gr.Request, progress=gr.Progress()): """去水印接口 - 支持强力模式""" try: client_ip = request.client.host x_forwarded_for = dict(request.headers).get('x-forwarded-for') if x_forwarded_for: client_ip = x_forwarded_for if input_image is None: return "", t("error_upload_image", lang), gr.update(visible=False) except Exception as e: return "", t("error_request_processing", lang), gr.update(visible=False) geo_info = util.IP_Country_Cache.get(client_ip, {"country": "Unknown"}) country = geo_info.get("country", "Unknown") current_phase = get_ip_phase(client_ip) current_count = get_ip_generation_count(client_ip) show_like_tip = rate_limit_config.should_show_like_tip(country, current_count) redirect_url = rate_limit_config.get_redirect_url(country, lang) # 检查活动任务 is_active, remaining_seconds = has_active_task(client_ip) if is_active: return "", f"⏰ Task in progress. Please wait until it is finished before submitting a new task.", gr.update(value=create_task_locked_button_html(redirect_url, remaining_seconds), visible=True) # 检查是否被封锁 if current_phase == 'blocked': return "", t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if current_phase in ['rate_limit_1', 'rate_limit_2', 'rate_limit_3']: is_limited, wait_minutes, _ = check_rate_limit_for_phase(client_ip, current_phase) if is_limited: return "", t("error_free_limit_wait", lang).format(wait_minutes_int=int(wait_minutes)+1), gr.update(value=create_rate_limit_button_html(redirect_url), visible=True) # NSFW检测 is_nsfw_task, _ = check_nsfw_for_input(input_image, country, current_count, client_ip) def progress_callback(message): try: if progress is not None: mode_text = "💪 AI Force Mode | " if force_removal else "" progress(0.5, desc=f"{mode_text}🧽 Removing watermark... | {message}") except Exception: pass try: set_active_task(client_ip, True) task_priority = 1 if current_count < rate_limit_config.HIGH_PRIORITY_COUNT else 0 record_generation_attempt(client_ip, current_phase) input_url, result_url, message, task_uuid = process_watermark_removal(input_image, progress_callback, priority=task_priority, client_ip=client_ip, force_removal=force_removal) if message and message.startswith("HF_LIMIT_EXCEEDED:"): set_active_task(client_ip, False) return "", t("error_free_limit_reached", lang), gr.update(value=create_blocked_button_html(redirect_url), visible=True) if result_url: # 检查结果图片NSFW if check_nsfw_for_result(result_url, country, current_count): is_nsfw_task = True # 应用模糊处理 if is_nsfw_task: nsfw_response = create_nsfw_blurred_response(result_url, redirect_url, lang) if nsfw_response: blurred_html, nsfw_button_html = nsfw_response set_active_task(client_ip, False) return blurred_html, t("warning_content_filter", lang), gr.update(value=nsfw_button_html, visible=True) result_html = create_result_image_html(result_url) action_html = "" if task_uuid and lang not in ["zh", "hi", "ru"]: task_detail_url = f"https://omnicreator.net/my-creations/task/{task_uuid}" action_html = f""" <div style='display: flex; justify-content: center; gap: 15px; margin: 10px 0 5px 0; padding: 0px;'> <a href='{task_detail_url}' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; min-width: 160px; box-shadow: 0 4px 15px rgba(17, 153, 142, 0.4); '>💾 Download HD Image</a> <a href='https://omnicreator.net/remove-watermark#generator' target='_blank' style=' display: inline-flex; align-items: center; justify-content: center; padding: 16px 32px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; text-decoration: none; border-radius: 12px; font-weight: 600; font-size: 16px; min-width: 160px; box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4); '>🚀 Unlimited Removal</a> </div> """ if show_like_tip or lang in ["zh", "hi", "ru"]: action_html += create_like_tip_html() set_active_task(client_ip, False) return result_html, t("status_completed_message", lang).format(message=message), gr.update(value=action_html, visible=bool(action_html)) else: set_active_task(client_ip, False) return "", t("error_processing_failed", lang).format(message=message), gr.update(visible=False) except Exception as e: set_active_task(client_ip, False) return "", t("error_processing_exception", lang).format(error=str(e)), gr.update(visible=False)
# =============================================================================# 创建Gradio应用# =============================================================================def create_app(): with gr.Blocks( title="AI Image Editor", theme=gr.themes.Soft(), css=""" .main-container { max-width: 1200px; margin: 0 auto; } .news-banner-row { margin: 10px auto 15px auto; padding: 0 10px; max-width: 1200px; width: 100% !important; } .banner-lang-selector { margin-left: auto !important; display: flex !important; justify-content: flex-end !important; } .upload-area { border: 2px dashed #ccc; border-radius: 10px; padding: 20px; text-align: center; } .result-area { margin-top: 20px; padding: 20px; border-radius: 10px; background-color: #f8f9fa; } """ ) as app: lang_state = gr.State("en")
# 主标题 header_title = gr.HTML(f""" <div style="text-align: center; margin: 20px auto 10px auto; max-width: 800px;"> <h1 style="color: #2c3e50; margin: 0; font-size: 3.5em; font-weight: 800; letter-spacing: 3px; text-shadow: 2px 2px 4px rgba(0,0,0,0.1);"> {t('header_title', 'en')} </h1> </div> """) with gr.Row(elem_classes=["news-banner-row"]): with gr.Column(scale=1, min_width=400): news_banner = gr.HTML(f""" <style> @keyframes breathe {{ 0%, 100% {{ transform: scale(1); }} 50% {{ transform: scale(1.02); }} }} .breathing-banner {{ animation: breathe 3s ease-in-out infinite; }} </style> <div class="breathing-banner" style=" background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); margin: 0 auto; padding: 8px 40px; border-radius: 20px; max-width: 800px; box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3); text-align: center; width: fit-content; "> <span style="color: white; font-weight: 600; font-size: 1.0em;"> 🎉 Please give us a ❤️ if you think it's helpful </span> </div> """, visible=True) with gr.Column(scale=0, min_width=160, elem_classes=["banner-lang-selector"]): lang_dropdown = gr.Dropdown( choices=[("English", "en"), ("中文", "zh")], value="en", label="🌐", show_label=True, interactive=True, container=False ) # ============================================================================= # 多Tab界面 # ============================================================================= with gr.Tabs() as tabs: # ============================================================================= # Tab 1: 单图编辑 # ============================================================================= with gr.Tab(t("tab_single_image_edit", "en")) as single_edit_tab: with gr.Row(): with gr.Column(scale=1): gr.Markdown(t("upload_image_header", "en")) single_input_image = gr.Image(label=t("upload_image_label", "en"), type="pil", height=512, elem_classes=["upload-area"]) gr.Markdown(t("editing_instructions_header", "en")) single_prompt = gr.Textbox(label=t("prompt_input_label", "en"), placeholder=t("prompt_input_placeholder", "en"), lines=3) single_edit_btn = gr.Button(t("start_editing_button", "en"), variant="primary", size="lg") with gr.Column(scale=1): gr.Markdown(t("editing_result_header", "en")) single_output_image = gr.HTML(label=t("output_image_label", "en"), elem_classes=["result-area"]) single_output_url = gr.State() # 隐藏state保存URL用于Use as Input single_use_as_input_btn = gr.Button(t("use_as_input_button", "en"), variant="secondary", size="sm") single_status = gr.Textbox(label=t("status_output_label", "en"), lines=2, interactive=False) single_action_buttons = gr.HTML(visible=False) gr.Markdown(t("prompt_examples_header", "en")) with gr.Row(): for prompt in ["Change background to beach sunset", "Add rainbow in the sky", "Make it look like oil painting", "Remove the background", "Change outfit to red dress"]: gr.Button(prompt, size="sm").click(lambda p=prompt: p, outputs=single_prompt) single_edit_btn.click( fn=edit_image_interface, inputs=[single_input_image, single_prompt, lang_state], outputs=[single_output_image, single_output_url, single_status, single_action_buttons], show_progress=True, concurrency_limit=20 ) def use_result_as_input(url): if url: try: import requests from PIL import Image import io response = requests.get(url, timeout=10) if response.status_code == 200: return Image.open(io.BytesIO(response.content)) except: pass return None single_use_as_input_btn.click( fn=use_result_as_input, inputs=[single_output_url], outputs=[single_input_image] ) # ============================================================================= # Tab 2: 多图编辑 # ============================================================================= with gr.Tab(t("tab_multi_image_edit", "en")) as multi_edit_tab: with gr.Row(): with gr.Column(scale=1): gr.Markdown(t("multi_image_upload_header", "en")) # 3个图片组件放在同一排 with gr.Row(): multi_input_image1 = gr.Image(label=t("multi_image1_label", "en"), type="pil", height=200, elem_classes=["upload-area"]) multi_input_image2 = gr.Image(label=t("multi_image2_label", "en"), type="pil", height=200, elem_classes=["upload-area"]) multi_input_image3 = gr.Image(label=t("multi_image3_label", "en"), type="pil", height=200, elem_classes=["upload-area"]) gr.Markdown("📐 Output Size") multi_aspect_ratio = gr.Radio( choices=["Auto", "16:9", "4:3", "1:1", "3:4", "9:16"], value="Auto", label="Select aspect ratio", info="Choose output dimensions or Auto for original sizing" ) gr.Markdown(t("multi_prompt_header", "en")) multi_prompt = gr.Textbox(label=t("multi_prompt_label", "en"), placeholder=t("multi_prompt_placeholder", "en"), lines=3) multi_edit_btn = gr.Button(t("multi_edit_button", "en"), variant="primary", size="lg") with gr.Column(scale=1): gr.Markdown(t("editing_result_header", "en")) multi_output_image = gr.HTML(label=t("output_image_label", "en"), elem_classes=["result-area"]) multi_status = gr.Textbox(label=t("status_output_label", "en"), lines=2, interactive=False) multi_action_buttons = gr.HTML(visible=False) gr.Markdown(t("multi_examples_header", "en")) with gr.Row(): for prompt in ["Merge these two animals into one image", "Combine the elements from both images", "Create a scene with objects from all images"]: gr.Button(prompt, size="sm").click(lambda p=prompt: p, outputs=multi_prompt) multi_edit_btn.click( fn=multi_image_edit_interface, inputs=[multi_input_image1, multi_input_image2, multi_input_image3, multi_prompt, multi_aspect_ratio, lang_state], outputs=[multi_output_image, multi_status, multi_action_buttons], show_progress=True, concurrency_limit=20 ) # ============================================================================= # Tab 3: 文生图 # ============================================================================= with gr.Tab(t("tab_text_to_image", "en")) as t2i_tab: with gr.Row(): with gr.Column(scale=1): gr.Markdown(t("t2i_prompt_header", "en")) t2i_prompt = gr.Textbox(label=t("t2i_prompt_label", "en"), placeholder=t("t2i_prompt_placeholder", "en"), lines=5) gr.Markdown("📐 Output Size") t2i_aspect_ratio = gr.Radio( choices=["16:9", "4:3", "1:1", "3:4", "9:16"], value="1:1", label="Select aspect ratio", info="Choose output dimensions for generated image" ) t2i_btn = gr.Button(t("t2i_generate_button", "en"), variant="primary", size="lg") with gr.Column(scale=1): gr.Markdown(t("t2i_result_header", "en")) t2i_output_image = gr.HTML(label=t("t2i_output_label", "en"), elem_classes=["result-area"]) t2i_output_url = gr.State() # 保存URL用于生成按钮链接 t2i_status = gr.Textbox(label=t("status_output_label", "en"), lines=2, interactive=False) t2i_action_buttons = gr.HTML(visible=False) gr.Markdown(t("t2i_examples_header", "en")) with gr.Row(): for prompt in ["A beautiful young woman standing by the seaside at sunset", "A majestic dragon flying over a medieval castle", "A cute cat wearing a wizard hat, digital art", "Futuristic city skyline at night with neon lights"]: gr.Button(prompt, size="sm").click(lambda p=prompt: p, outputs=t2i_prompt) t2i_btn.click( fn=text_to_image_interface, inputs=[t2i_prompt, t2i_aspect_ratio, lang_state], outputs=[t2i_output_image, t2i_status, t2i_action_buttons], show_progress=True, concurrency_limit=20 ) # ============================================================================= # Tab 4: 图片放大 # ============================================================================= with gr.Tab(t("tab_image_upscale", "en")) as upscale_tab: with gr.Row(): with gr.Column(scale=1): gr.Markdown(t("upscale_upload_header", "en")) upscale_input_image = gr.Image(label=t("upscale_input_label", "en"), type="pil", height=400, elem_classes=["upload-area"]) upscale_btn = gr.Button(t("upscale_button", "en"), variant="primary", size="lg") with gr.Column(scale=1): gr.Markdown(t("upscale_result_header", "en")) upscale_output_image = gr.HTML(label=t("upscale_output_label", "en"), elem_classes=["result-area"]) upscale_status = gr.Textbox(label=t("status_output_label", "en"), lines=2, interactive=False) upscale_action_buttons = gr.HTML(visible=False) upscale_btn.click( fn=image_upscale_interface, inputs=[upscale_input_image, lang_state], outputs=[upscale_output_image, upscale_status, upscale_action_buttons], show_progress=True, concurrency_limit=20 ) # ============================================================================= # Tab 5: 换脸 # ============================================================================= with gr.Tab(t("tab_face_swap", "en")) as faceswap_tab: with gr.Row(): with gr.Column(scale=1): gr.Markdown(t("faceswap_target_header", "en")) gr.Markdown("*If multiple faces exist, draw on the face you want to replace*", elem_classes=["hint-text"]) faceswap_target_editor = gr.ImageEditor( label=t("faceswap_target_label", "en"), type="pil", height=350, brush=gr.Brush(colors=["#FFFFFF"], default_size=80, color_mode="fixed"), eraser=gr.Eraser(default_size=40), layers=False, sources=["upload", "clipboard"] ) gr.Markdown(t("faceswap_source_header", "en")) faceswap_source = gr.Image(label=t("faceswap_source_label", "en"), type="pil", height=256) faceswap_btn = gr.Button(t("faceswap_button", "en"), variant="primary", size="lg") with gr.Column(scale=1): gr.Markdown(t("faceswap_result_header", "en")) faceswap_output = gr.HTML(label=t("faceswap_output_label", "en"), elem_classes=["result-area"]) faceswap_status = gr.Textbox(label=t("status_output_label", "en"), lines=2, interactive=False) faceswap_action_buttons = gr.HTML(visible=False) faceswap_btn.click( fn=face_swap_interface, inputs=[faceswap_target_editor, faceswap_source, lang_state], outputs=[faceswap_output, faceswap_status, faceswap_action_buttons], show_progress=True, concurrency_limit=20 ) # ============================================================================= # Tab 6: 去水印 # ============================================================================= with gr.Tab("🧽 Remove Watermark") as watermark_tab: with gr.Row(): with gr.Column(scale=1): gr.Markdown("🖼️ Upload Image with Watermark") watermark_input = gr.Image(label="Select image to remove watermark", type="pil", height=400, elem_classes=["upload-area"]) watermark_force_removal = gr.Checkbox( label="💪 Force Removal", info="Ultimate AI-powered watermark removal. AI analyzes the watermark for better results.", value=False ) watermark_btn = gr.Button("🧽 Remove Watermark", variant="primary", size="lg") with gr.Column(scale=1): gr.Markdown("🎯 Result") watermark_output = gr.HTML(label="Image without watermark", elem_classes=["result-area"]) watermark_use_as_input_btn = gr.Button("🔄 Use as Input (Try Again)", variant="secondary", size="sm") watermark_status = gr.Textbox(label="Processing status", lines=2, interactive=False) watermark_action_buttons = gr.HTML(visible=False) watermark_btn.click( fn=watermark_removal_interface, inputs=[watermark_input, watermark_force_removal, lang_state], outputs=[watermark_output, watermark_status, watermark_action_buttons], show_progress=True, concurrency_limit=20 ) # 定义一个函数来实现"使用结果作为输入"功能 def watermark_use_result(output_html): # 从HTML中提取图片URL并下载 if output_html and 'src=' in str(output_html): import re match = re.search(r"src='([^']+)'", str(output_html)) if match: url = match.group(1) try: import requests from PIL import Image import io response = requests.get(url, timeout=10) if response.status_code == 200: return Image.open(io.BytesIO(response.content)) except: pass return None watermark_use_as_input_btn.click( fn=watermark_use_result, inputs=[watermark_output], outputs=[watermark_input] ) # ============================================================================= # SEO内容区域 # ============================================================================= seo_html = gr.HTML()
def get_seo_html(lang): if lang in ["zh", "hi", "ru"]: return "" return f""" <div style="width: 100%; margin: 50px 0; padding: 0 20px;"> <!-- Unlimited Access CTA - Top --> <div style="text-align: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 40px; border-radius: 20px; margin: 40px 0;"> <h2 style="margin: 0 0 20px 0; font-size: 2.2em; font-weight: 700;">🎨 {t('seo_unlimited_title', lang)}</h2> <p style="margin: 0 0 25px 0; font-size: 1.2em; opacity: 0.95; line-height: 1.6;">{t('seo_unlimited_desc', lang)}</p> <div style="display: flex; justify-content: center; gap: 25px; flex-wrap: wrap; margin: 30px 0;"> <a href="https://omnicreator.net/#generator" target="_blank" style=" display: inline-flex; align-items: center; justify-content: center; padding: 20px 40px; background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%); color: white; text-decoration: none; border-radius: 15px; font-weight: 700; font-size: 18px; min-width: 250px; box-shadow: 0 8px 25px rgba(255, 107, 107, 0.4); ">🚀 {t('seo_unlimited_button', lang)}</a> </div> </div>
<!-- OmniAI Model Introduction --> <div style="background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); padding: 35px; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); margin: 40px 0;"> <h2 style="color: #2c3e50; margin: 0 0 20px 0; font-size: 1.9em; font-weight: 700; text-align: center;"> 🤖 About Omni Creator 2.0 - 8B Multi-Modal Generation Model </h2> <div style="line-height: 1.8; font-size: 1.05em;"> <p style="color: #555; margin-bottom: 20px;"> <strong style="color: #667eea;">OmniAI</strong> is an 8-billion parameter multi-modal generation model developed by the OmniCreator research team. Through extensive training on massive video datasets, we discovered that the network can simultaneously acquire text, image, and video editing and generation capabilities. </p> <p style="color: #555; margin-bottom: 20px;"> That's why we call it the <strong style="color: #e74c3c;">Omni Creator</strong> - it handles everything from text-to-image, image editing, to video generation with a single unified architecture. </p> </div> </div> <!-- Performance Highlights --> <div style="background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%); color: white; padding: 40px; border-radius: 20px; margin: 40px 0;"> <h3 style="margin: 0 0 25px 0; font-size: 1.6em; font-weight: 700; text-align: center;">⚡ Performance Highlights</h3> <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin: 20px 0;"> <div style="background: rgba(255,255,255,0.15); padding: 20px; border-radius: 12px; text-align: center;"> <h4 style="margin: 0 0 10px 0; font-size: 1.2em;">🏁 Image Generation</h4> <p style="margin: 0; opacity: 0.95; font-size: 0.95em;"><strong>896×896 in under 10 seconds</strong> on RTX 5090 (32GB VRAM)</p> </div> <div style="background: rgba(255,255,255,0.15); padding: 20px; border-radius: 12px; text-align: center;"> <h4 style="margin: 0 0 10px 0; font-size: 1.2em;">🎥 Video Generation</h4> <p style="margin: 0; opacity: 0.95; font-size: 0.95em;"><strong>3-second 320p video in 30 seconds</strong></p> </div> <div style="background: rgba(255,255,255,0.15); padding: 20px; border-radius: 12px; text-align: center;"> <h4 style="margin: 0 0 10px 0; font-size: 1.2em;">💡 Knowledge Distillation</h4> <p style="margin: 0; opacity: 0.95; font-size: 0.95em;">Real-time inference performance achieved</p> </div> </div> </div>
<!-- Capabilities --> <div style="background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 50%, #fecfef 100%); padding: 30px; border-radius: 15px; margin: 40px 0;"> <h3 style="color: #8b5cf6; text-align: center; margin: 0 0 25px 0; font-size: 1.5em; font-weight: 700;"> 🎨 What Omni Model Can Do </h3> <p style="color: #555; text-align: center; margin-bottom: 20px;"> This Space demonstrates just a <strong>small fraction</strong> of what the Omni model can do. Beyond what you see here, it can also perform: </p> <div style="display: flex; flex-wrap: wrap; gap: 12px; justify-content: center; margin: 15px 0;"> <span style="background: rgba(139,92,246,0.2); color: #7c3aed; padding: 10px 18px; border-radius: 25px; font-weight: 500;">👗 Virtual Try-On</span> <span style="background: rgba(139,92,246,0.2); color: #7c3aed; padding: 10px 18px; border-radius: 25px; font-weight: 500;">🌅 Background Replacement</span> <span style="background: rgba(139,92,246,0.2); color: #7c3aed; padding: 10px 18px; border-radius: 25px; font-weight: 500;">💇 Hairstyle Changer</span> <span style="background: rgba(139,92,246,0.2); color: #7c3aed; padding: 10px 18px; border-radius: 25px; font-weight: 500;">📄 Poster Editing</span> <span style="background: rgba(139,92,246,0.2); color: #7c3aed; padding: 10px 18px; border-radius: 25px; font-weight: 500;">🎨 Style Transfer</span> <span style="background: rgba(139,92,246,0.2); color: #7c3aed; padding: 10px 18px; border-radius: 25px; font-weight: 500;">+ dozens more...</span> </div> <p style="color: #666; font-style: italic; text-align: center; margin-top: 20px;"> No fine-tuning required - just modify the prompt and input parameters! </p> </div> </div> """ # 收集所有需要更新的UI组件 all_ui_components = [ header_title, news_banner, single_edit_tab, multi_edit_tab, t2i_tab, upscale_tab, faceswap_tab, watermark_tab, seo_html, ]
def update_ui_lang(lang): show_banner = lang not in ["zh", "hi", "ru"] return { header_title: gr.update(value=f""" <div style="text-align: center; margin: 20px auto 10px auto; max-width: 800px;"> <h1 style="color: #2c3e50; margin: 0; font-size: 3.5em; font-weight: 800; letter-spacing: 3px;"> {t('header_title', lang)} </h1> </div>"""), news_banner: gr.update(visible=show_banner), single_edit_tab: gr.update(label=t("tab_single_image_edit", lang)), multi_edit_tab: gr.update(label=t("tab_multi_image_edit", lang)), t2i_tab: gr.update(label=t("tab_text_to_image", lang)), upscale_tab: gr.update(label=t("tab_image_upscale", lang)), faceswap_tab: gr.update(label=t("tab_face_swap", lang)), watermark_tab: gr.update(label="🧽 Remove Watermark"), seo_html: gr.update(value=get_seo_html(lang)), }
def on_lang_change(lang): return lang, *update_ui_lang(lang).values() lang_dropdown.change( on_lang_change, inputs=[lang_dropdown], outputs=[lang_state] + all_ui_components )
ip_query_state = gr.State({"status": "pending", "ip": None, "lang": "en"}) def on_load_immediate(request: gr.Request): client_ip = None try: client_ip = request.client.host headers = dict(request.headers) if hasattr(request, 'headers') else {} x_forwarded_for = headers.get('x-forwarded-for') or headers.get('X-Forwarded-For') if x_forwarded_for: client_ip = x_forwarded_for.split(',')[0].strip() except Exception: client_ip = "unknown" try: if client_ip in util.IP_Country_Cache: cached_lang = get_lang_from_ip(client_ip) query_state = {"ip": client_ip, "cached": True} return cached_lang, cached_lang, query_state, *update_ui_lang(cached_lang).values() detected_lang = get_lang_from_ip(client_ip) query_state = {"ip": client_ip, "cached": False} return detected_lang, detected_lang, query_state, *update_ui_lang(detected_lang).values() except Exception: query_state = {"ip": client_ip or "unknown", "cached": False} return "en", "en", query_state, *update_ui_lang("en").values()
app.load( on_load_immediate, inputs=None, outputs=[lang_state, lang_dropdown, ip_query_state] + all_ui_components, )
return app
if __name__ == "__main__": app = create_app() app.queue( default_concurrency_limit=20, max_size=50, api_open=False ) app.launch( server_name="0.0.0.0", show_error=True, quiet=False, max_threads=40, height=800, favicon_path=None )123456789101112131415161718192021222324252627282930313233343536"""i18n loader for encrypted translation files"""import sysimport importlib.utilfrom pathlib import Path
def load_pyc_module(module_name, pyc_path): """Load a .pyc module using importlib""" spec = importlib.util.spec_from_file_location(module_name, pyc_path) if spec is None or spec.loader is None: raise ImportError(f"Cannot load module {module_name} from {pyc_path}") module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) return module
def load_translations(): """Load all encrypted translation files""" translations = {} i18n_dir = Path(__file__).parent # List all .pyc files in i18n directory for pyc_file in i18n_dir.glob("*.pyc"): lang = pyc_file.stem # Get language code from filename try: module = load_pyc_module(f"i18n_{lang}", pyc_file) if hasattr(module, 'data'): translations[lang] = module.data except Exception as e: print(f"Failed to load {pyc_file.name}: {e}") return translations
# Auto-load translations when module is importedtranslations = load_translations()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960"""Minimal app loader for Omni-Image-EditorThis app loads the compiled, obfuscated modules from __lib__"""import sysfrom pathlib import Pathimport importlib.util
# Add __lib__ to path to import compiled moduleslib_dir = Path(__file__).parent / "__lib__"if not lib_dir.exists(): raise RuntimeError(f"Compiled library directory not found: {lib_dir}")
sys.path.insert(0, str(lib_dir))
def load_pyc_module(module_name, pyc_path): """Load a .pyc module using importlib""" spec = importlib.util.spec_from_file_location(module_name, pyc_path) if spec is None or spec.loader is None: raise ImportError(f"Cannot load module {module_name} from {pyc_path}") module = importlib.util.module_from_spec(spec) sys.modules[module_name] = module spec.loader.exec_module(module) return module
try: # Load compiled modules util_module = load_pyc_module("util", lib_dir / "util.pyc") nfsw_module = load_pyc_module("nfsw", lib_dir / "nfsw.pyc") # Import app module (source file) import app as app_module
# Create and launch app app = app_module.create_app() app.queue( default_concurrency_limit=20, max_size=50, api_open=False ) app.launch( server_name="0.0.0.0", show_error=True, quiet=False, max_threads=40, height=800, favicon_path=None )
except ImportError as e: print(f"Failed to import compiled modules: {e}") print("Make sure to run build_encrypted.py first to compile the modules") import traceback traceback.print_exc() sys.exit(1)except Exception as e: print(f"Error running app: {e}") import traceback traceback.print_exc() sys.exit(1)1234{ "0": "normal", "1": "nsfw"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934import torchimport torch.nn as nnimport torch.nn.functional as Ffrom typing import Optional, Tuple, Union, List, Dict, Any, Callablefrom dataclasses import dataclassimport numpy as npfrom PIL import Imageimport torchvision.transforms as Tfrom torchvision.transforms.functional import to_tensor, normalizeimport warningsfrom contextlib import contextmanagerfrom functools import wraps
from transformers import PretrainedConfig, PreTrainedModel, CLIPTextModel, CLIPTokenizerfrom transformers.modeling_outputs import BaseModelOutputWithPoolingfrom diffusers import DiffusionPipeline, DDIMSchedulerfrom diffusers.configuration_utils import ConfigMixin, register_to_configfrom diffusers.models.modeling_utils import ModelMixinfrom diffusers.utils import BaseOutput
# Optimization importstry: import transformer_engine.pytorch as te from transformer_engine.common import recipe HAS_TRANSFORMER_ENGINE = Trueexcept ImportError: HAS_TRANSFORMER_ENGINE = False
try: from torch._dynamo import config as dynamo_config HAS_TORCH_COMPILE = hasattr(torch, 'compile')except ImportError: HAS_TORCH_COMPILE = False
# -----------------------------------------------------------------------------# 1. Advanced Configuration (8B Scale)# -----------------------------------------------------------------------------
class OmniMMDitV2Config(PretrainedConfig): model_type = "omnimm_dit_v2" def __init__( self, vocab_size: int = 49408, hidden_size: int = 4096, # 4096 dim for ~7B-8B scale intermediate_size: int = 11008, # Llama-style MLP expansion num_hidden_layers: int = 32, # Deep network num_attention_heads: int = 32, num_key_value_heads: Optional[int] = 8, # GQA (Grouped Query Attention) hidden_act: str = "silu", max_position_embeddings: int = 4096, initializer_range: float = 0.02, rms_norm_eps: float = 1e-5, use_cache: bool = True, pad_token_id: int = 0, bos_token_id: int = 1, eos_token_id: int = 2, tie_word_embeddings: bool = False, rope_theta: float = 10000.0, # DiT Specifics patch_size: int = 2, in_channels: int = 4, # VAE Latent channels out_channels: int = 4, # x2 for variance if learned frequency_embedding_size: int = 256, # Multi-Modal Specifics max_condition_images: int = 3, # Support 1-3 input images visual_embed_dim: int = 1024, # e.g., SigLIP or CLIP Vision text_embed_dim: int = 4096, # T5-XXL or similar use_temporal_attention: bool = True, # For Video generation # Optimization Configs use_fp8_quantization: bool = False, use_compilation: bool = False, compile_mode: str = "reduce-overhead", use_flash_attention: bool = True, **kwargs, ): self.vocab_size = vocab_size self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.num_hidden_layers = num_hidden_layers self.num_attention_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.max_position_embeddings = max_position_embeddings self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.patch_size = patch_size self.in_channels = in_channels self.out_channels = out_channels self.frequency_embedding_size = frequency_embedding_size self.max_condition_images = max_condition_images self.visual_embed_dim = visual_embed_dim self.text_embed_dim = text_embed_dim self.use_temporal_attention = use_temporal_attention self.use_fp8_quantization = use_fp8_quantization self.use_compilation = use_compilation self.compile_mode = compile_mode self.use_flash_attention = use_flash_attention super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, )
# -----------------------------------------------------------------------------# 2. Professional Building Blocks (RoPE, SwiGLU, AdaLN)# -----------------------------------------------------------------------------
class OmniRMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps
def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype)
class OmniRotaryEmbedding(nn.Module): """Complex implementation of Rotary Positional Embeddings for DiT""" def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): super().__init__() self.dim = dim self.max_position_embeddings = max_position_embeddings self.base = base inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim)) self.register_buffer("inv_freq", inv_freq, persistent=False)
def forward(self, x, seq_len=None): t = torch.arange(seq_len or x.shape[1], device=x.device).type_as(self.inv_freq) freqs = torch.outer(t, self.inv_freq) emb = torch.cat((freqs, freqs), dim=-1) return emb.cos(), emb.sin()
class OmniSwiGLU(nn.Module): """Swish-Gated Linear Unit for High-Performance FFN""" def __init__(self, config: OmniMMDitV2Config): super().__init__() self.w1 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False) self.w2 = nn.Linear(config.intermediate_size, config.hidden_size, bias=False) self.w3 = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
def forward(self, x): return self.w2(F.silu(self.w1(x)) * self.w3(x))
class TimestepEmbedder(nn.Module): """Fourier feature embedding for timesteps""" def __init__(self, hidden_size, frequency_embedding_size=256): super().__init__() self.mlp = nn.Sequential( nn.Linear(frequency_embedding_size, hidden_size, bias=True), nn.SiLU(), nn.Linear(hidden_size, hidden_size, bias=True), ) self.frequency_embedding_size = frequency_embedding_size
@staticmethod def timestep_embedding(t, dim, max_period=10000): half = dim // 2 freqs = torch.exp( -torch.log(torch.tensor(max_period)) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=t.device) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def forward(self, t, dtype): t_freq = self.timestep_embedding(t, self.frequency_embedding_size).to(dtype) return self.mlp(t_freq)
# -----------------------------------------------------------------------------# 2.5. Data Processing Utilities# -----------------------------------------------------------------------------
class OmniImageProcessor: """Advanced image preprocessing for multi-modal diffusion models""" def __init__( self, image_mean: List[float] = [0.485, 0.456, 0.406], image_std: List[float] = [0.229, 0.224, 0.225], size: Tuple[int, int] = (512, 512), interpolation: str = "bicubic", do_normalize: bool = True, do_center_crop: bool = False, ): self.image_mean = image_mean self.image_std = image_std self.size = size self.do_normalize = do_normalize self.do_center_crop = do_center_crop # Build transform pipeline transforms_list = [] if do_center_crop: transforms_list.append(T.CenterCrop(min(size))) interp_mode = { "bilinear": T.InterpolationMode.BILINEAR, "bicubic": T.InterpolationMode.BICUBIC, "lanczos": T.InterpolationMode.LANCZOS, }.get(interpolation, T.InterpolationMode.BICUBIC) transforms_list.append(T.Resize(size, interpolation=interp_mode, antialias=True)) self.transform = T.Compose(transforms_list) def preprocess( self, images: Union[Image.Image, np.ndarray, torch.Tensor, List[Union[Image.Image, np.ndarray, torch.Tensor]]], return_tensors: str = "pt", ) -> torch.Tensor: """ Preprocess images for model input. Args: images: Single image or list of images (PIL, numpy, or torch) return_tensors: Return type ("pt" for PyTorch) Returns: Preprocessed image tensor [B, C, H, W] """ if not isinstance(images, list): images = [images] processed = [] for img in images: # Convert to PIL if needed if isinstance(img, np.ndarray): if img.dtype == np.uint8: img = Image.fromarray(img) else: img = Image.fromarray((img * 255).astype(np.uint8)) elif isinstance(img, torch.Tensor): img = T.ToPILImage()(img) # Apply transforms img = self.transform(img) # Convert to tensor if not isinstance(img, torch.Tensor): img = to_tensor(img) # Normalize if self.do_normalize: img = normalize(img, self.image_mean, self.image_std) processed.append(img) # Stack into batch if return_tensors == "pt": return torch.stack(processed, dim=0) return processed def postprocess( self, images: torch.Tensor, output_type: str = "pil", ) -> Union[List[Image.Image], np.ndarray, torch.Tensor]: """ Postprocess model output to desired format. Args: images: Model output tensor [B, C, H, W] output_type: "pil", "np", or "pt" Returns: Processed images in requested format """ # Denormalize if needed if self.do_normalize: mean = torch.tensor(self.image_mean).view(1, 3, 1, 1).to(images.device) std = torch.tensor(self.image_std).view(1, 3, 1, 1).to(images.device) images = images * std + mean # Clamp to valid range images = torch.clamp(images, 0, 1) if output_type == "pil": images = images.cpu().permute(0, 2, 3, 1).numpy() images = (images * 255).round().astype(np.uint8) return [Image.fromarray(img) for img in images] elif output_type == "np": return images.cpu().numpy() else: return images
class OmniVideoProcessor: """Video frame processing for temporal diffusion models""" def __init__( self, image_processor: OmniImageProcessor, num_frames: int = 16, frame_stride: int = 1, ): self.image_processor = image_processor self.num_frames = num_frames self.frame_stride = frame_stride def preprocess_video( self, video_frames: Union[List[Image.Image], np.ndarray, torch.Tensor], temporal_interpolation: bool = True, ) -> torch.Tensor: """ Preprocess video frames for temporal model. Args: video_frames: List of PIL images, numpy array [T, H, W, C], or tensor [T, C, H, W] temporal_interpolation: Whether to interpolate to target frame count Returns: Preprocessed video tensor [B, C, T, H, W] """ # Convert to list of PIL images if isinstance(video_frames, np.ndarray): if video_frames.ndim == 4: # [T, H, W, C] video_frames = [Image.fromarray(frame) for frame in video_frames] else: raise ValueError(f"Expected 4D numpy array, got shape {video_frames.shape}") elif isinstance(video_frames, torch.Tensor): if video_frames.ndim == 4: # [T, C, H, W] video_frames = [T.ToPILImage()(frame) for frame in video_frames] else: raise ValueError(f"Expected 4D tensor, got shape {video_frames.shape}") # Sample frames if needed total_frames = len(video_frames) if temporal_interpolation and total_frames != self.num_frames: indices = np.linspace(0, total_frames - 1, self.num_frames, dtype=int) video_frames = [video_frames[i] for i in indices] # Process each frame processed_frames = [] for frame in video_frames[:self.num_frames]: frame_tensor = self.image_processor.preprocess(frame, return_tensors="pt")[0] processed_frames.append(frame_tensor) # Stack: [T, C, H, W] -> [1, C, T, H, W] video_tensor = torch.stack(processed_frames, dim=1).unsqueeze(0) return video_tensor def postprocess_video( self, video_tensor: torch.Tensor, output_type: str = "pil", ) -> Union[List[Image.Image], np.ndarray, torch.Tensor]: """ Postprocess video output. Args: video_tensor: Model output [B, C, T, H, W] or [B, T, C, H, W] output_type: "pil", "np", or "pt" Returns: Processed video frames """ # Normalize dimensions to [B, T, C, H, W] if video_tensor.ndim == 5: if video_tensor.shape[1] in [3, 4]: # [B, C, T, H, W] video_tensor = video_tensor.permute(0, 2, 1, 3, 4) batch_size, num_frames = video_tensor.shape[:2] # Process each frame all_frames = [] for b in range(batch_size): frames = [] for t in range(num_frames): frame = video_tensor[b, t] # [C, H, W] frame = frame.unsqueeze(0) # [1, C, H, W] processed = self.image_processor.postprocess(frame, output_type=output_type) frames.extend(processed) all_frames.append(frames) return all_frames[0] if batch_size == 1 else all_frames
class OmniLatentProcessor: """VAE latent space encoding/decoding with scaling and normalization""" def __init__( self, vae: Any, scaling_factor: float = 0.18215, do_normalize_latents: bool = True, ): self.vae = vae self.scaling_factor = scaling_factor self.do_normalize_latents = do_normalize_latents @torch.no_grad() def encode( self, images: torch.Tensor, generator: Optional[torch.Generator] = None, return_dict: bool = False, ) -> torch.Tensor: """ Encode images to latent space. Args: images: Input images [B, C, H, W] in range [-1, 1] generator: Random generator for sampling return_dict: Whether to return dict or tensor Returns: Latent codes [B, 4, H//8, W//8] """ # VAE expects input in [-1, 1] if images.min() >= 0: images = images * 2.0 - 1.0 # Encode latent_dist = self.vae.encode(images).latent_dist latents = latent_dist.sample(generator=generator) # Scale latents latents = latents * self.scaling_factor # Additional normalization for stability if self.do_normalize_latents: latents = (latents - latents.mean()) / (latents.std() + 1e-6) return latents if not return_dict else {"latents": latents} @torch.no_grad() def decode( self, latents: torch.Tensor, return_dict: bool = False, ) -> torch.Tensor: """ Decode latents to image space. Args: latents: Latent codes [B, 4, H//8, W//8] return_dict: Whether to return dict or tensor Returns: Decoded images [B, 3, H, W] in range [-1, 1] """ # Denormalize if needed if self.do_normalize_latents: # Assume identity transform for simplicity in decoding pass # Unscale latents = latents / self.scaling_factor # Decode images = self.vae.decode(latents).sample return images if not return_dict else {"images": images} @torch.no_grad() def encode_video( self, video_frames: torch.Tensor, generator: Optional[torch.Generator] = None, ) -> torch.Tensor: """ Encode video frames to latent space. Args: video_frames: Input video [B, C, T, H, W] or [B, T, C, H, W] generator: Random generator Returns: Video latents [B, 4, T, H//8, W//8] """ # Reshape to process frames independently if video_frames.shape[2] not in [3, 4]: # [B, T, C, H, W] B, T, C, H, W = video_frames.shape video_frames = video_frames.reshape(B * T, C, H, W) # Encode latents = self.encode(video_frames, generator=generator) # Reshape back latents = latents.reshape(B, T, *latents.shape[1:]) latents = latents.permute(0, 2, 1, 3, 4) # [B, 4, T, H//8, W//8] else: # [B, C, T, H, W] B, C, T, H, W = video_frames.shape video_frames = video_frames.permute(0, 2, 1, 3, 4).reshape(B * T, C, H, W) latents = self.encode(video_frames, generator=generator) latents = latents.reshape(B, T, *latents.shape[1:]) latents = latents.permute(0, 2, 1, 3, 4) return latents
# -----------------------------------------------------------------------------# 3. Core Architecture: OmniMMDitBlock (3D-Attention + Modulation)# -----------------------------------------------------------------------------
class OmniMMDitBlock(nn.Module): def __init__(self, config: OmniMMDitV2Config, layer_idx: int): super().__init__() self.layer_idx = layer_idx self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.head_dim = config.hidden_size // config.num_attention_heads # Self-Attention with QK-Norm self.norm1 = OmniRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.attn = nn.MultiheadAttention( config.hidden_size, config.num_attention_heads, batch_first=True ) self.q_norm = OmniRMSNorm(self.head_dim, eps=config.rms_norm_eps) self.k_norm = OmniRMSNorm(self.head_dim, eps=config.rms_norm_eps)
# Cross-Attention for multimodal fusion self.norm2 = OmniRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.cross_attn = nn.MultiheadAttention( config.hidden_size, config.num_attention_heads, batch_first=True )
# Feed-Forward Network with SwiGLU activation self.norm3 = OmniRMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.ffn = OmniSwiGLU(config)
# Adaptive Layer Normalization with zero initialization self.adaLN_modulation = nn.Sequential( nn.SiLU(), nn.Linear(config.hidden_size, 6 * config.hidden_size, bias=True) )
def forward( self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, # Text embeddings visual_context: Optional[torch.Tensor], # Reference image embeddings timestep_emb: torch.Tensor, rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, ) -> torch.Tensor: # AdaLN Modulation shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = ( self.adaLN_modulation(timestep_emb)[:, None].chunk(6, dim=-1) )
# Self-Attention block normed_hidden = self.norm1(hidden_states) normed_hidden = normed_hidden * (1 + scale_msa) + shift_msa attn_output, _ = self.attn(normed_hidden, normed_hidden, normed_hidden) hidden_states = hidden_states + gate_msa * attn_output
# Cross-Attention with multimodal conditioning if visual_context is not None: context = torch.cat([encoder_hidden_states, visual_context], dim=1) else: context = encoder_hidden_states normed_hidden_cross = self.norm2(hidden_states) cross_output, _ = self.cross_attn(normed_hidden_cross, context, context) hidden_states = hidden_states + cross_output
# Feed-Forward block normed_ffn = self.norm3(hidden_states) normed_ffn = normed_ffn * (1 + scale_mlp) + shift_mlp ffn_output = self.ffn(normed_ffn) hidden_states = hidden_states + gate_mlp * ffn_output
return hidden_states
# -----------------------------------------------------------------------------# 4. The Model: OmniMMDitV2# -----------------------------------------------------------------------------
class OmniMMDitV2(ModelMixin, PreTrainedModel): """ Omni-Modal Multi-Dimensional Diffusion Transformer V2. Supports: Text-to-Image, Image-to-Image (Edit), Image-to-Video. """ config_class = OmniMMDitV2Config _supports_gradient_checkpointing = True
def __init__(self, config: OmniMMDitV2Config): super().__init__(config) self.config = config
# Initialize optimizer for advanced features self.optimizer = ModelOptimizer( fp8_config=FP8Config(enabled=config.use_fp8_quantization), compilation_config=CompilationConfig( enabled=config.use_compilation, mode=config.compile_mode, ), mixed_precision_config=MixedPrecisionConfig( enabled=True, dtype="bfloat16", ), )
# Input Latent Projection (Patchify) self.x_embedder = nn.Linear(config.in_channels * config.patch_size * config.patch_size, config.hidden_size, bias=True) # Time & Vector Embeddings self.t_embedder = TimestepEmbedder(config.hidden_size, config.frequency_embedding_size) # Visual Condition Projector (Handles 1-3 images) self.visual_projector = nn.Sequential( nn.Linear(config.visual_embed_dim, config.hidden_size), nn.LayerNorm(config.hidden_size), nn.Linear(config.hidden_size, config.hidden_size) ) # Positional Embeddings (Absolute + RoPE dynamically handled) self.pos_embed = nn.Parameter(torch.zeros(1, config.max_position_embeddings, config.hidden_size), requires_grad=False)
# Transformer Backbone self.blocks = nn.ModuleList([ OmniMMDitBlock(config, i) for i in range(config.num_hidden_layers) ]) # Final Layer (AdaLN-Zero + Linear) self.final_layer = nn.Sequential( OmniRMSNorm(config.hidden_size, eps=config.rms_norm_eps), nn.Linear(config.hidden_size, config.patch_size * config.patch_size * config.out_channels, bias=True) ) self.initialize_weights() # Apply optimizations if enabled if config.use_fp8_quantization or config.use_compilation: self._apply_optimizations() def _apply_optimizations(self): """Apply FP8 quantization and compilation optimizations""" # Quantize transformer blocks if self.config.use_fp8_quantization: for i, block in enumerate(self.blocks): self.blocks[i] = self.optimizer.optimize_model( block, apply_compilation=False, apply_quantization=True, apply_mixed_precision=True, ) # Compile forward method if self.config.use_compilation and HAS_TORCH_COMPILE: self.forward = torch.compile( self.forward, mode=self.config.compile_mode, dynamic=True, )
def initialize_weights(self): def _basic_init(module): if isinstance(module, nn.Linear): torch.nn.init.xavier_uniform_(module.weight) if module.bias is not None: nn.init.constant_(module.bias, 0) self.apply(_basic_init)
def unpatchify(self, x, h, w): c = self.config.out_channels p = self.config.patch_size h_ = h // p w_ = w // p x = x.reshape(shape=(x.shape[0], h_, w_, p, p, c)) x = torch.einsum('nhwpqc->nchpwq', x) imgs = x.reshape(shape=(x.shape[0], c, h, w)) return imgs
def forward( self, hidden_states: torch.Tensor, # Noisy Latents [B, C, H, W] or [B, C, F, H, W] timestep: torch.LongTensor, encoder_hidden_states: torch.Tensor, # Text Embeddings visual_conditions: Optional[List[torch.Tensor]] = None, # List of [B, L, D] video_frames: Optional[int] = None, # If generating video return_dict: bool = True, ) -> Union[torch.Tensor, BaseOutput]: batch_size, channels, _, _ = hidden_states.shape # Patchify input latents p = self.config.patch_size h, w = hidden_states.shape[-2], hidden_states.shape[-1] x = hidden_states.unfold(2, p, p).unfold(3, p, p) x = x.permute(0, 2, 3, 1, 4, 5).contiguous() x = x.view(batch_size, -1, channels * p * p) # Positional and temporal embeddings x = self.x_embedder(x) x = x + self.pos_embed[:, :x.shape[1], :] t = self.t_embedder(timestep, x.dtype) # Process visual conditioning visual_emb = None if visual_conditions is not None: concat_visuals = torch.cat(visual_conditions, dim=1) visual_emb = self.visual_projector(concat_visuals)
# Transformer blocks for block in self.blocks: x = block( hidden_states=x, encoder_hidden_states=encoder_hidden_states, visual_context=visual_emb, timestep_emb=t )
# Output projection x = self.final_layer[0](x) x = self.final_layer[1](x) # Unpatchify to image space output = self.unpatchify(x, h, w)
if not return_dict: return (output,)
return BaseOutput(sample=output)
# -----------------------------------------------------------------------------# 5. The "Fancy" Pipeline# -----------------------------------------------------------------------------
class OmniMMDitV2Pipeline(DiffusionPipeline): """ Omni-Modal Diffusion Transformer Pipeline. Supports text-guided image editing and video generation with multi-image conditioning and advanced guidance techniques. """ model: OmniMMDitV2 tokenizer: CLIPTokenizer text_encoder: CLIPTextModel vae: Any # AutoencoderKL scheduler: DDIMScheduler _optional_components = ["visual_encoder"]
def __init__( self, model: OmniMMDitV2, vae: Any, text_encoder: CLIPTextModel, tokenizer: CLIPTokenizer, scheduler: DDIMScheduler, visual_encoder: Optional[Any] = None, ): super().__init__() self.register_modules( model=model, vae=vae, text_encoder=text_encoder, tokenizer=tokenizer, scheduler=scheduler, visual_encoder=visual_encoder ) self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1) # Initialize data processors self.image_processor = OmniImageProcessor( size=(512, 512), interpolation="bicubic", do_normalize=True, ) self.video_processor = OmniVideoProcessor( image_processor=self.image_processor, num_frames=16, ) self.latent_processor = OmniLatentProcessor( vae=vae, scaling_factor=0.18215, ) # Initialize model optimizer self.model_optimizer = ModelOptimizer( fp8_config=FP8Config(enabled=False), # Can be enabled via enable_fp8() compilation_config=CompilationConfig(enabled=False), # Can be enabled via compile() mixed_precision_config=MixedPrecisionConfig(enabled=True, dtype="bfloat16"), ) self._is_compiled = False self._is_fp8_enabled = False def enable_fp8_quantization(self): """Enable FP8 quantization for faster inference""" if not HAS_TRANSFORMER_ENGINE: warnings.warn("Transformer Engine not available. Install with: pip install transformer-engine") return self self.model_optimizer.fp8_config.enabled = True self.model = self.model_optimizer.optimize_model( self.model, apply_compilation=False, apply_quantization=True, apply_mixed_precision=False, ) self._is_fp8_enabled = True return self def compile_model( self, mode: str = "reduce-overhead", fullgraph: bool = False, dynamic: bool = True, ): """ Compile model using torch.compile for faster inference. Args: mode: Compilation mode - "default", "reduce-overhead", "max-autotune" fullgraph: Whether to compile the entire model as one graph dynamic: Whether to enable dynamic shapes """ if not HAS_TORCH_COMPILE: warnings.warn("torch.compile not available. Upgrade to PyTorch 2.0+") return self self.model_optimizer.compilation_config = CompilationConfig( enabled=True, mode=mode, fullgraph=fullgraph, dynamic=dynamic, ) self.model = self.model_optimizer._compile_model(self.model) self._is_compiled = True return self def enable_optimizations( self, enable_fp8: bool = False, enable_compilation: bool = False, compilation_mode: str = "reduce-overhead", ): """ Enable all optimizations at once. Args: enable_fp8: Enable FP8 quantization enable_compilation: Enable torch.compile compilation_mode: Compilation mode for torch.compile """ if enable_fp8: self.enable_fp8_quantization() if enable_compilation: self.compile_model(mode=compilation_mode) return self
@torch.no_grad() def __call__( self, prompt: Union[str, List[str]] = None, input_images: Optional[List[Union[torch.Tensor, Any]]] = None, height: Optional[int] = 1024, width: Optional[int] = 1024, num_frames: Optional[int] = 1, num_inference_steps: int = 50, guidance_scale: float = 7.5, image_guidance_scale: float = 1.5, negative_prompt: Optional[Union[str, List[str]]] = None, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.Tensor] = None, output_type: Optional[str] = "pil", return_dict: bool = True, callback: Optional[Callable[[int, int, torch.Tensor], None]] = None, callback_steps: int = 1, use_optimized_inference: bool = True, **kwargs, ): # Use optimized inference context with optimized_inference_mode( enable_cudnn_benchmark=use_optimized_inference, enable_tf32=use_optimized_inference, enable_flash_sdp=use_optimized_inference, ): return self._forward_impl( prompt=prompt, input_images=input_images, height=height, width=width, num_frames=num_frames, num_inference_steps=num_inference_steps, guidance_scale=guidance_scale, image_guidance_scale=image_guidance_scale, negative_prompt=negative_prompt, eta=eta, generator=generator, latents=latents, output_type=output_type, return_dict=return_dict, callback=callback, callback_steps=callback_steps, **kwargs, ) def _forward_impl( self, prompt: Union[str, List[str]] = None, input_images: Optional[List[Union[torch.Tensor, Any]]] = None, height: Optional[int] = 1024, width: Optional[int] = 1024, num_frames: Optional[int] = 1, num_inference_steps: int = 50, guidance_scale: float = 7.5, image_guidance_scale: float = 1.5, negative_prompt: Optional[Union[str, List[str]]] = None, eta: float = 0.0, generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None, latents: Optional[torch.Tensor] = None, output_type: Optional[str] = "pil", return_dict: bool = True, callback: Optional[Callable[[int, int, torch.Tensor], None]] = None, callback_steps: int = 1, **kwargs, ): # Validate and set default dimensions height = height or self.model.config.sample_size * self.vae_scale_factor width = width or self.model.config.sample_size * self.vae_scale_factor
# Encode text prompts if isinstance(prompt, str): prompt = [prompt] batch_size = len(prompt) text_inputs = self.tokenizer( prompt, padding="max_length", max_length=self.tokenizer.model_max_length, truncation=True, return_tensors="pt" ) text_embeddings = self.text_encoder(text_inputs.input_ids.to(self.device))[0]
# Encode visual conditions with preprocessing visual_embeddings_list = [] if input_images: if not isinstance(input_images, list): input_images = [input_images] if len(input_images) > 3: raise ValueError("Maximum 3 reference images supported") for img in input_images: # Preprocess image if not isinstance(img, torch.Tensor): img_tensor = self.image_processor.preprocess(img, return_tensors="pt") else: img_tensor = img img_tensor = img_tensor.to(device=self.device, dtype=text_embeddings.dtype) # Encode with visual encoder if self.visual_encoder is not None: vis_emb = self.visual_encoder(img_tensor).last_hidden_state else: # Fallback: use VAE encoder + projection with torch.no_grad(): latent_features = self.vae.encode(img_tensor * 2 - 1).latent_dist.mode() B, C, H, W = latent_features.shape # Flatten spatial dims and project vis_emb = latent_features.flatten(2).transpose(1, 2) # [B, H*W, C] # Simple projection to visual_embed_dim if vis_emb.shape[-1] != self.model.config.visual_embed_dim: proj = nn.Linear(vis_emb.shape[-1], self.model.config.visual_embed_dim).to(self.device) vis_emb = proj(vis_emb) visual_embeddings_list.append(vis_emb)
# Prepare timesteps self.scheduler.set_timesteps(num_inference_steps, device=self.device) timesteps = self.scheduler.timesteps
# Initialize latent space num_channels_latents = self.model.config.in_channels shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor) if num_frames > 1: shape = (batch_size, num_channels_latents, num_frames, height // self.vae_scale_factor, width // self.vae_scale_factor)
latents = torch.randn(shape, generator=generator, device=self.device, dtype=text_embeddings.dtype) latents = latents * self.scheduler.init_noise_sigma
# Denoising loop with optimizations with self.progress_bar(total=num_inference_steps) as progress_bar: for i, t in enumerate(timesteps): latent_model_input = torch.cat([latents] * 2) if guidance_scale > 1.0 else latents latent_model_input = self.scheduler.scale_model_input(latent_model_input, t) # Use mixed precision autocast with self.model_optimizer.autocast_context(): noise_pred = self.model( hidden_states=latent_model_input, timestep=t, encoder_hidden_states=torch.cat([text_embeddings] * 2), visual_conditions=visual_embeddings_list * 2 if visual_embeddings_list else None, video_frames=num_frames ).sample
# Apply classifier-free guidance if guidance_scale > 1.0: noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) latents = self.scheduler.step(noise_pred, t, latents, eta=eta).prev_sample # Call callback if provided if callback is not None and i % callback_steps == 0: callback(i, t, latents) progress_bar.update()
# Decode latents with proper post-processing if output_type == "latent": output_images = latents else: # Decode latents to pixel space with torch.no_grad(): if num_frames > 1: # Video decoding: process frame by frame B, C, T, H, W = latents.shape latents_2d = latents.permute(0, 2, 1, 3, 4).reshape(B * T, C, H, W) decoded = self.latent_processor.decode(latents_2d) decoded = decoded.reshape(B, T, 3, H * 8, W * 8) # Convert to [0, 1] range decoded = (decoded / 2 + 0.5).clamp(0, 1) # Post-process video if output_type == "pil": output_images = self.video_processor.postprocess_video(decoded, output_type="pil") elif output_type == "np": output_images = decoded.cpu().numpy() else: output_images = decoded else: # Image decoding decoded = self.latent_processor.decode(latents) decoded = (decoded / 2 + 0.5).clamp(0, 1) # Post-process images if output_type == "pil": output_images = self.image_processor.postprocess(decoded, output_type="pil") elif output_type == "np": output_images = decoded.cpu().numpy() else: output_images = decoded
if not return_dict: return (output_images,)
return BaseOutput(images=output_images)
# -----------------------------------------------------------------------------# 6. Advanced Multi-Modal Window Attention Block (Audio + Video + Image)# -----------------------------------------------------------------------------
@dataclassclass MultiModalInput: """Container for multi-modal inputs""" image_embeds: Optional[torch.Tensor] = None # [B, L_img, D] video_embeds: Optional[torch.Tensor] = None # [B, T_video, L_vid, D] audio_embeds: Optional[torch.Tensor] = None # [B, T_audio, L_aud, D] attention_mask: Optional[torch.Tensor] = None # [B, total_length]
class TemporalWindowPartition(nn.Module): """ Partition temporal sequences into windows for efficient attention. Supports both uniform and adaptive windowing strategies. """ def __init__( self, window_size: int = 8, shift_size: int = 0, use_adaptive_window: bool = False, ): super().__init__() self.window_size = window_size self.shift_size = shift_size self.use_adaptive_window = use_adaptive_window def partition(self, x: torch.Tensor) -> Tuple[torch.Tensor, Dict[str, Any]]: """ Partition sequence into windows. Args: x: Input tensor [B, T, L, D] or [B, L, D] Returns: windowed: [B * num_windows, window_size, L, D] info: Dictionary with partition information """ if x.ndim == 3: # Static input (image) return x, {"is_temporal": False, "original_shape": x.shape} B, T, L, D = x.shape # Apply temporal shift for shifted window attention (Swin-Transformer style) if self.shift_size > 0: x = torch.roll(x, shifts=-self.shift_size, dims=1) # Pad if necessary pad_t = (self.window_size - T % self.window_size) % self.window_size if pad_t > 0: x = F.pad(x, (0, 0, 0, 0, 0, pad_t)) T_padded = T + pad_t num_windows = T_padded // self.window_size # Reshape into windows: [B, num_windows, window_size, L, D] x_windowed = x.view(B, num_windows, self.window_size, L, D) # Merge batch and window dims: [B * num_windows, window_size, L, D] x_windowed = x_windowed.view(B * num_windows, self.window_size, L, D) info = { "is_temporal": True, "original_shape": (B, T, L, D), "num_windows": num_windows, "pad_t": pad_t, } return x_windowed, info def merge(self, x_windowed: torch.Tensor, info: Dict[str, Any]) -> torch.Tensor: """ Merge windows back to original sequence. Args: x_windowed: Windowed tensor [B * num_windows, window_size, L, D] info: Partition information from partition() Returns: x: Merged tensor [B, T, L, D] or [B, L, D] """ if not info["is_temporal"]: return x_windowed B, T, L, D = info["original_shape"] num_windows = info["num_windows"] pad_t = info["pad_t"] # Reshape: [B * num_windows, window_size, L, D] -> [B, num_windows, window_size, L, D] x = x_windowed.view(B, num_windows, self.window_size, L, D) # Merge windows: [B, T_padded, L, D] x = x.view(B, num_windows * self.window_size, L, D) # Remove padding if pad_t > 0: x = x[:, :-pad_t, :, :] # Reverse temporal shift if self.shift_size > 0: x = torch.roll(x, shifts=self.shift_size, dims=1) return x
class WindowCrossAttention(nn.Module): """ Window-based Cross Attention with support for temporal sequences. Performs attention within local windows for computational efficiency. """ def __init__( self, dim: int, num_heads: int = 8, window_size: int = 8, qkv_bias: bool = True, attn_drop: float = 0.0, proj_drop: float = 0.0, use_relative_position_bias: bool = True, ): super().__init__() self.dim = dim self.num_heads = num_heads self.window_size = window_size self.head_dim = dim // num_heads self.scale = self.head_dim ** -0.5 # Query, Key, Value projections self.q_proj = nn.Linear(dim, dim, bias=qkv_bias) self.k_proj = nn.Linear(dim, dim, bias=qkv_bias) self.v_proj = nn.Linear(dim, dim, bias=qkv_bias) # QK Normalization for stability self.q_norm = OmniRMSNorm(self.head_dim) self.k_norm = OmniRMSNorm(self.head_dim) # Attention dropout self.attn_drop = nn.Dropout(attn_drop) # Output projection self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) # Relative position bias (for temporal coherence) self.use_relative_position_bias = use_relative_position_bias if use_relative_position_bias: # Temporal relative position bias self.relative_position_bias_table = nn.Parameter( torch.zeros((2 * window_size - 1), num_heads) ) nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02) # Get relative position index coords = torch.arange(window_size) relative_coords = coords[:, None] - coords[None, :] # [window_size, window_size] relative_coords += window_size - 1 # Shift to start from 0 self.register_buffer("relative_position_index", relative_coords) def get_relative_position_bias(self, window_size: int) -> torch.Tensor: """Generate relative position bias for attention""" if not self.use_relative_position_bias: return None relative_position_bias = self.relative_position_bias_table[ self.relative_position_index[:window_size, :window_size].reshape(-1) ].reshape(window_size, window_size, -1) # Permute to [num_heads, window_size, window_size] relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() return relative_position_bias def forward( self, query: torch.Tensor, # [B, T_q, L_q, D] or [B, L_q, D] key: torch.Tensor, # [B, T_k, L_k, D] or [B, L_k, D] value: torch.Tensor, # [B, T_v, L_v, D] or [B, L_v, D] attention_mask: Optional[torch.Tensor] = None, ) -> torch.Tensor: """ Perform windowed cross attention. Args: query: Query tensor key: Key tensor value: Value tensor attention_mask: Optional attention mask Returns: Output tensor with same shape as query """ # Handle both temporal and non-temporal inputs is_temporal = query.ndim == 4 if is_temporal: B, T_q, L_q, D = query.shape _, T_k, L_k, _ = key.shape # Flatten temporal and spatial dims for cross attention query_flat = query.reshape(B, T_q * L_q, D) key_flat = key.reshape(B, T_k * L_k, D) value_flat = value.reshape(B, T_k * L_k, D) else: B, L_q, D = query.shape _, L_k, _ = key.shape query_flat = query key_flat = key value_flat = value # Project to Q, K, V q = self.q_proj(query_flat) # [B, N_q, D] k = self.k_proj(key_flat) # [B, N_k, D] v = self.v_proj(value_flat) # [B, N_v, D] # Reshape for multi-head attention q = q.reshape(B, -1, self.num_heads, self.head_dim).transpose(1, 2) # [B, H, N_q, head_dim] k = k.reshape(B, -1, self.num_heads, self.head_dim).transpose(1, 2) # [B, H, N_k, head_dim] v = v.reshape(B, -1, self.num_heads, self.head_dim).transpose(1, 2) # [B, H, N_v, head_dim] # Apply QK normalization q = self.q_norm(q) k = self.k_norm(k) # Scaled dot-product attention attn = (q @ k.transpose(-2, -1)) * self.scale # [B, H, N_q, N_k] # Add relative position bias if temporal if is_temporal and self.use_relative_position_bias: # Apply per-window bias rel_bias = self.get_relative_position_bias(min(T_q, self.window_size)) if rel_bias is not None: # Broadcast bias across spatial dimensions attn = attn + rel_bias.unsqueeze(0).unsqueeze(2) # Apply attention mask if attention_mask is not None: attn = attn.masked_fill(attention_mask.unsqueeze(1).unsqueeze(2) == 0, float('-inf')) # Softmax and dropout attn = F.softmax(attn, dim=-1) attn = self.attn_drop(attn) # Apply attention to values out = (attn @ v).transpose(1, 2).reshape(B, -1, D) # [B, N_q, D] # Output projection out = self.proj(out) out = self.proj_drop(out) # Reshape back to original shape if is_temporal: out = out.reshape(B, T_q, L_q, D) else: out = out.reshape(B, L_q, D) return out
class MultiModalFusionLayer(nn.Module): """ Fuses multiple modalities (audio, video, image) with learnable fusion weights. """ def __init__( self, dim: int, num_modalities: int = 3, fusion_type: str = "weighted", # "weighted", "gated", "adaptive" ): super().__init__() self.dim = dim self.num_modalities = num_modalities self.fusion_type = fusion_type if fusion_type == "weighted": # Learnable fusion weights self.fusion_weights = nn.Parameter(torch.ones(num_modalities) / num_modalities) elif fusion_type == "gated": # Gated fusion with cross-modal interactions self.gate_proj = nn.Sequential( nn.Linear(dim * num_modalities, dim * 2), nn.GELU(), nn.Linear(dim * 2, num_modalities), nn.Softmax(dim=-1) ) elif fusion_type == "adaptive": # Adaptive fusion with per-token gating self.adaptive_gate = nn.Sequential( nn.Linear(dim, dim // 2), nn.GELU(), nn.Linear(dim // 2, num_modalities), nn.Sigmoid() ) def forward(self, modality_features: List[torch.Tensor]) -> torch.Tensor: """ Fuse multiple modality features. Args: modality_features: List of [B, L, D] tensors for each modality Returns: fused: Fused features [B, L, D] """ if self.fusion_type == "weighted": # Simple weighted sum weights = F.softmax(self.fusion_weights, dim=0) fused = sum(w * feat for w, feat in zip(weights, modality_features)) elif self.fusion_type == "gated": # Concatenate and compute gates concat_features = torch.cat(modality_features, dim=-1) # [B, L, D * num_modalities] gates = self.gate_proj(concat_features) # [B, L, num_modalities] # Apply gates stacked = torch.stack(modality_features, dim=-1) # [B, L, D, num_modalities] fused = (stacked * gates.unsqueeze(2)).sum(dim=-1) # [B, L, D] elif self.fusion_type == "adaptive": # Adaptive per-token fusion fused_list = [] for feat in modality_features: gate = self.adaptive_gate(feat) # [B, L, num_modalities] fused_list.append(feat.unsqueeze(-1) * gate.unsqueeze(2)) fused = torch.cat(fused_list, dim=-1).sum(dim=-1) # [B, L, D] return fused
class FancyMultiModalWindowAttentionBlock(nn.Module): """ 🎯 Fancy Multi-Modal Window Attention Block A state-of-the-art block that processes audio, video, and image embeddings with temporal window-based cross-attention for efficient multi-modal fusion. Features: - ✨ Temporal windowing for audio and video (frame-by-frame processing) - 🪟 Shifted window attention for better temporal coherence (Swin-style) - 🔄 Cross-modal attention between all modality pairs - 🎭 Adaptive multi-modal fusion with learnable gates - 🚀 Efficient computation with window partitioning - 💎 QK normalization for training stability Architecture: 1. Temporal Partitioning (audio/video frames → windows) 2. Intra-Modal Self-Attention (within each modality) 3. Inter-Modal Cross-Attention (audio ↔ video ↔ image) 4. Multi-Modal Fusion (adaptive weighted combination) 5. Feed-Forward Network (SwiGLU activation) 6. Window Merging (reconstruct temporal sequences) """ def __init__( self, dim: int = 1024, num_heads: int = 16, window_size: int = 8, shift_size: int = 4, mlp_ratio: float = 4.0, qkv_bias: bool = True, drop: float = 0.0, attn_drop: float = 0.0, drop_path: float = 0.1, use_relative_position_bias: bool = True, fusion_type: str = "adaptive", # "weighted", "gated", "adaptive" use_shifted_window: bool = True, ): super().__init__() self.dim = dim self.num_heads = num_heads self.window_size = window_size self.shift_size = shift_size if use_shifted_window else 0 self.mlp_ratio = mlp_ratio # =============== Temporal Window Partitioning =============== self.window_partition = TemporalWindowPartition( window_size=window_size, shift_size=self.shift_size, ) # =============== Intra-Modal Self-Attention =============== self.norm_audio_self = OmniRMSNorm(dim) self.norm_video_self = OmniRMSNorm(dim) self.norm_image_self = OmniRMSNorm(dim) self.audio_self_attn = WindowCrossAttention( dim=dim, num_heads=num_heads, window_size=window_size, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop, use_relative_position_bias=use_relative_position_bias, ) self.video_self_attn = WindowCrossAttention( dim=dim, num_heads=num_heads, window_size=window_size, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop, use_relative_position_bias=use_relative_position_bias, ) self.image_self_attn = WindowCrossAttention( dim=dim, num_heads=num_heads, window_size=window_size, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop, use_relative_position_bias=False, # No temporal bias for static images ) # =============== Inter-Modal Cross-Attention =============== # Audio → Video/Image self.norm_audio_cross = OmniRMSNorm(dim) self.audio_to_visual = WindowCrossAttention( dim=dim, num_heads=num_heads, window_size=window_size, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop, ) # Video → Audio/Image self.norm_video_cross = OmniRMSNorm(dim) self.video_to_others = WindowCrossAttention( dim=dim, num_heads=num_heads, window_size=window_size, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop, ) # Image → Audio/Video self.norm_image_cross = OmniRMSNorm(dim) self.image_to_temporal = WindowCrossAttention( dim=dim, num_heads=num_heads, window_size=window_size, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop, ) # =============== Multi-Modal Fusion =============== self.multimodal_fusion = MultiModalFusionLayer( dim=dim, num_modalities=3, fusion_type=fusion_type, ) # =============== Feed-Forward Network =============== self.norm_ffn = OmniRMSNorm(dim) mlp_hidden_dim = int(dim * mlp_ratio) self.ffn = nn.Sequential( nn.Linear(dim, mlp_hidden_dim, bias=False), nn.GELU(), nn.Dropout(drop), nn.Linear(mlp_hidden_dim, dim, bias=False), nn.Dropout(drop), ) # =============== Stochastic Depth (Drop Path) =============== self.drop_path = nn.Identity() if drop_path <= 0. else nn.Dropout(drop_path) # =============== Output Projections =============== self.output_projection = nn.ModuleDict({ 'audio': nn.Linear(dim, dim), 'video': nn.Linear(dim, dim), 'image': nn.Linear(dim, dim), }) def forward( self, audio_embeds: Optional[torch.Tensor] = None, # [B, T_audio, L_audio, D] video_embeds: Optional[torch.Tensor] = None, # [B, T_video, L_video, D] image_embeds: Optional[torch.Tensor] = None, # [B, L_image, D] attention_mask: Optional[torch.Tensor] = None, return_intermediates: bool = False, ) -> Dict[str, torch.Tensor]: """ Forward pass of the Fancy Multi-Modal Window Attention Block. Args: audio_embeds: Audio embeddings [B, T_audio, L_audio, D] T_audio: number of audio frames L_audio: sequence length per frame video_embeds: Video embeddings [B, T_video, L_video, D] T_video: number of video frames L_video: sequence length per frame (e.g., patches) image_embeds: Image embeddings [B, L_image, D] L_image: sequence length (e.g., image patches) attention_mask: Optional attention mask return_intermediates: Whether to return intermediate features Returns: outputs: Dictionary containing processed embeddings for each modality - 'audio': [B, T_audio, L_audio, D] - 'video': [B, T_video, L_video, D] - 'image': [B, L_image, D] - 'fused': [B, L_total, D] (optional) """ intermediates = {} if return_intermediates else None # ========== Stage 1: Temporal Window Partitioning ========== partitioned_audio, audio_info = None, None partitioned_video, video_info = None, None if audio_embeds is not None: partitioned_audio, audio_info = self.window_partition.partition(audio_embeds) if return_intermediates: intermediates['audio_windows'] = partitioned_audio if video_embeds is not None: partitioned_video, video_info = self.window_partition.partition(video_embeds) if return_intermediates: intermediates['video_windows'] = partitioned_video # ========== Stage 2: Intra-Modal Self-Attention ========== audio_self_out, video_self_out, image_self_out = None, None, None if audio_embeds is not None: audio_normed = self.norm_audio_self(partitioned_audio) audio_self_out = self.audio_self_attn(audio_normed, audio_normed, audio_normed) audio_self_out = partitioned_audio + self.drop_path(audio_self_out) if video_embeds is not None: video_normed = self.norm_video_self(partitioned_video) video_self_out = self.video_self_attn(video_normed, video_normed, video_normed) video_self_out = partitioned_video + self.drop_path(video_self_out) if image_embeds is not None: image_normed = self.norm_image_self(image_embeds) image_self_out = self.image_self_attn(image_normed, image_normed, image_normed) image_self_out = image_embeds + self.drop_path(image_self_out) # ========== Stage 3: Inter-Modal Cross-Attention ========== audio_cross_out, video_cross_out, image_cross_out = None, None, None # Prepare context (merge windows temporarily for cross-attention) if audio_self_out is not None: audio_merged = self.window_partition.merge(audio_self_out, audio_info) if video_self_out is not None: video_merged = self.window_partition.merge(video_self_out, video_info) # Audio attends to Video and Image if audio_embeds is not None: audio_q = self.norm_audio_cross(audio_merged) # Create key-value context from other modalities kv_list = [] if video_embeds is not None: kv_list.append(video_merged) if image_embeds is not None: # Expand image to match temporal dimension B, L_img, D = image_self_out.shape T_audio = audio_merged.shape[1] image_expanded = image_self_out.unsqueeze(1).expand(B, T_audio, L_img, D) kv_list.append(image_expanded) if kv_list: # Concatenate along sequence dimension kv_context = torch.cat([kv.flatten(1, 2) for kv in kv_list], dim=1) kv_context = kv_context.reshape(B, -1, D) audio_cross_out = self.audio_to_visual( audio_q.flatten(1, 2), kv_context, kv_context, attention_mask ) audio_cross_out = audio_cross_out.reshape_as(audio_merged) audio_cross_out = audio_merged + self.drop_path(audio_cross_out) else: audio_cross_out = audio_merged # Video attends to Audio and Image if video_embeds is not None: video_q = self.norm_video_cross(video_merged) kv_list = [] if audio_embeds is not None: kv_list.append(audio_merged if audio_cross_out is None else audio_cross_out) if image_embeds is not None: B, L_img, D = image_self_out.shape T_video = video_merged.shape[1] image_expanded = image_self_out.unsqueeze(1).expand(B, T_video, L_img, D) kv_list.append(image_expanded) if kv_list: kv_context = torch.cat([kv.flatten(1, 2) for kv in kv_list], dim=1) kv_context = kv_context.reshape(B, -1, D) video_cross_out = self.video_to_others( video_q.flatten(1, 2), kv_context, kv_context, attention_mask ) video_cross_out = video_cross_out.reshape_as(video_merged) video_cross_out = video_merged + self.drop_path(video_cross_out) else: video_cross_out = video_merged # Image attends to Audio and Video if image_embeds is not None: image_q = self.norm_image_cross(image_self_out) kv_list = [] if audio_embeds is not None: # Average pool audio over time for image audio_pooled = (audio_merged if audio_cross_out is None else audio_cross_out).mean(dim=1) kv_list.append(audio_pooled) if video_embeds is not None: # Average pool video over time for image video_pooled = (video_merged if video_cross_out is None else video_cross_out).mean(dim=1) kv_list.append(video_pooled) if kv_list: kv_context = torch.cat(kv_list, dim=1) image_cross_out = self.image_to_temporal( image_q, kv_context, kv_context, attention_mask ) image_cross_out = image_self_out + self.drop_path(image_cross_out) else: image_cross_out = image_self_out # ========== Stage 4: Multi-Modal Fusion ========== # Collect features from all modalities for fusion fusion_features = [] if audio_cross_out is not None: audio_flat = audio_cross_out.flatten(1, 2) # [B, T*L, D] fusion_features.append(audio_flat) if video_cross_out is not None: video_flat = video_cross_out.flatten(1, 2) # [B, T*L, D] fusion_features.append(video_flat) if image_cross_out is not None: fusion_features.append(image_cross_out) # [B, L, D] # Pad/align sequence lengths for fusion if len(fusion_features) > 1: max_len = max(f.shape[1] for f in fusion_features) aligned_features = [] for feat in fusion_features: if feat.shape[1] < max_len: pad_len = max_len - feat.shape[1] feat = F.pad(feat, (0, 0, 0, pad_len)) aligned_features.append(feat) # Fuse modalities fused_features = self.multimodal_fusion(aligned_features) else: fused_features = fusion_features[0] if fusion_features else None # ========== Stage 5: Feed-Forward Network ========== if fused_features is not None: fused_normed = self.norm_ffn(fused_features) fused_ffn = self.ffn(fused_normed) fused_features = fused_features + self.drop_path(fused_ffn) # ========== Stage 6: Prepare Outputs ========== outputs = {} # Project back to original shapes if audio_embeds is not None and audio_cross_out is not None: # Partition again for consistency audio_final, _ = self.window_partition.partition(audio_cross_out) audio_final = self.output_projection['audio'](audio_final) audio_final = self.window_partition.merge(audio_final, audio_info) outputs['audio'] = audio_final if video_embeds is not None and video_cross_out is not None: video_final, _ = self.window_partition.partition(video_cross_out) video_final = self.output_projection['video'](video_final) video_final = self.window_partition.merge(video_final, video_info) outputs['video'] = video_final if image_embeds is not None and image_cross_out is not None: image_final = self.output_projection['image'](image_cross_out) outputs['image'] = image_final if fused_features is not None: outputs['fused'] = fused_features if return_intermediates: outputs['intermediates'] = intermediates return outputs
# -----------------------------------------------------------------------------# 7. Optimization Utilities (FP8, Compilation, Mixed Precision)# -----------------------------------------------------------------------------
@dataclassclass FP8Config: """Configuration for FP8 quantization""" enabled: bool = False margin: int = 0 fp8_format: str = "hybrid" # "e4m3", "e5m2", "hybrid" amax_history_len: int = 1024 amax_compute_algo: str = "max"
@dataclass class CompilationConfig: """Configuration for torch.compile""" enabled: bool = False mode: str = "reduce-overhead" # "default", "reduce-overhead", "max-autotune" fullgraph: bool = False dynamic: bool = True backend: str = "inductor"
@dataclassclass MixedPrecisionConfig: """Configuration for mixed precision training/inference""" enabled: bool = True dtype: str = "bfloat16" # "float16", "bfloat16" use_amp: bool = True
class ModelOptimizer: """ Unified model optimizer supporting FP8 quantization, torch.compile, and mixed precision inference. """ def __init__( self, fp8_config: Optional[FP8Config] = None, compilation_config: Optional[CompilationConfig] = None, mixed_precision_config: Optional[MixedPrecisionConfig] = None, ): self.fp8_config = fp8_config or FP8Config() self.compilation_config = compilation_config or CompilationConfig() self.mixed_precision_config = mixed_precision_config or MixedPrecisionConfig() # Setup mixed precision self._setup_mixed_precision() def _setup_mixed_precision(self): """Setup mixed precision context""" if self.mixed_precision_config.enabled: dtype_map = { "float16": torch.float16, "bfloat16": torch.bfloat16, } self.dtype = dtype_map.get(self.mixed_precision_config.dtype, torch.bfloat16) else: self.dtype = torch.float32 @contextmanager def autocast_context(self): """Context manager for automatic mixed precision""" if self.mixed_precision_config.enabled and self.mixed_precision_config.use_amp: with torch.autocast(device_type='cuda', dtype=self.dtype): yield else: yield def _compile_model(self, model: nn.Module) -> nn.Module: """Compile model using torch.compile""" if not self.compilation_config.enabled or not HAS_TORCH_COMPILE: return model return torch.compile( model, mode=self.compilation_config.mode, fullgraph=self.compilation_config.fullgraph, dynamic=self.compilation_config.dynamic, backend=self.compilation_config.backend, ) def _quantize_model_fp8(self, model: nn.Module) -> nn.Module: """Apply FP8 quantization using Transformer Engine""" if not self.fp8_config.enabled or not HAS_TRANSFORMER_ENGINE: return model # Convert compatible layers to FP8 for name, module in model.named_modules(): if isinstance(module, nn.Linear): # Replace with TE FP8 Linear fp8_linear = te.Linear( module.in_features, module.out_features, bias=module.bias is not None, ) # Copy weights fp8_linear.weight.data.copy_(module.weight.data) if module.bias is not None: fp8_linear.bias.data.copy_(module.bias.data) # Replace module parent_name = '.'.join(name.split('.')[:-1]) child_name = name.split('.')[-1] if parent_name: parent = dict(model.named_modules())[parent_name] setattr(parent, child_name, fp8_linear) return model def optimize_model( self, model: nn.Module, apply_compilation: bool = True, apply_quantization: bool = True, apply_mixed_precision: bool = True, ) -> nn.Module: """ Apply all optimizations to model. Args: model: Model to optimize apply_compilation: Whether to compile with torch.compile apply_quantization: Whether to apply FP8 quantization apply_mixed_precision: Whether to convert to mixed precision dtype Returns: Optimized model """ # Apply FP8 quantization first if apply_quantization and self.fp8_config.enabled: model = self._quantize_model_fp8(model) # Convert to mixed precision dtype if apply_mixed_precision and self.mixed_precision_config.enabled: model = model.to(dtype=self.dtype) # Compile model last if apply_compilation and self.compilation_config.enabled: model = self._compile_model(model) return model
@contextmanagerdef optimized_inference_mode( enable_cudnn_benchmark: bool = True, enable_tf32: bool = True, enable_flash_sdp: bool = True,): """ Context manager for optimized inference with various PyTorch optimizations. Args: enable_cudnn_benchmark: Enable cuDNN autotuner enable_tf32: Enable TF32 for faster matmul on Ampere+ GPUs enable_flash_sdp: Enable Flash Attention in scaled_dot_product_attention """ # Save original states orig_benchmark = torch.backends.cudnn.benchmark orig_tf32_matmul = torch.backends.cuda.matmul.allow_tf32 orig_tf32_cudnn = torch.backends.cudnn.allow_tf32 orig_sdp_flash = torch.backends.cuda.flash_sdp_enabled() try: # Enable optimizations torch.backends.cudnn.benchmark = enable_cudnn_benchmark torch.backends.cuda.matmul.allow_tf32 = enable_tf32 torch.backends.cudnn.allow_tf32 = enable_tf32 if enable_flash_sdp: torch.backends.cuda.enable_flash_sdp(True) yield finally: # Restore original states torch.backends.cudnn.benchmark = orig_benchmark torch.backends.cuda.matmul.allow_tf32 = orig_tf32_matmul torch.backends.cudnn.allow_tf32 = orig_tf32_cudnn torch.backends.cuda.enable_flash_sdp(orig_sdp_flash)12345678910gradio==5.42.0opencv-python>=4.8.0requests>=2.28.0func-timeout>=4.3.5numpy>=1.24.0boto3botocoreonnxruntimehuggingface_hub>=0.16.0Pillow>=9.0.0.gitattributes+4
.gitignoreAdded+5
README.md+4-3
__lib__/__init__.pyAdded
__lib__/app.pyAdded+1834
__lib__/i18n/__init__.pyAdded+36
__lib__/i18n/en.pycAdded
__lib__/nfsw.pycAdded
__lib__/util.pycAdded
app.pyAdded+60
datas/cat01.webpAdded

Large File Pointer Details
- SHA256: 1bf3d4cb894df32d7175b6ba091b21f7efe28178561ef68b8d0cb90f84adcb83
- Pointer size: 130 Bytes
- Size of remote file: 56.1 kB
datas/panda01.jpegAdded

Large File Pointer Details
- SHA256: ce5abe529cdd94a469fc1f86515e8f45a4d7b7594f9eadb318b8a597fd769a81
- Pointer size: 131 Bytes
- Size of remote file: 112 kB
datas/panda01m.jpegAdded

Large File Pointer Details
- SHA256: 659dfb517584cf3bc4ab3f5b444db325917a2f6badc97ec8f277d500e75c8d40
- Pointer size: 130 Bytes
- Size of remote file: 21.4 kB
labels.jsonAdded+4
pipeline.pyAdded+1934
requirements.txtAdded+10