use HunyuanImage-2.1 for text to image
Browse files2832 unmodified lines283328342835283628372838283985 unmodified lines292529262927292829292930293197 unmodified lines3029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213 unmodified lines31253126312731283129313031313132518 unmodified lines365136523653365436553656365783 unmodified lines3741374237433744374537463747524 unmodified lines427242734274427542764277427842792953 unmodified lines72337234723572367237723872392832 unmodified lines"""try:# Create unique filename with timestamp and UUIDtimestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")unique_id = str(uuid.uuid4())[:8]base_name, ext = os.path.splitext(filename)unique_filename = f"{media_type}_{timestamp}_{unique_id}_{base_name}{ext}"85 unmodified lines# Continue anyway, repo might already exist# Create unique filename with timestamp and UUIDtimestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")unique_id = str(uuid.uuid4())[:8]base_name, ext = os.path.splitext(filename)unique_filename = f"{media_type}/{timestamp}_{unique_id}_{base_name}{ext}"97 unmodified linesexcept Exception as e:print(f"[TempCleanup] Error during cleanup: {str(e)}")def generate_image_with_gemini(prompt: str, image_index: int = 0, token: gr.OAuthToken | None = None) -> str:"""Generate image using Google Gemini 2.5 Flash Image Preview via OpenRouter.Uses google/gemini-2.5-flash-image-preview:free via OpenRouter chat completions API.Returns an HTML <img> tag whose src is an uploaded temporary URL."""try:print(f"[Text2Image] Starting generation with prompt: {prompt[:100]}...")# Check for OpenRouter API keyopenrouter_key = os.getenv('OPENROUTER_API_KEY')if not openrouter_key:print("[Text2Image] Missing OPENROUTER_API_KEY")return "Error: OPENROUTER_API_KEY environment variable is not set. Please set it to your OpenRouter API key."import requestsimport json as _jsonimport base64import io as _iofrom PIL import Image# Create the chat completion request for text-to-imageheaders = {"Authorization": f"Bearer {openrouter_key}","Content-Type": "application/json"}data = {"model": "google/gemini-2.5-flash-image-preview:free","messages": [{"role": "user","content": f"Generate an image based on this description: {prompt}"}],"temperature": 0.7,"max_tokens": 1000}try:print("[Text2Image] Making API request to OpenRouter...")response = requests.post("https://openrouter.ai/api/v1/chat/completions",headers=headers,json=data,timeout=60)response.raise_for_status()result_data = response.json()print(f"[Text2Image] Received API response: {_json.dumps(result_data, indent=2)}")# Extract the generated image from the response (using same pattern as image-to-image)message = result_data.get('choices', [{}])[0].get('message', {})if message and 'images' in message and message['images']:# Get the first image from the 'images' listimage_data = message['images'][0]base64_string = image_data.get('image_url', {}).get('url', '')if base64_string and ',' in base64_string:# Remove the "data:image/png;base64," prefixbase64_content = base64_string.split(',')[1]# Decode the base64 string and create a PIL imageimg_bytes = base64.b64decode(base64_content)generated_image = Image.open(_io.BytesIO(img_bytes))# Convert PIL image to JPEG bytes for uploadout_buf = _io.BytesIO()generated_image.convert('RGB').save(out_buf, format='JPEG', quality=90, optimize=True)image_bytes = out_buf.getvalue()else:raise RuntimeError(f"API returned an invalid image format. Response: {_json.dumps(result_data, indent=2)}")else:raise RuntimeError(f"API did not return an image. Full Response: {_json.dumps(result_data, indent=2)}")except requests.exceptions.HTTPError as err:error_body = err.response.textif err.response.status_code == 401:return "Error: Authentication failed. Check your OpenRouter API key."elif err.response.status_code == 429:return "Error: Rate limit exceeded or insufficient credits. Check your OpenRouter account."else:return f"Error: An API error occurred: {error_body}"except Exception as e:return f"Error: An unexpected error occurred: {str(e)}"# Upload and return HTML tagprint("[Text2Image] Uploading image to HF...")filename = f"generated_image_{image_index}.jpg"3 unmodified linesreturn temp_urlprint(f"[Text2Image] Successfully generated image: {temp_url}")return f"<img src=\"{temp_url}\" alt=\"{prompt}\" style=\"max-width: 100%; height: auto; border-radius: 8px; margin: 10px 0;\" loading=\"lazy\" />"except Exception as e:print(f"Text-to-image generation error: {str(e)}")return f"Error generating image (text-to-image): {str(e)}"def generate_image_with_qwen(prompt: str, image_index: int = 0, token: gr.OAuthToken | None = None) -> str:518 unmodified lines# Generate images for each promptgenerated_images = []for i, prompt in enumerate(image_prompts):image_html = generate_image_with_gemini(prompt, i, token=None) # TODO: Pass token from parent contextif not image_html.startswith("Error"):generated_images.append((i, image_html))83 unmodified linesplaceholder_images = re.findall(img_pattern, html_content)# Generate a single imageimage_html = generate_image_with_gemini(prompt, 0, token=None) # TODO: Pass token from parent contextif image_html.startswith("Error"):return ""524 unmodified linesprint(f"[MediaApply] Running text-to-image with prompt len={len(t2i_prompt)}")# Single-image flow for text-to-image (LLM placement first, fallback deterministic)try:print(f"[MediaApply] Calling generate_image_with_gemini with prompt: {t2i_prompt[:50]}...")image_html_tag = generate_image_with_gemini(t2i_prompt, 0, token=token)print(f"[MediaApply] Image generation result: {image_html_tag[:200]}...")if not (image_html_tag or "").startswith("Error"):print("[MediaApply] Attempting LLM placement of image...")2953 unmodified lineslabel="🎨 Generate Images (text → image)",value=False,visible=True,info="Include generated images in your outputs using Nano Banana")text_to_image_prompt = gr.Textbox(label="Text-to-Image Prompt",2832 unmodified lines283328342835283628372838283985 unmodified lines292529262927292829292930293197 unmodified lines3029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823 unmodified lines308630873088308930903091309230933094518 unmodified lines361336143615361636173618361983 unmodified lines3703370437053706370737083709524 unmodified lines423442354236423742384239424042412953 unmodified lines71957196719771987199720072012832 unmodified lines"""try:# Create unique filename with timestamp and UUIDtimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")unique_id = str(uuid.uuid4())[:8]base_name, ext = os.path.splitext(filename)unique_filename = f"{media_type}_{timestamp}_{unique_id}_{base_name}{ext}"85 unmodified lines# Continue anyway, repo might already exist# Create unique filename with timestamp and UUIDtimestamp = datetime.now().strftime("%Y%m%d_%H%M%S")unique_id = str(uuid.uuid4())[:8]base_name, ext = os.path.splitext(filename)unique_filename = f"{media_type}/{timestamp}_{unique_id}_{base_name}{ext}"97 unmodified linesexcept Exception as e:print(f"[TempCleanup] Error during cleanup: {str(e)}")def generate_image_with_hunyuan(prompt: str, image_index: int = 0, token: gr.OAuthToken | None = None) -> str:"""Generate image using Tencent HunyuanImage-2.1 via Hugging Face InferenceClient.Uses tencent/HunyuanImage-2.1 via HuggingFace InferenceClient with fal-ai provider.Returns an HTML <img> tag whose src is an uploaded temporary URL."""try:print(f"[Text2Image] Starting HunyuanImage generation with prompt: {prompt[:100]}...")# Check for HF_TOKENhf_token = os.getenv('HF_TOKEN')if not hf_token:print("[Text2Image] Missing HF_TOKEN")return "Error: HF_TOKEN environment variable is not set. Please set it to your Hugging Face API token."from huggingface_hub import InferenceClientfrom PIL import Imageimport io as _io# Create InferenceClient with fal-ai providerclient = InferenceClient(provider="fal-ai",api_key=hf_token,bill_to="huggingface",)print("[Text2Image] Making API request to HuggingFace InferenceClient...")# Generate image using HunyuanImage-2.1 modelimage = client.text_to_image(prompt,model="tencent/HunyuanImage-2.1",)print(f"[Text2Image] Successfully generated image with size: {image.size}")# Resize image to reduce size while maintaining qualitymax_size = 1024if image.width > max_size or image.height > max_size:image.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)# Convert PIL Image to bytes for uploadbuffer = _io.BytesIO()# Save as JPEG with good qualityimage.convert('RGB').save(buffer, format='JPEG', quality=90, optimize=True)image_bytes = buffer.getvalue()# Upload and return HTML tagprint("[Text2Image] Uploading image to HF...")filename = f"generated_image_{image_index}.jpg"3 unmodified linesreturn temp_urlprint(f"[Text2Image] Successfully generated image: {temp_url}")return f"<img src=\"{temp_url}\" alt=\"{prompt}\" style=\"max-width: 100%; height: auto; border-radius: 8px; margin: 10px 0;\" loading=\"lazy\" />"except Exception as e:print(f"[Text2Image] Error generating image with HunyuanImage: {str(e)}")return f"Error generating image (text-to-image): {str(e)}"def generate_image_with_qwen(prompt: str, image_index: int = 0, token: gr.OAuthToken | None = None) -> str:518 unmodified lines# Generate images for each promptgenerated_images = []for i, prompt in enumerate(image_prompts):image_html = generate_image_with_hunyuan(prompt, i, token=None) # TODO: Pass token from parent contextif not image_html.startswith("Error"):generated_images.append((i, image_html))83 unmodified linesplaceholder_images = re.findall(img_pattern, html_content)# Generate a single imageimage_html = generate_image_with_hunyuan(prompt, 0, token=None) # TODO: Pass token from parent contextif image_html.startswith("Error"):return ""524 unmodified linesprint(f"[MediaApply] Running text-to-image with prompt len={len(t2i_prompt)}")# Single-image flow for text-to-image (LLM placement first, fallback deterministic)try:print(f"[MediaApply] Calling generate_image_with_hunyuan with prompt: {t2i_prompt[:50]}...")image_html_tag = generate_image_with_hunyuan(t2i_prompt, 0, token=token)print(f"[MediaApply] Image generation result: {image_html_tag[:200]}...")if not (image_html_tag or "").startswith("Error"):print("[MediaApply] Attempting LLM placement of image...")2953 unmodified lineslabel="🎨 Generate Images (text → image)",value=False,visible=True,info="Include generated images in your outputs using HunyuanImage-2.1")text_to_image_prompt = gr.Textbox(label="Text-to-Image Prompt",
app.py+47-85