faizee07 commited on
Commit
8e00ad1
Β·
verified Β·
1 Parent(s): 5c62b96

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +197 -183
app.py CHANGED
@@ -1,184 +1,198 @@
1
- import asyncio
2
- import gradio as gr
3
- from browser_use import Agent
4
- from langchain_huggingface import HuggingFaceEndpoint
5
- import re
6
- import os
7
-
8
- # Model mapping
9
- MODELS = {
10
- "Qwen 2.5 72B (Recommended)": "Qwen/Qwen2.5-72B-Instruct",
11
- "Meta Llama 3.1 70B": "meta-llama/Llama-3.1-70B-Instruct",
12
- "Mixtral 8x7B": "mistralai/Mixtral-8x7B-Instruct-v0.1",
13
- "Phi-3 Medium": "microsoft/Phi-3-medium-4k-instruct",
14
- }
15
-
16
- async def generate_meme_async(query: str, model_name: str, hf_token: str):
17
- """Async function to generate meme"""
18
-
19
- # Get token from environment if not provided
20
- if not hf_token:
21
- hf_token = os.environ.get("HF_TOKEN", "")
22
-
23
- if not hf_token:
24
- return None, "❌ Error: HuggingFace token is required! Get one from https://huggingface.co/settings/tokens"
25
-
26
- if not query:
27
- return None, "❌ Error: Please enter a meme idea!"
28
-
29
- try:
30
- # Initialize HuggingFace LLM
31
- llm = HuggingFaceEndpoint(
32
- repo_id=MODELS[model_name],
33
- huggingfacehub_api_token=hf_token,
34
- temperature=0.3,
35
- max_new_tokens=2048,
36
- top_k=50,
37
- top_p=0.95
38
- )
39
-
40
- task_description = (
41
- f"You are a meme generator expert. Generate a meme for: '{query}'\n\n"
42
- "Steps:\n"
43
- "1. Go to https://imgflip.com/memetemplates\n"
44
- "2. Search for ONE main action verb from the query (like 'laugh', 'cry', 'think')\n"
45
- "3. Pick a fitting meme template and click 'Add Caption'\n"
46
- "4. Write Top Text (setup) and Bottom Text (punchline) about: '{query}'\n"
47
- "5. Preview and adjust if needed\n"
48
- "6. Click 'Generate meme'\n"
49
- "7. Copy and return the image URL\n"
50
- ).format(query=query)
51
-
52
- agent = Agent(
53
- task=task_description,
54
- llm=llm,
55
- max_actions_per_step=5,
56
- max_failures=25,
57
- use_vision=False
58
- )
59
-
60
- history = await agent.run()
61
- final_result = history.final_result()
62
-
63
- # Extract meme URL
64
- url_match = re.search(r'https://imgflip\.com/i/(\w+)', final_result)
65
- if url_match:
66
- meme_id = url_match.group(1)
67
- meme_url = f"https://i.imgflip.com/{meme_id}.jpg"
68
- return meme_url, f"βœ… Success! Meme generated using {model_name}"
69
-
70
- return None, "❌ Could not generate meme. Try rephrasing your idea or use a different model."
71
-
72
- except Exception as e:
73
- return None, f"❌ Error: {str(e)}\n\nTip: Make sure your HuggingFace token is valid!"
74
-
75
- def generate_meme(query: str, model_name: str, hf_token: str):
76
- """Wrapper function for Gradio"""
77
- return asyncio.run(generate_meme_async(query, model_name, hf_token))
78
-
79
- # Example meme ideas
80
- examples = [
81
- ["When you finally fix the bug at 3 AM", "Qwen 2.5 72B (Recommended)"],
82
- ["Junior dev vs Senior dev looking at the same error", "Meta Llama 3.1 70B"],
83
- ["My code in development vs in production", "Qwen 2.5 72B (Recommended)"],
84
- ["Trying to explain AI to my parents", "Mixtral 8x7B"],
85
- ["Me before coffee vs after coffee", "Qwen 2.5 72B (Recommended)"],
86
- ]
87
-
88
- # Create Gradio interface
89
- with gr.Blocks(theme=gr.themes.Soft(), title="πŸ₯Έ AI Meme Generator") as demo:
90
-
91
- gr.Markdown("""
92
- # πŸ₯Έ AI Meme Generator
93
- ### Powered by Free HuggingFace Models πŸ€—
94
-
95
- This AI agent automatically browses ImgFlip and creates memes based on your description!
96
- """)
97
-
98
- with gr.Row():
99
- with gr.Column(scale=2):
100
- query_input = gr.Textbox(
101
- label="🎨 Describe Your Meme Idea",
102
- placeholder="Example: When the client says 'just one small change'...",
103
- lines=3
104
- )
105
-
106
- model_dropdown = gr.Dropdown(
107
- choices=list(MODELS.keys()),
108
- value="Qwen 2.5 72B (Recommended)",
109
- label="πŸ€– Select AI Model (All Free!)",
110
- info="Choose which model to use for meme generation"
111
- )
112
-
113
- token_input = gr.Textbox(
114
- label="πŸ”‘ HuggingFace Token (Optional if set in Space secrets)",
115
- placeholder="hf_...",
116
- type="password",
117
- value=os.environ.get("HF_TOKEN", "")
118
- )
119
-
120
- with gr.Row():
121
- generate_btn = gr.Button("πŸš€ Generate Meme", variant="primary", size="lg")
122
- clear_btn = gr.ClearButton(components=[query_input], value="πŸ—‘οΈ Clear")
123
-
124
- with gr.Column(scale=1):
125
- gr.Markdown("""
126
- ### πŸ“– Quick Guide
127
-
128
- **First Time?**
129
- 1. Get FREE token: [HuggingFace Tokens](https://huggingface.co/settings/tokens)
130
- 2. Paste it above
131
- 3. Describe your meme
132
- 4. Click Generate!
133
-
134
- **Tips for Best Results:**
135
- - Be specific and descriptive
136
- - Include the emotion/scenario
137
- - Think about popular meme formats
138
- - Qwen 2.5 72B works best!
139
-
140
- **Examples:**
141
- - "Confident vs reality"
142
- - "Before/after situations"
143
- - "Expectations vs reality"
144
- - "Relatable daily struggles"
145
- """)
146
-
147
- with gr.Row():
148
- output_image = gr.Image(label="Generated Meme", type="filepath")
149
-
150
- status_output = gr.Textbox(label="Status", lines=2)
151
-
152
- gr.Markdown("""
153
- ### πŸ’‘ Example Meme Ideas (Click to try!)
154
- """)
155
-
156
- gr.Examples(
157
- examples=examples,
158
- inputs=[query_input, model_dropdown],
159
- label="Click any example to auto-fill"
160
- )
161
-
162
- gr.Markdown("""
163
- ---
164
- <div style='text-align: center;'>
165
- <p><strong>πŸ€— 100% Free & Open Source</strong></p>
166
- <p>Powered by HuggingFace Inference API β€’ Browser-Use β€’ Gradio</p>
167
- <p>⭐ Star on GitHub if you like this project!</p>
168
- </div>
169
- """)
170
-
171
- # Connect button to function
172
- generate_btn.click(
173
- fn=generate_meme,
174
- inputs=[query_input, model_dropdown, token_input],
175
- outputs=[output_image, status_output]
176
- )
177
-
178
- # Launch the app
179
- if __name__ == "__main__":
180
- demo.launch(
181
- server_name="0.0.0.0",
182
- server_port=7860,
183
- share=False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  )
 
1
+ import asyncio
2
+ import gradio as gr
3
+ from browser_use import Agent
4
+ from langchain_huggingface import HuggingFaceEndpoint
5
+ import re
6
+ import os
7
+ import subprocess
8
+ import sys
9
+
10
+ # Install Playwright on startup
11
+ def install_playwright():
12
+ try:
13
+ subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=True)
14
+ subprocess.run([sys.executable, "-m", "playwright", "install-deps", "chromium"], check=True)
15
+ print("βœ… Playwright installed successfully")
16
+ except Exception as e:
17
+ print(f"⚠️ Playwright installation warning: {e}")
18
+
19
+ # Run installation
20
+ install_playwright()
21
+
22
+ # Model mapping
23
+ MODELS = {
24
+ "Qwen 2.5 72B (Recommended)": "Qwen/Qwen2.5-72B-Instruct",
25
+ "Meta Llama 3.1 70B": "meta-llama/Llama-3.1-70B-Instruct",
26
+ "Mixtral 8x7B": "mistralai/Mixtral-8x7B-Instruct-v0.1",
27
+ "Phi-3 Medium": "microsoft/Phi-3-medium-4k-instruct",
28
+ }
29
+
30
+ async def generate_meme_async(query: str, model_name: str, hf_token: str):
31
+ """Async function to generate meme"""
32
+
33
+ # Get token from environment if not provided
34
+ if not hf_token:
35
+ hf_token = os.environ.get("HF_TOKEN", "")
36
+
37
+ if not hf_token:
38
+ return None, "❌ Error: HuggingFace token is required! Get one from https://huggingface.co/settings/tokens"
39
+
40
+ if not query:
41
+ return None, "❌ Error: Please enter a meme idea!"
42
+
43
+ try:
44
+ # Initialize HuggingFace LLM
45
+ llm = HuggingFaceEndpoint(
46
+ repo_id=MODELS[model_name],
47
+ huggingfacehub_api_token=hf_token,
48
+ temperature=0.3,
49
+ max_new_tokens=2048,
50
+ top_k=50,
51
+ top_p=0.95
52
+ )
53
+
54
+ task_description = (
55
+ f"You are a meme generator expert. Generate a meme for: '{query}'\n\n"
56
+ "Steps:\n"
57
+ "1. Go to https://imgflip.com/memetemplates\n"
58
+ "2. Search for ONE main action verb from the query (like 'laugh', 'cry', 'think')\n"
59
+ "3. Pick a fitting meme template and click 'Add Caption'\n"
60
+ "4. Write Top Text (setup) and Bottom Text (punchline) about: '{query}'\n"
61
+ "5. Preview and adjust if needed\n"
62
+ "6. Click 'Generate meme'\n"
63
+ "7. Copy and return the image URL\n"
64
+ ).format(query=query)
65
+
66
+ agent = Agent(
67
+ task=task_description,
68
+ llm=llm,
69
+ max_actions_per_step=5,
70
+ max_failures=25,
71
+ use_vision=False
72
+ )
73
+
74
+ history = await agent.run()
75
+ final_result = history.final_result()
76
+
77
+ # Extract meme URL
78
+ url_match = re.search(r'https://imgflip\.com/i/(\w+)', final_result)
79
+ if url_match:
80
+ meme_id = url_match.group(1)
81
+ meme_url = f"https://i.imgflip.com/{meme_id}.jpg"
82
+ return meme_url, f"βœ… Success! Meme generated using {model_name}"
83
+
84
+ return None, "❌ Could not generate meme. Try rephrasing your idea or use a different model."
85
+
86
+ except Exception as e:
87
+ return None, f"❌ Error: {str(e)}\n\nTip: Make sure your HuggingFace token is valid!"
88
+
89
+ def generate_meme(query: str, model_name: str, hf_token: str):
90
+ """Wrapper function for Gradio"""
91
+ return asyncio.run(generate_meme_async(query, model_name, hf_token))
92
+
93
+ # Example meme ideas
94
+ examples = [
95
+ ["When you finally fix the bug at 3 AM", "Qwen 2.5 72B (Recommended)"],
96
+ ["Junior dev vs Senior dev looking at the same error", "Meta Llama 3.1 70B"],
97
+ ["My code in development vs in production", "Qwen 2.5 72B (Recommended)"],
98
+ ["Trying to explain AI to my parents", "Mixtral 8x7B"],
99
+ ["Me before coffee vs after coffee", "Qwen 2.5 72B (Recommended)"],
100
+ ]
101
+
102
+ # Create Gradio interface
103
+ with gr.Blocks(theme=gr.themes.Soft(), title="πŸ₯Έ AI Meme Generator") as demo:
104
+
105
+ gr.Markdown("""
106
+ # πŸ₯Έ AI Meme Generator
107
+ ### Powered by Free HuggingFace Models πŸ€—
108
+
109
+ This AI agent automatically browses ImgFlip and creates memes based on your description!
110
+ """)
111
+
112
+ with gr.Row():
113
+ with gr.Column(scale=2):
114
+ query_input = gr.Textbox(
115
+ label="🎨 Describe Your Meme Idea",
116
+ placeholder="Example: When the client says 'just one small change'...",
117
+ lines=3
118
+ )
119
+
120
+ model_dropdown = gr.Dropdown(
121
+ choices=list(MODELS.keys()),
122
+ value="Qwen 2.5 72B (Recommended)",
123
+ label="πŸ€– Select AI Model (All Free!)",
124
+ info="Choose which model to use for meme generation"
125
+ )
126
+
127
+ token_input = gr.Textbox(
128
+ label="πŸ”‘ HuggingFace Token (Optional if set in Space secrets)",
129
+ placeholder="hf_...",
130
+ type="password",
131
+ value=os.environ.get("HF_TOKEN", "")
132
+ )
133
+
134
+ with gr.Row():
135
+ generate_btn = gr.Button("πŸš€ Generate Meme", variant="primary", size="lg")
136
+ clear_btn = gr.ClearButton(components=[query_input], value="πŸ—‘οΈ Clear")
137
+
138
+ with gr.Column(scale=1):
139
+ gr.Markdown("""
140
+ ### πŸ“– Quick Guide
141
+
142
+ **First Time?**
143
+ 1. Get FREE token: [HuggingFace Tokens](https://huggingface.co/settings/tokens)
144
+ 2. Paste it above
145
+ 3. Describe your meme
146
+ 4. Click Generate!
147
+
148
+ **Tips for Best Results:**
149
+ - Be specific and descriptive
150
+ - Include the emotion/scenario
151
+ - Think about popular meme formats
152
+ - Qwen 2.5 72B works best!
153
+
154
+ **Examples:**
155
+ - "Confident vs reality"
156
+ - "Before/after situations"
157
+ - "Expectations vs reality"
158
+ - "Relatable daily struggles"
159
+ """)
160
+
161
+ with gr.Row():
162
+ output_image = gr.Image(label="Generated Meme", type="filepath")
163
+
164
+ status_output = gr.Textbox(label="Status", lines=2)
165
+
166
+ gr.Markdown("""
167
+ ### πŸ’‘ Example Meme Ideas (Click to try!)
168
+ """)
169
+
170
+ gr.Examples(
171
+ examples=examples,
172
+ inputs=[query_input, model_dropdown],
173
+ label="Click any example to auto-fill"
174
+ )
175
+
176
+ gr.Markdown("""
177
+ ---
178
+ <div style='text-align: center;'>
179
+ <p><strong>πŸ€— 100% Free & Open Source</strong></p>
180
+ <p>Powered by HuggingFace Inference API β€’ Browser-Use β€’ Gradio</p>
181
+ <p>⭐ Star on GitHub if you like this project!</p>
182
+ </div>
183
+ """)
184
+
185
+ # Connect button to function
186
+ generate_btn.click(
187
+ fn=generate_meme,
188
+ inputs=[query_input, model_dropdown, token_input],
189
+ outputs=[output_image, status_output]
190
+ )
191
+
192
+ # Launch the app
193
+ if __name__ == "__main__":
194
+ demo.launch(
195
+ server_name="0.0.0.0",
196
+ server_port=7860,
197
+ share=False
198
  )