vam commited on
Commit
d08879f
·
verified ·
1 Parent(s): c0af8d7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -131
app.py CHANGED
@@ -1,149 +1,96 @@
1
  import gradio as gr
2
  import numpy as np
3
  import random
 
 
 
 
4
  from openai import OpenAI
5
-
6
  import os
7
 
8
  api_key = os.getenv("YOUR_OPENAI_KEY")
9
  client = OpenAI(api_key=api_key)
10
 
11
- #import spaces #[uncomment to use ZeroGPU]
12
- from diffusers import DiffusionPipeline
13
- import torch
14
-
15
- device = "cuda" if torch.cuda.is_available() else "cpu"
16
- model_repo_id = "stabilityai/sdxl-turbo" #Replace to the model you would like to use
17
-
18
- if torch.cuda.is_available():
19
- torch_dtype = torch.float16
20
- else:
21
- torch_dtype = torch.float32
22
-
23
- pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype)
24
- pipe = pipe.to(device)
25
-
26
- MAX_SEED = np.iinfo(np.int32).max
27
- MAX_IMAGE_SIZE = 1024
 
 
 
 
 
 
28
 
29
- #@spaces.GPU #[uncomment to use ZeroGPU]
30
- def infer(prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps, progress=gr.Progress(track_tqdm=True)):
31
 
32
- if randomize_seed:
33
- seed = random.randint(0, MAX_SEED)
34
-
35
- generator = torch.Generator().manual_seed(seed)
36
 
37
- image = pipe(
38
- prompt = prompt,
39
- negative_prompt = negative_prompt,
40
- guidance_scale = guidance_scale,
41
- num_inference_steps = num_inference_steps,
42
- width = width,
43
- height = height,
44
- generator = generator
45
- ).images[0]
46
 
47
- return image, seed
48
-
49
- examples = [
50
- "Astronaut in a jungle, cold color palette, muted colors, detailed, 8k",
51
- "An astronaut riding a green horse",
52
- "A delicious ceviche cheesecake slice",
53
- ]
54
-
55
- css="""
56
- #col-container {
57
- margin: 0 auto;
58
- max-width: 640px;
59
- }
60
- """
61
-
62
- with gr.Blocks(css=css) as demo:
63
 
64
- with gr.Column(elem_id="col-container"):
65
- gr.Markdown(f"""
66
- # Text-to-Image Gradio Template
67
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
- with gr.Row():
70
-
71
- prompt = gr.Text(
72
- label="Prompt",
73
- show_label=False,
74
- max_lines=1,
75
- placeholder="Enter your prompt",
76
- container=False,
77
- )
78
-
79
- run_button = gr.Button("Run", scale=0)
80
 
81
- result = gr.Image(label="Result", show_label=False)
82
-
83
- with gr.Accordion("Advanced Settings", open=False):
84
-
85
- negative_prompt = gr.Text(
86
- label="Negative prompt",
87
- max_lines=1,
88
- placeholder="Enter a negative prompt",
89
- visible=False,
90
- )
91
-
92
- seed = gr.Slider(
93
- label="Seed",
94
- minimum=0,
95
- maximum=MAX_SEED,
96
- step=1,
97
- value=0,
98
- )
99
-
100
- randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
101
-
102
- with gr.Row():
103
-
104
- width = gr.Slider(
105
- label="Width",
106
- minimum=256,
107
- maximum=MAX_IMAGE_SIZE,
108
- step=32,
109
- value=1024, #Replace with defaults that work for your model
110
- )
111
-
112
- height = gr.Slider(
113
- label="Height",
114
- minimum=256,
115
- maximum=MAX_IMAGE_SIZE,
116
- step=32,
117
- value=1024, #Replace with defaults that work for your model
118
- )
119
-
120
- with gr.Row():
121
-
122
- guidance_scale = gr.Slider(
123
- label="Guidance scale",
124
- minimum=0.0,
125
- maximum=10.0,
126
- step=0.1,
127
- value=0.0, #Replace with defaults that work for your model
128
- )
129
-
130
- num_inference_steps = gr.Slider(
131
- label="Number of inference steps",
132
- minimum=1,
133
- maximum=50,
134
- step=1,
135
- value=2, #Replace with defaults that work for your model
136
- )
137
 
138
- gr.Examples(
139
- examples = examples,
140
- inputs = [prompt]
141
- )
142
- gr.on(
143
- triggers=[run_button.click, prompt.submit],
144
- fn = infer,
145
- inputs = [prompt, negative_prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
146
- outputs = [result, seed]
147
- )
148
 
149
- demo.queue().launch()
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
+ import matplotlib.pyplot as plt
5
+ import matplotlib.image as mpimg
6
+ from embedding import model, docs_list, doc_embeddings, embedded_dict
7
+ import openai
8
  from openai import OpenAI
 
9
  import os
10
 
11
  api_key = os.getenv("YOUR_OPENAI_KEY")
12
  client = OpenAI(api_key=api_key)
13
 
14
+ # Function to generate meme caption using GPT model
15
+ def generate_meme_caption(topic):
16
+ response = openai.ChatCompletion.create(
17
+ model="gpt-4o-mini",
18
+ messages=[
19
+ {
20
+ "role": "user",
21
+ "content": f'''You are a loser, a meme lover who is always on the internet.
22
+ You are a meme professional, so you will generate short captions for memes based on the following rules:
23
+ Do not add emoji.
24
+ Do not add any punctuation.
25
+ Must be funny.
26
+ Only if some topic related to friends, use "bro" or "blud".
27
+ Answer from previous question can not be the same for this time prompt.
28
+ If the user does not specify their caption request, you can generate a short caption for the meme.
29
+ But if they do, you cannot replace their prompt; just need to copy their request and make it the caption.
30
+ Now generate a caption based on this topic: {topic}.
31
+ '''
32
+ }
33
+ ],
34
+ max_tokens=250,
35
+ temperature=1.1
36
+ )
37
 
38
+ caption = response['choices'][0]['message']['content']
39
+ return caption
40
 
41
+ # Function to create meme with caption
42
+ def create_meme(prompt):
43
+ # Tạo embedding cho prompt
44
+ prompt_embedding = model.encode([prompt])
45
 
46
+ # Tính toán độ tương đồng giữa prompt và các văn bản
47
+ similarities = model.similarity(prompt_embedding, doc_embeddings)
 
 
 
 
 
 
 
48
 
49
+ # Lấy chỉ số văn bản có độ tương đồng cao nhất
50
+ closest_text_idx = np.argmax(similarities)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
+ # Tải ảnh meme tương ứng
53
+ img_path = f'/kaggle/input/memedata/{embedded_dict[closest_text_idx]["filename"]}'
54
+ img = mpimg.imread(img_path)
55
+
56
+ # Tạo khoảng trắng để hiển thị caption
57
+ white_space_height = 100
58
+ white_space = np.ones((white_space_height, img.shape[1], img.shape[2]), dtype=img.dtype) * 255
59
+
60
+ # Kết hợp khoảng trắng với hình ảnh gốc
61
+ combined_img = np.vstack((white_space, img))
62
+
63
+ # Sinh caption từ GPT model
64
+ caption = generate_meme_caption(prompt)
65
+
66
+ # Hiển thị ảnh với caption
67
+ plt.imshow(combined_img)
68
+ plt.axis('off')
69
+ plt.text(
70
+ x=combined_img.shape[1] / 2,
71
+ y=white_space_height / 2,
72
+ s=caption,
73
+ fontsize=11, color='black', ha='center', va='top', fontweight='bold'
74
+ )
75
+
76
+ plt.show()
77
+
78
+ # Gradio interface
79
+ with gr.Blocks() as demo:
80
+ with gr.Column():
81
+ gr.Markdown("# Meme Generator using Embeddings and GPT")
82
 
83
+ prompt = gr.Textbox(label="Enter your meme prompt:")
84
+ run_button = gr.Button("Generate Meme")
 
 
 
 
 
 
 
 
 
85
 
86
+ result = gr.Plot(label="Generated Meme")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
+ def gradio_infer(prompt):
89
+ plt.figure(figsize=(10, 8))
90
+ create_meme(prompt)
91
+ plt.savefig('/tmp/meme.png') # Lưu hình tạm thời
92
+ return plt
93
+
94
+ run_button.click(gradio_infer, inputs=[prompt], outputs=[result])
 
 
 
95
 
96
+ demo.launch()