-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfrontend.py
More file actions
193 lines (153 loc) Β· 6.71 KB
/
frontend.py
File metadata and controls
193 lines (153 loc) Β· 6.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
import streamlit as st
import requests
import base64
import urllib.parse
import time
st.set_page_config(page_title="PixelFlow", layout="wide")
API_URL = "https://simple-social-api-5efn.onrender.com"
# Initialize session state
if 'token' not in st.session_state:
st.session_state.token = None
if 'user' not in st.session_state:
st.session_state.user = None
def get_headers():
"""Get authorization headers with token"""
if st.session_state.token:
return {"Authorization": f"Bearer {st.session_state.token}"}
return {}
def login_page():
st.title("Welcome to PixelFlow")
# Simple form with two buttons
email = st.text_input("Email:")
password = st.text_input("Password:", type="password")
if email and password:
col1, col2 = st.columns(2)
with col1:
if st.button("Login", type="primary", use_container_width=True):
# Login using FastAPI Users JWT endpoint
login_data = {"username": email, "password": password}
response = requests.post(f"{API_URL}/auth/jwt/login", data=login_data)
if response.status_code == 200:
token_data = response.json()
st.session_state.token = token_data["access_token"]
# Get user info
user_response = requests.get(f"{API_URL}/users/me", headers=get_headers())
if user_response.status_code == 200:
st.session_state.user = user_response.json()
st.rerun()
else:
st.error("Failed to get user info")
else:
st.error("Invalid email or password!")
with col2:
if st.button("Sign Up", type="secondary", use_container_width=True):
# Register using FastAPI Users
signup_data = {"email": email, "password": password}
response = requests.post(f"{API_URL}/auth/register", json=signup_data)
if response.status_code == 201:
st.success("Account created! Click Login now.")
else:
error_detail = response.json().get("detail", "Registration failed")
st.error(f"Registration failed: {error_detail}")
else:
st.info("Enter your email and password above")
def upload_page():
# π CSS to hide the "Limit 200MB" text
st.markdown("""
<style>
[data-testid="stFileUploader"] section > input + div {
display: none;
}
/* Alternative selector if the above doesn't catch it */
[data-testid="stFileUploader"] small {
display: none;
}
</style>""", unsafe_allow_html=True)
st.title("πΈ Share Something")
uploaded_file = st.file_uploader("Choose media", type=['png', 'jpg', 'jpeg', 'mp4', 'avi', 'mov', 'mkv', 'webm'])
caption = st.text_area("Caption:", placeholder="What's on your mind?")
if uploaded_file and st.button("Share", type="primary"):
with st.spinner("Uploading..."):
files = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
data = {"caption": caption}
response = requests.post(f"{API_URL}/upload", files=files, data=data, headers=get_headers())
if response.status_code == 200:
st.success("Posted!")
time.sleep(2)
st.rerun()
else:
st.error("Upload failed!")
def encode_text_for_overlay(text):
"""Encode text for ImageKit overlay - base64 then URL encode"""
if not text:
return ""
# Base64 encode the text
base64_text = base64.b64encode(text.encode('utf-8')).decode('utf-8')
# URL encode the result
return urllib.parse.quote(base64_text)
def create_transformed_url(original_url, transformation_params, caption=None):
if caption:
encoded_caption = encode_text_for_overlay(caption)
# Add text overlay at bottom with semi-transparent background
text_overlay = f"l-text,ie-{encoded_caption},ly-N20,lx-20,fs-100,co-white,bg-000000A0,l-end"
transformation_params = text_overlay
if not transformation_params:
return original_url
parts = original_url.split("/")
imagekit_id = parts[3]
file_path = "/".join(parts[4:])
base_url = "/".join(parts[:4])
return f"{base_url}/tr:{transformation_params}/{file_path}"
def feed_page():
st.title("π Feed")
response = requests.get(f"{API_URL}/feed", headers=get_headers())
if response.status_code == 200:
posts = response.json()["posts"]
if not posts:
st.info("No posts yet! Be the first to share something.")
return
for post in posts:
st.markdown("---")
# Header with user, date, and delete button (if owner)
col1, col2 = st.columns([4, 1])
with col1:
st.markdown(f"**{post['email']}** β’ {post['created_at'][:10]}")
with col2:
if post.get('is_owner', False):
if st.button("ποΈ", key=f"delete_{post['id']}", help="Delete post"):
# Delete the post
response = requests.delete(f"{API_URL}/posts/{post['id']}", headers=get_headers())
if response.status_code == 200:
st.success("Post deleted!")
st.rerun()
else:
st.error("Failed to delete post!")
# Uniform media display with caption overlay
caption = post.get('caption', '')
if post['file_type'] == 'image':
uniform_url = create_transformed_url(post['url'], "", caption)
st.image(uniform_url, width=300)
else:
# For videos: specify only height to maintain aspect ratio + caption overlay
uniform_video_url = create_transformed_url(post['url'], "w-400,h-200,cm-pad_resize,bg-blurred")
st.video(uniform_video_url, width=300)
st.caption(caption)
st.markdown("") # Space between posts
else:
st.error("Failed to load feed")
# Main app logic
if st.session_state.user is None:
login_page()
else:
# Sidebar navigation
st.sidebar.title(f"π Hi {st.session_state.user['email']}!")
if st.sidebar.button("Logout"):
st.session_state.user = None
st.session_state.token = None
st.rerun()
st.sidebar.markdown("---")
page = st.sidebar.radio("Navigate:", ["π Feed", "πΈ Upload"])
if page == "π Feed":
feed_page()
else:
upload_page()