Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,212 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import requests
|
3 |
+
import cloudinary
|
4 |
+
import cloudinary.uploader
|
5 |
+
from PIL import Image
|
6 |
+
import io
|
7 |
+
from google_auth_oauthlib.flow import InstalledAppFlow
|
8 |
+
from googleapiclient.discovery import build
|
9 |
+
import os
|
10 |
+
|
11 |
+
# Configure Cloudinary with your credentials
|
12 |
+
cloudinary.config(
|
13 |
+
cloud_name="dvuowbmrz",
|
14 |
+
api_key="177664162661619",
|
15 |
+
api_secret="qVMYel17N_C5QUUUuBIuatB5tq0"
|
16 |
+
)
|
17 |
+
|
18 |
+
# Set up OAuth2 client details
|
19 |
+
CLIENT_SECRET_FILE = 'client_secret.json'
|
20 |
+
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'] # Adjust scopes as needed
|
21 |
+
|
22 |
+
# Set up Streamlit app
|
23 |
+
#st.title("Google Authentication Demo")
|
24 |
+
|
25 |
+
# Check if the user is authenticated
|
26 |
+
if 'credentials' not in st.session_state:
|
27 |
+
#st.write("WELCOME")
|
28 |
+
flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
|
29 |
+
credentials = flow.run_local_server(port=8501, authorization_prompt_message='')
|
30 |
+
|
31 |
+
# Save credentials to a file for future use (optional)
|
32 |
+
with open('token.json', 'w') as token_file:
|
33 |
+
token_file.write(credentials.to_json())
|
34 |
+
|
35 |
+
st.session_state.credentials = credentials
|
36 |
+
st.success("Authentication successful. You can now use the app.")
|
37 |
+
|
38 |
+
# Use authenticated credentials to interact with Google API
|
39 |
+
credentials = st.session_state.credentials
|
40 |
+
service = build('drive', 'v3', credentials=credentials)
|
41 |
+
|
42 |
+
# Fetch user's name from Google API
|
43 |
+
try:
|
44 |
+
user_info = service.about().get(fields="user").execute()
|
45 |
+
user_name = user_info["user"]["displayName"]
|
46 |
+
#st.header("Google Profile Information")
|
47 |
+
st.markdown(f"<p style='font-size: 24px;'><strong>Userame: {user_name.upper()}</strong></p>", unsafe_allow_html=True)
|
48 |
+
except Exception as e:
|
49 |
+
st.error(f"Error fetching user profile: {str(e)}")
|
50 |
+
|
51 |
+
# Your app's functionality goes here
|
52 |
+
# # Display Google Drive contents
|
53 |
+
# st.header("Google Drive Contents")
|
54 |
+
# results = service.files().list(pageSize=10).execute()
|
55 |
+
# files = results.get('files', [])
|
56 |
+
# if not files:
|
57 |
+
# st.write('No files found in Google Drive.')
|
58 |
+
# else:
|
59 |
+
# st.write('Files in Google Drive:')
|
60 |
+
# for file in files:
|
61 |
+
# st.write(f"- {file['name']} ({file['mimeType']})")
|
62 |
+
|
63 |
+
# Logout button
|
64 |
+
if st.button("Logout"):
|
65 |
+
del st.session_state.credentials
|
66 |
+
os.remove("token_dir/token.json") # Remove the token file
|
67 |
+
|
68 |
+
|
69 |
+
|
70 |
+
# Set up Hugging Face API endpoint
|
71 |
+
API_URL = "https://api-inference.huggingface.co/models/CompVis/stable-diffusion-v1-4"
|
72 |
+
headers = {"Authorization": "Bearer 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"}
|
73 |
+
|
74 |
+
|
75 |
+
def query_model_with_image(image_description):
|
76 |
+
payload = {
|
77 |
+
"inputs": image_description
|
78 |
+
}
|
79 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
80 |
+
image_bytes = response.content
|
81 |
+
|
82 |
+
image = Image.open(io.BytesIO(image_bytes))
|
83 |
+
return image
|
84 |
+
|
85 |
+
def upload_to_cloudinary(image, prompt_text):
|
86 |
+
image_data = io.BytesIO()
|
87 |
+
image.save(image_data, format="JPEG")
|
88 |
+
image_data.seek(0)
|
89 |
+
|
90 |
+
upload_result = cloudinary.uploader.upload(
|
91 |
+
image_data,
|
92 |
+
folder="compvis_app",
|
93 |
+
public_id=prompt_text
|
94 |
+
)
|
95 |
+
return upload_result["secure_url"]
|
96 |
+
|
97 |
+
|
98 |
+
def fetch_latest_images_from_cloudinary(num_images=9):
|
99 |
+
# Use the Cloudinary Admin API to list resources
|
100 |
+
url = f"https://api.cloudinary.com/v1_1/{cloudinary.config().cloud_name}/resources/image"
|
101 |
+
params = {
|
102 |
+
"max_results": num_images,
|
103 |
+
"type": "upload"
|
104 |
+
}
|
105 |
+
response = requests.get(url, params=params, auth=(cloudinary.config().api_key, cloudinary.config().api_secret))
|
106 |
+
|
107 |
+
if response.status_code == 200:
|
108 |
+
images = response.json()["resources"]
|
109 |
+
else:
|
110 |
+
images = []
|
111 |
+
|
112 |
+
return images
|
113 |
+
|
114 |
+
# Streamlit app
|
115 |
+
st.markdown("""<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">""", unsafe_allow_html=True)
|
116 |
+
|
117 |
+
st.title("Text to Image Generator")
|
118 |
+
|
119 |
+
image_description = st.text_input("Enter the image description")
|
120 |
+
|
121 |
+
if st.button("Generate Image"):
|
122 |
+
processed_image = query_model_with_image(image_description)
|
123 |
+
st.image(processed_image, use_column_width=True, output_format="JPEG") # Use use_column_width=True
|
124 |
+
st.session_state.processed_image = processed_image
|
125 |
+
st.session_state.image_description = image_description
|
126 |
+
st.write("Image generated.")
|
127 |
+
|
128 |
+
if st.button("Upload"):
|
129 |
+
if 'processed_image' in st.session_state:
|
130 |
+
uploaded_url = upload_to_cloudinary(st.session_state.processed_image, st.session_state.image_description)
|
131 |
+
st.write("Image uploaded to Cloudinary. Prompt Text:", st.session_state.image_description)
|
132 |
+
st.write("Image URL on Cloudinary:", uploaded_url)
|
133 |
+
else:
|
134 |
+
st.write("Generate an image first before uploading.")
|
135 |
+
|
136 |
+
# Fetch and display the latest images from Cloudinary
|
137 |
+
st.header("Latest Images created")
|
138 |
+
|
139 |
+
# Use the 'fetch_latest_images_from_cloudinary' function to get the latest images
|
140 |
+
latest_images = fetch_latest_images_from_cloudinary()
|
141 |
+
|
142 |
+
# Define the number of columns in the grid
|
143 |
+
num_columns = 3 # You can adjust this number as needed
|
144 |
+
|
145 |
+
# Calculate the width for each column
|
146 |
+
column_width = f"calc(33.33% - {10}px)" # Adjust the width and margin as needed
|
147 |
+
|
148 |
+
# Add CSS styling for the grid and rounded images
|
149 |
+
st.markdown(
|
150 |
+
f"""
|
151 |
+
<style>
|
152 |
+
.responsive-grid {{
|
153 |
+
display: flex;
|
154 |
+
flex-wrap: wrap;
|
155 |
+
justify-content: space-between;
|
156 |
+
}}
|
157 |
+
.responsive-grid-item {{
|
158 |
+
width: {column_width};
|
159 |
+
margin: 10px;
|
160 |
+
box-sizing: border-box;
|
161 |
+
text-align: center;
|
162 |
+
position: relative;
|
163 |
+
}}
|
164 |
+
.image-caption {{
|
165 |
+
font-weight: bold;
|
166 |
+
}}
|
167 |
+
.rounded-image {{
|
168 |
+
border-radius: 15px; # Adjust the radius as needed for more or less roundness
|
169 |
+
overflow: hidden;
|
170 |
+
}}
|
171 |
+
.download-button {{
|
172 |
+
background-color: black; # Set button color to black
|
173 |
+
color: white;
|
174 |
+
padding: 5px 10px;
|
175 |
+
border-radius: 5px;
|
176 |
+
text-decoration: none;
|
177 |
+
display: inline-block;
|
178 |
+
position: absolute;
|
179 |
+
top: 10px; # Adjust top value for vertical positioning
|
180 |
+
right: 10px; # Adjust right value for horizontal positioning
|
181 |
+
}}
|
182 |
+
</style>
|
183 |
+
""",
|
184 |
+
unsafe_allow_html=True,
|
185 |
+
)
|
186 |
+
|
187 |
+
# Create the responsive grid layout
|
188 |
+
st.markdown('<div class="responsive-grid">', unsafe_allow_html=True)
|
189 |
+
|
190 |
+
for i, image in enumerate(latest_images):
|
191 |
+
image_url = image.get('secure_url', '') # Get the image URL
|
192 |
+
public_id = image.get('public_id', '') # Get the full public_id
|
193 |
+
|
194 |
+
# Extract just the filename (without the folder)
|
195 |
+
filename = public_id.split('/')[-1]
|
196 |
+
|
197 |
+
# Add some spacing around the image and its name
|
198 |
+
st.markdown(f'<div class="responsive-grid-item">', unsafe_allow_html=True)
|
199 |
+
st.markdown(f'<p class="image-caption">{filename}</p>', unsafe_allow_html=True)
|
200 |
+
|
201 |
+
# Add rounded corners to the image using HTML
|
202 |
+
st.markdown(f'<img src="{image_url}" class="rounded-image" width="{int(1.25 * 300)}">', unsafe_allow_html=True)
|
203 |
+
|
204 |
+
# Add an arrow icon instead of "Download" button with black color
|
205 |
+
download_link = f'<a href="{image_url}" class="download-button" download="{filename}">↓</a>'
|
206 |
+
st.markdown(download_link, unsafe_allow_html=True)
|
207 |
+
|
208 |
+
st.write("") # Add empty spaces for separation
|
209 |
+
st.markdown('</div>', unsafe_allow_html=True)
|
210 |
+
|
211 |
+
# Close the responsive grid layout
|
212 |
+
st.markdown('</div>', unsafe_allow_html=True)
|