noumanjavaid commited on
Commit
a6084f0
Β·
verified Β·
1 Parent(s): b4c4f3a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +154 -0
app.py ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ from dotenv import load_dotenv, set_key
4
+ import requests
5
+ import asyncio
6
+ from telegram import Update
7
+ from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
8
+
9
+ # Page config
10
+ st.set_page_config(page_title="Meme Bot Setup", page_icon="🎭")
11
+
12
+ # Load environment variables
13
+ load_dotenv()
14
+
15
+ # Initialize session state
16
+ if 'bot_running' not in st.session_state:
17
+ st.session_state.bot_running = False
18
+
19
+ def format_meme_prompt(user_input):
20
+ """Format user input into a meme-specific prompt"""
21
+ return f"Create a funny meme that shows: {user_input}. Make it in classic meme style with impact font text. Make it humorous and shareable. The image should be meme-worthy and entertaining."
22
+
23
+ def save_credentials(telegram_token, openai_key):
24
+ """Save credentials to .env file"""
25
+ try:
26
+ with open('.env', 'w') as f:
27
+ f.write(f'TELEGRAM_BOT_TOKEN="{telegram_token}"\n')
28
+ f.write(f'IMAGE_API_KEY="{openai_key}"\n')
29
+ return True
30
+ except Exception as e:
31
+ st.error(f"Error saving credentials: {str(e)}")
32
+ return False
33
+
34
+ async def test_meme_generation(prompt):
35
+ """Test meme generation with OpenAI API"""
36
+ api_key = os.getenv("IMAGE_API_KEY")
37
+ if not api_key:
38
+ return None, "OpenAI API key not found"
39
+
40
+ formatted_prompt = format_meme_prompt(prompt)
41
+ headers = {"Authorization": f"Bearer {api_key}"}
42
+ data = {
43
+ "prompt": formatted_prompt,
44
+ "size": "1024x1024",
45
+ "model": "dall-e-3"
46
+ }
47
+
48
+ try:
49
+ response = requests.post(
50
+ "https://api.openai.com/v1/images/generate",
51
+ json=data,
52
+ headers=headers,
53
+ timeout=15
54
+ )
55
+ if response.status_code == 200:
56
+ return response.json()["data"][0]["url"], None
57
+ else:
58
+ return None, f"API Error: {response.status_code} - {response.text}"
59
+ except Exception as e:
60
+ return None, f"Request failed: {str(e)}"
61
+
62
+ # Main UI
63
+ st.title("🎭 Meme Bot Setup")
64
+ st.markdown("Configure your Telegram bot to generate memes!")
65
+
66
+ # Credentials Section
67
+ st.header("Bot Configuration")
68
+ with st.form("credentials_form"):
69
+ telegram_token = st.text_input(
70
+ "Telegram Bot Token",
71
+ value=os.getenv("TELEGRAM_BOT_TOKEN", ""),
72
+ type="password",
73
+ help="Get this from @BotFather on Telegram"
74
+ )
75
+ openai_key = st.text_input(
76
+ "OpenAI API Key",
77
+ value=os.getenv("IMAGE_API_KEY", ""),
78
+ type="password",
79
+ help="Get this from OpenAI Platform"
80
+ )
81
+ save_button = st.form_submit_button("Save Credentials")
82
+
83
+ if save_button:
84
+ if telegram_token and openai_key:
85
+ if save_credentials(telegram_token, openai_key):
86
+ st.success("Credentials saved successfully!")
87
+ load_dotenv()
88
+ else:
89
+ st.error("Please provide both API keys")
90
+
91
+ # Test Meme Generation
92
+ st.header("Test Meme Generation")
93
+ test_prompt = st.text_input(
94
+ "Enter your meme idea",
95
+ placeholder="e.g., 'When you forget to save your work'"
96
+ )
97
+
98
+ if st.button("Generate Test Meme"):
99
+ if not os.getenv("IMAGE_API_KEY"):
100
+ st.error("Please set the OpenAI API key first")
101
+ else:
102
+ with st.spinner("Creating your meme..."):
103
+ image_url, error = asyncio.run(test_meme_generation(test_prompt))
104
+ if error:
105
+ st.error(error)
106
+ else:
107
+ st.image(image_url, caption="Your Generated Meme")
108
+ st.success("Meme generated successfully!")
109
+
110
+ # Bot Status
111
+ st.header("Bot Status")
112
+ col1, col2 = st.columns(2)
113
+
114
+ with col1:
115
+ if st.button("Start Bot" if not st.session_state.bot_running else "Stop Bot"):
116
+ if not st.session_state.bot_running:
117
+ if not os.getenv("TELEGRAM_BOT_TOKEN"):
118
+ st.error("Please set the Telegram Bot Token first")
119
+ else:
120
+ st.session_state.bot_running = True
121
+ st.success("Bot started!")
122
+ st.rerun()
123
+ else:
124
+ st.session_state.bot_running = False
125
+ st.warning("Bot stopped")
126
+ st.rerun()
127
+
128
+ with col2:
129
+ status = "🟒 Running" if st.session_state.bot_running else "πŸ”΄ Stopped"
130
+ st.write(f"Status: {status}")
131
+
132
+ # Instructions
133
+ with st.expander("How to Use"):
134
+ st.markdown("""
135
+ ### Setup Steps:
136
+ 1. Get a Telegram Bot Token from [@BotFather](https://t.me/botfather)
137
+ 2. Get an OpenAI API key from [OpenAI Platform](https://platform.openai.com)
138
+ 3. Enter both keys above and save
139
+ 4. Start the bot
140
+
141
+ ### Using the Bot:
142
+ 1. Find your bot on Telegram
143
+ 2. Send /start to begin
144
+ 3. Send any text to generate a meme
145
+
146
+ ### Example Prompts:
147
+ - "When the code works on first try"
148
+ - "Me explaining why I need another monitor"
149
+ - "That moment when you forget to git commit"
150
+ """)
151
+
152
+ # Footer
153
+ st.markdown("---")
154
+ st.markdown("Made for generating awesome memes 🎭")