kevalfst commited on
Commit
7ea27ba
·
verified ·
1 Parent(s): c4ccad7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -72
app.py CHANGED
@@ -1,88 +1,113 @@
1
  import gradio as gr
2
- import numpy as np
3
- import random
4
  import torch
 
5
  from diffusers import DiffusionPipeline
 
6
 
7
- # Define available models and their corresponding Hugging Face repositories
8
- MODEL_REPOS = {
9
- "Stable Diffusion XL Base 1.0": "stabilityai/stable-diffusion-xl-base-1.0",
10
- "SDXL-Turbo": "stabilityai/sdxl-turbo",
11
- "Playground v2 1024px Aesthetic": "playgroundai/playground-v2-1024px-aesthetic",
12
- "Segmind Vega": "segmind/Segmind-Vega",
13
- "SSD-1B": "segmind/SSD-1B",
14
- "Kandinsky 3": "kandinsky-community/kandinsky-3",
15
- "PixArt-LCM-XL-2-1024-MS": "PixArt-alpha/PixArt-LCM-XL-2-1024-MS",
16
- "BLIP Diffusion": "salesforce/blipdiffusion",
17
- "Muse-512-Finetuned": "amused/muse-512-finetuned",
18
- "Flux 1 Dev": "black-forest-labs/FLUX.1-dev"
19
- }
20
-
21
- # Set device
22
  device = "cuda" if torch.cuda.is_available() else "cpu"
23
  torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- # Cache for loaded pipelines
26
- loaded_pipelines = {}
 
 
 
 
 
 
 
 
 
 
27
 
28
- # Maximum seed value
29
- MAX_SEED = np.iinfo(np.int32).max
 
 
 
 
 
 
 
 
 
 
30
 
31
- def load_pipeline(model_name):
32
- """Load and cache the pipeline for the selected model."""
33
- if model_name in loaded_pipelines:
34
- return loaded_pipelines[model_name]
35
- repo_id = MODEL_REPOS[model_name]
36
- try:
37
- pipeline = DiffusionPipeline.from_pretrained(repo_id, torch_dtype=torch_dtype)
38
- pipeline.to(device)
39
- loaded_pipelines[model_name] = pipeline
40
- return pipeline
41
- except Exception as e:
42
- raise RuntimeError(f"Failed to load model '{model_name}': {e}")
43
 
44
- def generate_image(prompt, model_name, width, height, guidance_scale, num_inference_steps, seed, randomize_seed):
45
- """Generate an image using the selected model and parameters."""
46
  if randomize_seed:
47
  seed = random.randint(0, MAX_SEED)
48
- generator = torch.Generator(device=device).manual_seed(seed)
49
- pipeline = load_pipeline(model_name)
50
- try:
51
- image = pipeline(
52
- prompt=prompt,
53
- guidance_scale=guidance_scale,
54
- num_inference_steps=num_inference_steps,
55
- width=width,
56
- height=height,
57
- generator=generator
58
- ).images[0]
59
- return image, seed
60
- except Exception as e:
61
- raise RuntimeError(f"Image generation failed: {e}")
62
 
63
- # Define the Gradio interface
 
 
 
 
 
 
 
 
 
 
 
64
  with gr.Blocks() as demo:
65
- gr.Markdown("# 🖼️ Text-to-Image Generator with Multiple Models")
66
- with gr.Row():
67
- with gr.Column():
68
- prompt = gr.Textbox(label="Prompt", placeholder="Enter your prompt here")
69
- model_name = gr.Dropdown(label="Select Model", choices=list(MODEL_REPOS.keys()), value="Stable Diffusion XL Base 1.0")
70
- width = gr.Slider(label="Width", minimum=256, maximum=1024, step=64, value=512)
71
- height = gr.Slider(label="Height", minimum=256, maximum=1024, step=64, value=512)
72
- guidance_scale = gr.Slider(label="Guidance Scale", minimum=1.0, maximum=20.0, step=0.5, value=7.5)
73
- num_inference_steps = gr.Slider(label="Inference Steps", minimum=1, maximum=100, step=1, value=50)
74
- seed = gr.Slider(label="Seed", minimum=0, maximum=MAX_SEED, step=1, value=0)
75
- randomize_seed = gr.Checkbox(label="Randomize Seed", value=True)
76
- generate_button = gr.Button("Generate Image")
77
- with gr.Column():
78
- output_image = gr.Image(label="Generated Image")
79
- output_seed = gr.Textbox(label="Used Seed", interactive=False)
 
 
 
 
 
80
 
81
- generate_button.click(
82
- fn=generate_image,
83
- inputs=[prompt, model_name, width, height, guidance_scale, num_inference_steps, seed, randomize_seed],
84
- outputs=[output_image, output_seed]
85
- )
 
 
86
 
87
- if __name__ == "__main__":
88
- demo.launch()
 
1
  import gradio as gr
 
 
2
  import torch
3
+ import random
4
  from diffusers import DiffusionPipeline
5
+ from transformers import pipeline
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  device = "cuda" if torch.cuda.is_available() else "cpu"
8
  torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
9
+ MAX_SEED = 2**32 - 1
10
+
11
+ # --- Model lists ---
12
+ image_models = {
13
+ "Stable Diffusion 1.5": "runwayml/stable-diffusion-v1-5",
14
+ "Stable Diffusion 2.1": "stabilityai/stable-diffusion-2-1",
15
+ "SDXL Base 1.0": "stabilityai/stable-diffusion-xl-base-1.0",
16
+ "Playground v2": "playgroundai/playground-v2-1024px-aesthetic",
17
+ "Kandinsky 3": "kandinsky-community/kandinsky-3",
18
+ "PixArt": "PixArt-alpha/PixArt-LCM-XL-2-1024-MS",
19
+ "BLIP Diffusion": "Salesforce/blipdiffusion",
20
+ "Muse 512": "amused/muse-512-finetuned",
21
+ "Dreamlike 2.0": "dreamlike-art/dreamlike-photoreal-2.0",
22
+ "OpenJourney": "prompthero/openjourney"
23
+ }
24
 
25
+ video_models = {
26
+ "AnimateDiff": "animate-diff/animate-diff",
27
+ "CogVideoX-5b": "THUDM/CogVideoX-5b",
28
+ "HunyuanVideo": "tencent/HunyuanVideo",
29
+ "LTX-Video": "Lightricks/LTX-Video",
30
+ "ModelScope T2V": "damo-vilab/modelscope-text-to-video-synthesis",
31
+ "VideoCrafter": "videocrafter/videocrafter",
32
+ "Mochi-1": "mochi/mochi-1",
33
+ "Allegro": "allegro/allegro",
34
+ "OpenSora": "LanguageBind/Open-Sora-Plan-v1.2.0",
35
+ "Zer0Scope": "zero-scope/zero-scope"
36
+ }
37
 
38
+ text_models = {
39
+ "GPT-2": "gpt2",
40
+ "GPT-Neo 1.3B": "EleutherAI/gpt-neo-1.3B",
41
+ "GPT-J 6B": "EleutherAI/gpt-j-6B",
42
+ "BLOOM 1.1B": "bigscience/bloom-1b1",
43
+ "Falcon 7B": "tiiuae/falcon-7b",
44
+ "MPT 7B": "mosaicml/mpt-7b",
45
+ "LLaMA 2 7B": "meta-llama/Llama-2-7b-hf",
46
+ "BTLM 3B": "cerebras/btlm-3b-8k-base",
47
+ "XGen 7B": "Salesforce/xgen-7b-8k-base",
48
+ "StableLM 2": "stabilityai/stablelm-2-1_6b"
49
+ }
50
 
51
+ # --- Caching loaded pipelines ---
52
+ image_pipes = {}
53
+ text_pipes = {}
 
 
 
 
 
 
 
 
 
54
 
55
+ # --- Functional logic ---
56
+ def generate_image(prompt, model_name, seed, randomize_seed):
57
  if randomize_seed:
58
  seed = random.randint(0, MAX_SEED)
59
+ generator = torch.manual_seed(seed)
60
+
61
+ if model_name not in image_pipes:
62
+ image_pipes[model_name] = DiffusionPipeline.from_pretrained(
63
+ image_models[model_name],
64
+ torch_dtype=torch_dtype
65
+ ).to(device)
66
+
67
+ pipe = image_pipes[model_name]
68
+ image = pipe(prompt=prompt, generator=generator, num_inference_steps=25, width=512, height=512).images[0]
69
+ return image, seed
 
 
 
70
 
71
+ def generate_text(prompt, model_name):
72
+ if model_name not in text_pipes:
73
+ text_pipes[model_name] = pipeline("text-generation", model=text_models[model_name], device=0 if device == "cuda" else -1)
74
+ pipe = text_pipes[model_name]
75
+ output = pipe(prompt, max_length=100, do_sample=True)[0]['generated_text']
76
+ return output
77
+
78
+ def generate_video(prompt, model_name):
79
+ # Placeholder: real video models would return video frames
80
+ return f"[Video placeholder] Model: {model_name}\nPrompt: {prompt}"
81
+
82
+ # --- Interface ---
83
  with gr.Blocks() as demo:
84
+ gr.Markdown("# 🔄 Multi-Task AI Generator")
85
+
86
+ with gr.Tabs():
87
+ # Tab 1: Image Generation
88
+ with gr.Tab("🖼️ Image"):
89
+ img_prompt = gr.Textbox(label="Prompt")
90
+ img_model = gr.Dropdown(choices=list(image_models.keys()), value="Stable Diffusion 1.5", label="Select Image Model")
91
+ img_seed = gr.Slider(0, MAX_SEED, value=42, label="Seed")
92
+ img_rand = gr.Checkbox(label="Randomize seed", value=True)
93
+ img_btn = gr.Button("Generate Image")
94
+ img_out = gr.Image()
95
+ img_btn.click(fn=generate_image, inputs=[img_prompt, img_model, img_seed, img_rand], outputs=[img_out, img_seed])
96
+
97
+ # Tab 2: Video Generation
98
+ with gr.Tab("🎥 Video"):
99
+ vid_prompt = gr.Textbox(label="Prompt")
100
+ vid_model = gr.Dropdown(choices=list(video_models.keys()), value="AnimateDiff", label="Select Video Model")
101
+ vid_btn = gr.Button("Generate Video")
102
+ vid_out = gr.Textbox(label="Result (Placeholder)")
103
+ vid_btn.click(fn=generate_video, inputs=[vid_prompt, vid_model], outputs=vid_out)
104
 
105
+ # Tab 3: Text Generation
106
+ with gr.Tab("📝 Text"):
107
+ txt_prompt = gr.Textbox(label="Prompt")
108
+ txt_model = gr.Dropdown(choices=list(text_models.keys()), value="GPT-2", label="Select Text Model")
109
+ txt_btn = gr.Button("Generate Text")
110
+ txt_out = gr.Textbox(label="Generated Text")
111
+ txt_btn.click(fn=generate_text, inputs=[txt_prompt, txt_model], outputs=txt_out)
112
 
113
+ demo.launch(show_error=True)