import os import random import uuid import json import time import asyncio from threading import Thread import gradio as gr import spaces import torch import numpy as np from PIL import Image import edge_tts import cv2 from transformers import ( AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer, Qwen2VLForConditionalGeneration, AutoProcessor, ) from transformers.image_utils import load_image from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler MAX_MAX_NEW_TOKENS = 2048 DEFAULT_MAX_NEW_TOKENS = 1024 MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096")) device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") # Load text-only model and tokenizer model_id = "prithivMLmods/FastThink-0.5B-Tiny" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained( model_id, device_map="auto", torch_dtype=torch.bfloat16, ) model.eval() # Updated TTS voices list (all voices) TTS_VOICES = [ "af-ZA-AdriNeural", "af-ZA-WillemNeural", "am-ET-AmehaNeural", "am-ET-MekdesNeural", "ar-AE-FatimaNeural", "ar-AE-HamdanNeural", "ar-BH-LailaNeural", "ar-BH-MajedNeural", "ar-DZ-AminaNeural", "ar-DZ-IsmaelNeural", "ar-EG-SalmaNeural", "ar-EG-OmarNeural", "ar-IQ-LanaNeural", "ar-IQ-BassamNeural", "ar-JO-SanaNeural", "ar-JO-TaimNeural", "ar-KW-NouraNeural", "ar-KW-FahedNeural", "ar-LB-LaylaNeural", "ar-LB-RamiNeural", "ar-LY-ImanNeural", "ar-LY-OmarNeural", "ar-MA-MounaNeural", "ar-MA-JamalNeural", "ar-OM-AyshaNeural", "ar-OM-AbdullahNeural", "ar-QA-AmalNeural", "ar-QA-MoazNeural", "ar-SA-ZariyahNeural", "ar-SA-HamedNeural", "ar-SY-AmanyNeural", "ar-SY-LaithNeural", "ar-TN-ReemNeural", "ar-TN-SeifNeural", "ar-YE-MaryamNeural", "ar-YE-SalehNeural", "az-AZ-BabekNeural", "az-AZ-BanuNeural", "bg-BG-BorislavNeural", "bg-BG-KalinaNeural", "bn-BD-NabanitaNeural", "bn-BD-PradeepNeural", "bn-IN-TanishaNeural", "bn-IN-SwapanNeural", "bs-BA-GoranNeural", "bs-BA-VesnaNeural", "ca-ES-JoanaNeural", "ca-ES-AlbaNeural", "ca-ES-EnricNeural", "cs-CZ-AntoninNeural", "cs-CZ-VlastaNeural", "cy-GB-NiaNeural", "cy-GB-AledNeural", "da-DK-ChristelNeural", "da-DK-JeppeNeural", "de-AT-IngridNeural", "de-AT-JonasNeural", "de-CH-LeniNeural", "de-CH-JanNeural", "de-DE-KatjaNeural", "de-DE-ConradNeural", "el-GR-AthinaNeural", "el-GR-NestorasNeural", "en-AU-AnnetteNeural", "en-AU-MichaelNeural", "en-CA-ClaraNeural", "en-CA-LiamNeural", "en-GB-SoniaNeural", "en-GB-RyanNeural", "en-GH-EsiNeural", "en-GH-KwameNeural", "en-HK-YanNeural", "en-HK-TrevorNeural", "en-IE-EmilyNeural", "en-IE-ConnorNeural", "en-IN-NeerjaNeural", "en-IN-PrabhasNeural", "en-KE-ChantelleNeural", "en-KE-ChilembaNeural", "en-NG-EzinneNeural", "en-NG-AbechiNeural", "en-NZ-MollyNeural", "en-NZ-MitchellNeural", "en-PH-RosaNeural", "en-PH-JamesNeural", "en-SG-LunaNeural", "en-SG-WayneNeural", "en-TZ-ImaniNeural", "en-TZ-DaudiNeural", "en-US-JennyNeural", "en-US-GuyNeural", "en-ZA-LeahNeural", "en-ZA-LukeNeural", "es-AR-ElenaNeural", "es-AR-TomasNeural", "es-BO-SofiaNeural", "es-BO-MarceloNeural", "es-CL-CatalinaNeural", "es-CL-LorenzoNeural", "es-CO-SalomeNeural", "es-CO-GonzaloNeural", "es-CR-MariaNeural", "es-CR-JuanNeural", "es-CU-BelkysNeural", "es-CU-ManuelNeural", "es-DO-RamonaNeural", "es-DO-EmilioNeural", "es-EC-AndreaNeural", "es-EC-LuisNeural", "es-ES-ElviraNeural", "es-ES-AlvaroNeural", "es-GQ-TeresaNeural", "es-GQ-JavierNeural", "es-GT-MartaNeural", "es-GT-AndresNeural", "es-HN-KarlaNeural", "es-HN-CarlosNeural", "es-MX-DaliaNeural", "es-MX-JorgeNeural", "es-NI-YolandaNeural", "es-NI-FedericoNeural", "es-PA-MargaritaNeural", "es-PA-RobertoNeural", "es-PE-CamilaNeural", "es-PE-AlexNeural", "es-PR-KarinaNeural", "es-PR-VictorNeural", "es-PY-TaniaNeural", "es-PY-MarioNeural", "es-SV-LorenaNeural", "es-SV-RodrigoNeural", "es-US-SaraNeural", "es-US-AlonsoNeural", "es-UY-ValentinaNeural", "es-UY-MateoNeural", "es-VE-PaolaNeural", "es-VE-SebastianNeural", "et-EE-AnuNeural", "et-EE-KertNeural", "eu-ES-AinhoaNeural", "eu-ES-AnderNeural", "fa-IR-DilaraNeural", "fa-IR-FaridNeural", "fi-FI-NooraNeural", "fi-FI-HarriNeural", "fil-PH-BlessicaNeural", "fil-PH-AngeloNeural", "fr-BE-CharlineNeural", "fr-BE-GerardNeural", "fr-CA-SylvieNeural", "fr-CA-AntoineNeural", "fr-CH-ArianeNeural", "fr-CH-GuillaumeNeural", "fr-FR-DeniseNeural", "fr-FR-HenriNeural", "ga-IE-OrlaNeural", "ga-IE-ColmNeural", "gl-ES-SoniaNeural", "gl-ES-XiaoqiangNeural", "gu-IN-DhwaniNeural", "gu-IN-NiranjanNeural", "ha-NG-AishaNeural", "ha-NG-YusufNeural", "he-IL-HilaNeural", "he-IL-AvriNeural", "hi-IN-SwaraNeural", "hi-IN-MadhurNeural", "hr-HR-GabrijelaNeural", "hr-HR-SreckoNeural", "hu-HU-NoemiNeural", "hu-HU-TamasNeural", "hy-AM-AnushNeural", "hy-AM-HaykNeural", "id-ID-ArdiNeural", "id-ID-GadisNeural", "ig-NG-AdaNeural", "ig-NG-EzeNeural", "is-IS-GudrunNeural", "is-IS-GunnarNeural", "it-IT-ElsaNeural", "it-IT-DiegoNeural", "ja-JP-NanamiNeural", "ja-JP-KeitaNeural", "jv-ID-DianNeural", "jv-ID-GustiNeural", "ka-GE-EkaNeural", # ... (truncated for brevity; include all voices as needed) ] MODEL_ID = "Qwen/Qwen2.5-VL-3B-Instruct" processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True) model_m = Qwen2_5_VLForConditionalGeneration.from_pretrained( MODEL_ID, trust_remote_code=True, torch_dtype=torch.float16 ).to("cuda").eval() async def text_to_speech(text: str, voice: str, output_file="output.mp3"): """Convert text to speech using Edge TTS and save as MP3""" communicate = edge_tts.Communicate(text, voice) await communicate.save(output_file) return output_file def clean_chat_history(chat_history): """ Filter out any chat entries whose "content" is not a string. This helps prevent errors when concatenating previous messages. """ cleaned = [] for msg in chat_history: if isinstance(msg, dict) and isinstance(msg.get("content"), str): cleaned.append(msg) return cleaned # Environment variables and parameters for Stable Diffusion XL (left in case needed in the future) MODEL_ID_SD = os.getenv("MODEL_VAL_PATH") # SDXL Model repository path via env variable MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096")) USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1" ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1" BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1")) # For batched image generation # Load the SDXL pipeline (not used in the current configuration) sd_pipe = StableDiffusionXLPipeline.from_pretrained( MODEL_ID_SD, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, use_safetensors=True, add_watermarker=False, ).to(device) sd_pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(sd_pipe.scheduler.config) if torch.cuda.is_available(): sd_pipe.text_encoder = sd_pipe.text_encoder.half() if USE_TORCH_COMPILE: sd_pipe.compile() if ENABLE_CPU_OFFLOAD: sd_pipe.enable_model_cpu_offload() MAX_SEED = np.iinfo(np.int32).max def save_image(img: Image.Image) -> str: """Save a PIL image with a unique filename and return the path.""" unique_name = str(uuid.uuid4()) + ".png" img.save(unique_name) return unique_name def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: if randomize_seed: seed = random.randint(0, MAX_SEED) return seed def progress_bar_html(label: str) -> str: """ Returns an HTML snippet for a thin progress bar with a label. The progress bar is styled as a dark red animated bar. """ return f'''