Fix some bugs:

Traceback (most recent call last):
  File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\gradio\queueing.py", line 622, in process_events
    response = await route_utils.call_process_api(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\gradio\route_utils.py", line 323, in call_process_api
    output = await app.get_blocks().process_api(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\gradio\blocks.py", line 2016, in process_api
    result = await self.call_function(
             ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\gradio\blocks.py", line 1569, in call_function
    prediction = await anyio.to_thread.run_sync(  # type: ignore
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\anyio\to_thread.py", line 31, in run_sync
    return await get_asynclib().run_sync_in_worker_thread(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\anyio\_backends\_asyncio.py", line 937, in run_sync_in_worker_thread
    return await future
           ^^^^^^^^^^^^
  File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\anyio\_backends\_asyncio.py", line 867, in run
    result = context.run(func, *args)
             ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\gradio\utils.py", line 846, in wrapper
    response = f(*args, **kwargs)
               ^^^^^^^^^^^^^^^^^^
  File "C:\Users\hp\Downloads\image.py", line 232, in update_size
    return gr.Dropdown.update(visible=True)
           ^^^^^^^^^^^^^^^^^^
AttributeError: type object 'Dropdown' has no attribute 'update'

```
import gradio as gr
from g4f.client import Client
from g4f import Provider
from PIL import Image
import requests
from io import BytesIO
import os
import time
import logging
import json
from datetime import datetime
import threading
import queue
from typing import Dict, Any

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('image_generator.log'),
        logging.StreamHandler()
    ]
)

class ImageGenerator:
    """Image Generation Manager Class"""
    
    # Available providers and their configurations
    PROVIDER_CONFIG = {
        "Amigo": {
            "provider": Provider.AmigoChat,
            "models": ["flux-realism", "dalle-e-3"],
            "requires_auth": True,
            "supports_size": True,
            "sizes": ["1024x1024", "512x512"]
        },
        "Google": {
            "provider": Provider.Prodia,
            "models": ["aniverse_v30.safetensors [579e6f85]"],
            "requires_auth": False,
            "supports_size": False
        }
    }

    def __init__(self):
        self.client = Client()
        self.output_dir = "generated_images"
        self.history_file = "generation_history.json"
        self.generation_queue = queue.Queue()
        self.load_history()
        self.setup_output_directory()
        self.start_queue_processor()

    def setup_output_directory(self):
        os.makedirs(self.output_dir, exist_ok=True)

    def load_history(self):
        try:
            if os.path.exists(self.history_file):
                with open(self.history_file, 'r') as f:
                    self.history = json.load(f)
            else:
                self.history = []
        except Exception as e:
            logging.error(f"Error loading history: {e}")
            self.history = []

    def save_history(self):
        try:
            with open(self.history_file, 'w') as f:
                json.dump(self.history, f, indent=4)
        except Exception as e:
            logging.error(f"Error saving history: {e}")

    def get_available_models(self, provider_name: str) -> list:
        """Get available models for a specific provider"""
        return self.PROVIDER_CONFIG.get(provider_name, {}).get("models", [])

    def generate_image(self, prompt: str, provider_name: str, model_name: str, 
                      size: str = "1024x1024", batch_size: int = 1) -> Dict[str, Any]:
        """Queue an image generation task"""
        task_id = f"task_{int(time.time())}_{len(self.history)}"
        task = {
            "task_id": task_id,
            "prompt": prompt,
            "provider_name": provider_name,
            "model_name": model_name,
            "size": size,
            "batch_size": batch_size
        }
        self.generation_queue.put(task)
        return {"status": "queued", "task_id": task_id}

    def _generate_image_internal(self, **kwargs):
        """Internal image generation method"""
        try:
            provider_config = self.PROVIDER_CONFIG[kwargs['provider_name']]
            provider = provider_config['provider']
            images = []

            for _ in range(kwargs['batch_size']):
                # Prepare generation parameters
                gen_params = {
                    "model": kwargs['model_name'],
                    "prompt": kwargs['prompt'],
                    "provider": provider
                }

                # Add size parameter if supported
                if provider_config['supports_size']:
                    gen_params["size"] = kwargs['size']

                # Generate image
                try:
                    response = self.client.images.generate(**gen_params)
                    
                    # Handle different response types
                    if hasattr(response, 'data'):
                        image_url = response.data[0].url
                    else:
                        image_url = response  # Some providers might return URL directly

                    # Download and save image
                    img_response = requests.get(image_url)
                    img = Image.open(BytesIO(img_response.content))

                    # Save image
                    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                    filename = f"{timestamp}_{len(self.history)}.png"
                    full_path = os.path.join(self.output_dir, filename)
                    img.save(full_path)
                    images.append(full_path)

                    # Update history
                    entry = {
                        "timestamp": timestamp,
                        "prompt": kwargs['prompt'],
                        "provider": kwargs['provider_name'],
                        "model": kwargs['model_name'],
                        "filename": filename,
                        "parameters": kwargs
                    }
                    self.history.append(entry)
                    self.save_history()

                except Exception as e:
                    logging.error(f"Error with provider {kwargs['provider_name']}: {e}")
                    continue

            return images

        except Exception as e:
            logging.error(f"Error generating image: {e}")
            raise

    def process_queue(self):
        while True:
            try:
                task = self.generation_queue.get()
                if task is None:
                    break
                self._generate_image_internal(**task)
                self.generation_queue.task_done()
            except Exception as e:
                logging.error(f"Error processing queue: {e}")

    def start_queue_processor(self):
        self.queue_thread = threading.Thread(target=self.process_queue, daemon=True)
        self.queue_thread.start()

class ImageGeneratorUI:
    def __init__(self):
        self.generator = ImageGenerator()

    def create_interface(self):
        with gr.Blocks(theme=gr.themes.Soft()) as demo:
            gr.Markdown("# Advanced Image Generation App")
            
            with gr.Tabs():
                with gr.TabItem("Generate"):
                    with gr.Row():
                        with gr.Column():
                            prompt = gr.Textbox(
                                label="Prompt",
                                placeholder="Enter your image description...",
                                lines=3
                            )
                            
                            provider = gr.Dropdown(
                                choices=list(ImageGenerator.PROVIDER_CONFIG.keys()),
                                label="Provider",
                                value=list(ImageGenerator.PROVIDER_CONFIG.keys())[0]
                            )
                            
                            model = gr.Dropdown(
                                choices=[],
                                label="Model"
                            )
                            
                            size = gr.Dropdown(
                                choices=["1024x1024", "512x512"],
                                label="Image Size",
                                visible=False
                            )
                            
                            batch_size = gr.Slider(
                                minimum=1,
                                maximum=4,
                                value=1,
                                step=1,
                                label="Batch Size"
                            )
                            
                            generate_btn = gr.Button("Generate Image", variant="primary")
                            
                        with gr.Column():
                            output = gr.Gallery(label="Generated Images")
                            status = gr.Textbox(label="Status")
                
                with gr.TabItem("History"):
                    history_gallery = gr.Gallery(label="Generation History")
                    refresh_btn = gr.Button("Refresh History")

            def update_models(provider_name: str):
                models = self.generator.get_available_models(provider_name)
                return gr.Dropdown.update(choices=models, value=models[0])

            def update_size(provider_name: str):
                provider_config = ImageGenerator.PROVIDER_CONFIG[provider_name]
                if provider_config['supports_size']:
                    return gr.Dropdown.update(visible=True)
                else:
                    return gr.Dropdown.update(visible=False)

            provider.change(update_models, inputs=[provider], outputs=[model])
            provider.change(update_size, inputs=[provider], outputs=[size])

            def generate(*args):
                try:
                    result = self.generator.generate_image(*args)
                    return {
                        output: None,
                        status: f"Task queued: {result['task_id']}"
                    }
                except Exception as e:
                    return {
                        output: None,
                        status: f"Error: {str(e)}"
                    }

            def refresh_history():
                try:
                    history = self.generator.history
                    images = [os.path.join(self.generator.output_dir, entry['filename']) for entry in history]
                    return {
                        history_gallery: images,
                        refresh_btn: "Refresh History"
                    }
                except Exception as e:
                    return {
                        history_gallery: None,
                        refresh_btn: f"Error: {str(e)}"
                    }

            generate_btn.click(
                fn=generate,
                inputs=[prompt, provider, model, size, batch_size],
                outputs=[output, status]
            )
            refresh_btn.click(
                fn=refresh_history,
                inputs=[],
                outputs=[history_gallery, refresh_btn]
            )

        return demo

if __name__ == "__main__":
    ui = ImageGeneratorUI()
    demo = ui.create_interface()
    demo.launch(share=True)