artintel235 commited on
Commit
38c235b
·
verified ·
1 Parent(s): 92b570f

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +223 -0
app.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import firebase_admin
3
+ from firebase_admin import credentials
4
+ from firebase_admin import auth
5
+ from firebase_admin import firestore
6
+ from firebase_admin import storage
7
+ import requests
8
+ from io import BytesIO
9
+ from PIL import Image
10
+ import os
11
+ import tempfile
12
+ import mimetypes
13
+ import uuid
14
+
15
+
16
+ TOKEN = os.getenv("TOKEN0")
17
+ API_URL = os.getenv("API_URL")
18
+ token_id = 0
19
+ tokens_tried = 0
20
+ no_of_accounts = 11
21
+ model_id = os.getenv("MODEL_ID")
22
+
23
+ # Initialize Firebase Admin SDK
24
+ cred = credentials.Certificate("path/to/your/firebase/credentials.json")
25
+ firebase_admin.initialize_app(cred, {
26
+ 'storageBucket': 'your_storage_bucket_url'
27
+ })
28
+ db = firestore.client()
29
+ bucket = storage.bucket()
30
+
31
+
32
+ def get_image_from_url(url):
33
+ """
34
+ Fetches and returns an image from a given URL, converting to PNG if needed.
35
+ """
36
+ try:
37
+ response = requests.get(url, stream=True)
38
+ response.raise_for_status()
39
+ image = Image.open(BytesIO(response.content))
40
+ return image, url # Return the image and the URL
41
+
42
+ except requests.exceptions.RequestException as e:
43
+ return f"Error fetching image: {e}", None
44
+ except Exception as e:
45
+ return f"Error processing image: {e}", None
46
+
47
+
48
+ def generate_image(prompt, aspect_ratio, realism, user_id):
49
+ global token_id
50
+ global TOKEN
51
+ global tokens_tried
52
+ global no_of_accounts
53
+ global model_id
54
+
55
+ payload = {
56
+ "id": model_id,
57
+ "inputs": [prompt, aspect_ratio, str(realism).lower()],
58
+ }
59
+ headers = {"Authorization": f"Bearer {TOKEN}"}
60
+
61
+ try:
62
+ response_data = requests.post(API_URL, json=payload, headers=headers).json()
63
+ if "error" in response_data:
64
+ if 'error 429' in response_data['error']:
65
+ if tokens_tried < no_of_accounts:
66
+ token_id = (token_id + 1) % (no_of_accounts)
67
+ tokens_tried += 1
68
+ TOKEN = os.getenv(f"TOKEN{token_id}")
69
+ response_data = generate_image(prompt, aspect_ratio, realism, user_id)
70
+ tokens_tried = 0
71
+ return response_data
72
+ return "No credits available", None, None
73
+ return response_data, None, None
74
+ elif "output" in response_data:
75
+ url = response_data['output']
76
+ image, url = get_image_from_url(url)
77
+ # Store in firebase
78
+ download_path = download_image(url)
79
+ if download_path:
80
+ try:
81
+ # Create a unique filename for the image
82
+ image_filename = f"{uuid.uuid4()}{os.path.splitext(download_path)[1]}"
83
+ # Store file in cloud storage
84
+ blob = bucket.blob(f'users/{user_id}/{image_filename}')
85
+ blob.upload_from_filename(download_path)
86
+ image_url = blob.public_url
87
+ # Store prompt and image URL in Firestore
88
+ doc_ref = db.collection("images").add({
89
+ "user_id": user_id,
90
+ "prompt": prompt,
91
+ "image_url": image_url,
92
+ })
93
+ print(f"Document added with id: {doc_ref.id}")
94
+ os.remove(download_path)
95
+ return image, image_url, image_url
96
+ except Exception as e:
97
+ print(f"Error uploading image to firebase {e}")
98
+ return image, None, url
99
+ else:
100
+ return image, None, url # Return the image and the URL
101
+ else:
102
+ return "Error: Unexpected response from server", None, None
103
+ except Exception as e:
104
+ print(f"Error: {e}")
105
+ return f"Error", None, None
106
+
107
+
108
+ def download_image(image_url):
109
+ if not image_url:
110
+ return None # Return None if image_url is empty
111
+ try:
112
+ response = requests.get(image_url, stream=True)
113
+ response.raise_for_status()
114
+
115
+ # Get the content type from the headers
116
+ content_type = response.headers.get('content-type')
117
+ extension = mimetypes.guess_extension(content_type)
118
+
119
+ if not extension:
120
+ extension = ".png" # Default to .png if can't determine the extension
121
+
122
+ # Create a temporary file with the correct extension
123
+ with tempfile.NamedTemporaryFile(suffix=extension, delete=False) as tmp_file:
124
+ for chunk in response.iter_content(chunk_size=8192):
125
+ tmp_file.write(chunk)
126
+ temp_file_path = tmp_file.name
127
+ return temp_file_path
128
+ except Exception as e:
129
+ return None
130
+
131
+
132
+ def create_user_with_email_and_password(email, password):
133
+ try:
134
+ user = auth.create_user(
135
+ email = email,
136
+ password = password,
137
+ )
138
+ return user.uid, None
139
+ except Exception as e:
140
+ print(f"Error creating user {e}")
141
+ return None, str(e)
142
+
143
+ def sign_in_with_email_and_password(email, password):
144
+ try:
145
+ user = auth.get_user_by_email(email)
146
+ return user.uid, None
147
+ except Exception as e:
148
+ print(f"Error logging in user: {e}")
149
+ return None, str(e)
150
+
151
+
152
+ def main():
153
+ st.title("Image Generator")
154
+
155
+ # Initialize session state
156
+ if "user_id" not in st.session_state:
157
+ st.session_state.user_id = None
158
+
159
+
160
+ # Check if user is logged in
161
+ if not st.session_state.user_id:
162
+ st.subheader("Login/Signup")
163
+ st.session_state.login_status = False
164
+ login_option = st.radio("Select Option", ("Login", "Sign Up"))
165
+ if login_option == "Login":
166
+ email = st.text_input("Email")
167
+ password = st.text_input("Password", type="password")
168
+ if st.button("Log In"):
169
+ if email and password:
170
+ user_id, error = sign_in_with_email_and_password(email, password)
171
+ if user_id:
172
+ st.success("Logged in successfully!")
173
+ st.session_state.user_id = user_id
174
+ st.session_state.login_status = True
175
+ else:
176
+ st.error(f"Login Failed: {error}")
177
+ else:
178
+ st.error("Please provide both email and password")
179
+ elif login_option == "Sign Up":
180
+ email = st.text_input("Email")
181
+ password = st.text_input("Password", type="password")
182
+ if st.button("Sign Up"):
183
+ if email and password:
184
+ user_id, error = create_user_with_email_and_password(email, password)
185
+ if user_id:
186
+ st.success("Signed up successfully!")
187
+ st.session_state.user_id = user_id
188
+ st.session_state.login_status = True
189
+ else:
190
+ st.error(f"Sign Up Failed: {error}")
191
+ else:
192
+ st.error("Please provide both email and password")
193
+
194
+ # Main app logic if logged in
195
+ if st.session_state.user_id:
196
+ prompt = st.text_input("Prompt", placeholder="Describe the image you want to generate")
197
+ aspect_ratio = st.radio(
198
+ "Aspect Ratio",
199
+ ["1:1", "3:4", "4:3", "9:16", "16:9", "9:21", "21:9"],
200
+ index=4 #Default value is 16:9
201
+ )
202
+ realism = st.checkbox("Realism", value=False)
203
+
204
+ if st.button("Generate Image"):
205
+ image, url, file_url = generate_image(prompt, aspect_ratio, realism, st.session_state.user_id)
206
+
207
+ if isinstance(image, str):
208
+ st.error(image)
209
+ elif image:
210
+ st.image(image, caption="Generated Image", use_column_width=True)
211
+ if url:
212
+ st.write(f"Firestore URL: {url}")
213
+ if file_url:
214
+ st.download_button(label="Download Image", data=requests.get(file_url).content, file_name="image.jpg", mime="image/jpeg")
215
+
216
+
217
+ if st.button("Log Out"):
218
+ st.session_state.user_id = None
219
+ st.rerun()
220
+
221
+
222
+ if __name__ == "__main__":
223
+ main()