Whitepaper
Docs
Sign In
Tool
Tool
v1.0
Huggingface Image Generation
Tool ID
huggingface_image_generation
Creator
@blygf
Downloads
292+
Generates images. Look at description below.
Get
README
No README available
Tool Code
Show
""" title: Hugging Face Image Generation author: HugiSoft author_url: https://hugisoft.com funding_url: https://github.com/sponsors/hugisoft version: 1.0 required_open_webui_version: 0.3.9 description: | The Hugging Face Image Generation tool is a powerful integration that leverages the Hugging Face API to generate high-quality images from text prompts. It uses the Stable Diffusion 3.5 Large Turbo model to create visually stunning images based on user input. The tool is designed to enhance user prompts with detailed and creative descriptions, ensuring the generated images are both accurate and visually appealing. Key Features: - **Text-to-Image Generation**: Converts text prompts into high-resolution images using Hugging Face's Stable Diffusion model. - **Prompt Enhancement**: Automatically enhances user prompts with detailed and creative descriptions for better image results. - **Multiple Formats**: Supports various image formats, including default, square, landscape, and portrait. - **Secure Image Storage**: Saves generated images to a specified directory and provides a URL for easy access. - **Error Handling**: Includes robust error handling for API failures, timeouts, and other issues. License: MIT """ import requests import os from typing import Dict, Any from pydantic import BaseModel, Field from datetime import datetime class HFException(Exception): """Base exception for HuggingFace API related errors.""" pass class Tools: class Valves(BaseModel): HF_API_KEY: str = Field( default=None, description="HuggingFace API key for accessing the serverless endpoints", ) HF_API_URL: str = Field( default="https://api-inference.huggingface.co/models/stabilityai/stable-diffusion-3.5-large-turbo", description="HuggingFace API URL for accessing the serverless endpoint of a Text-to-Image Model.", ) IMAGE_SAVE_DIR: str = Field( default="/var/www/html/generated_images", description="Directory to save generated images.", ) IMAGE_BASE_URL: str = Field( default="https://hugisoft.com/generated_images", description="Base URL for accessing generated images.", ) def __init__(self): self.valves = self.Valves() # Ensure the image save directory exists os.makedirs(self.valves.IMAGE_SAVE_DIR, exist_ok=True) async def create_image( self, prompt: str, image_format: str = "default", __user__: dict = {}, __event_emitter__=None, ) -> str: """ Creates visually stunning images with text prompts using text-to-image models, based on a prompt. If the user prompt is too general or lacking, embellish it to generate a better illustration. :param prompt: The prompt to generate the image. :param image_format: Format of the image (default, landscape, portrait). """ if not self.valves.HF_API_KEY: return "HuggingFace API key is not set in the Valves." try: formats = { "default": (1024, 1024), "square": (1024, 1024), "landscape": (1024, 768), "landscape_large": (1440, 1024), "portrait": (768, 1024), "portrait_large": (1024, 1440), } if image_format not in formats: raise ValueError( f"Invalid format. Must be one of: {', '.join(formats.keys())}" ) width, height = formats[image_format] headers = {"Authorization": f"Bearer {self.valves.HF_API_KEY}"} payload = { "inputs": prompt, "parameters": {"width": width, "height": height}, } response = requests.post( self.valves.HF_API_URL, headers=headers, json=payload, timeout=(10, 600), ) if response.status_code != 200: raise HFException( f"API request failed with status code {response.status_code}: {response.text}" ) # Save the image to a file timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") image_filename = f"generated_image_{timestamp}.png" image_path = os.path.join(self.valves.IMAGE_SAVE_DIR, image_filename) with open(image_path, "wb") as f: f.write(response.content) # Generate the full image URL image_url = f"{self.valves.IMAGE_BASE_URL}/{image_filename}" # Return the fully formatted image for displaying return f"" except Exception as e: return f"An error occurred: {str(e)}"