MANIKANDAN A commited on
Commit
8b9bde5
·
1 Parent(s): ed2b9aa

Delete orginal.py

Browse files
Files changed (1) hide show
  1. orginal.py +0 -200
orginal.py DELETED
@@ -1,200 +0,0 @@
1
- import io
2
- import os
3
- import streamlit as st
4
- import requests
5
- from PIL import Image
6
- from model import get_caption_model, generate_caption
7
- from googletrans import Translator
8
- import sqlite3
9
-
10
- # Initialize Streamlit app
11
- st.set_page_config(page_title="Image Caption Generator", layout="wide")
12
-
13
- translator = Translator()
14
-
15
- @st.cache_resource
16
- def get_model():
17
- return get_caption_model()
18
-
19
- caption_model = get_model()
20
-
21
- # Constants
22
- SIGNUP_SUCCESS_MSG = "Signup successful! You can now login."
23
- SIGNUP_ERROR_EXISTING_USER = "Username already exists. Please choose a different username."
24
- LOGIN_SUCCESS_MSG = "Login successful!"
25
- LOGIN_ERROR_INVALID_CREDENTIALS = "Login failed. Invalid username or password."
26
-
27
- # Define CSS styles
28
- heading_style = "font-size: 24px; font-weight: bold; text-align: center;"
29
- input_style = "margin-top: 10px; padding: 5px; width: 100%;"
30
-
31
- # Function to create the SQLite table if it doesn't exist
32
- @st.cache_resource
33
- def create_table():
34
- with sqlite3.connect("login.db") as conn:
35
- cursor = conn.cursor()
36
- cursor.execute('''
37
- CREATE TABLE IF NOT EXISTS users (
38
- id INTEGER PRIMARY KEY AUTOINCREMENT,
39
- username TEXT NOT NULL UNIQUE,
40
- password TEXT NOT NULL,
41
- email TEXT NOT NULL,
42
- role TEXT NOT NULL
43
- )
44
- ''')
45
-
46
- # Function for signup section
47
- def signup_section():
48
-
49
- st.markdown(f"<p style='{heading_style}'>Signup</p>", unsafe_allow_html=True)
50
-
51
- new_username = st.text_input("New Username", key="new_username", help="Choose a unique username")
52
- new_password = st.text_input("New Password", type="password", key="new_password", help="Password should be at least 8 characters long")
53
- new_email = st.text_input("Email", key="new_email", help="Enter a valid email address")
54
-
55
- if st.button("Signup"):
56
- if not new_username or not new_password or not new_email:
57
- st.error("All fields are required for signup.")
58
- return
59
-
60
- role = "user"
61
-
62
- try:
63
- with sqlite3.connect("login.db") as conn:
64
- cursor = conn.cursor()
65
- cursor.execute("INSERT INTO users (username, password, email, role) VALUES (?, ?, ?, ?)",
66
- (new_username, new_password, new_email, role))
67
- st.success(SIGNUP_SUCCESS_MSG)
68
- st.balloons()
69
- except sqlite3.IntegrityError:
70
- st.error(SIGNUP_ERROR_EXISTING_USER)
71
-
72
- # Function for login section
73
- def login_section():
74
-
75
- st.markdown(f"<p style='{heading_style}'>Login</p>", unsafe_allow_html=True)
76
- username = st.text_input("Username", key="login_username", help="Enter your username")
77
- password = st.text_input("Password", type="password", key="login_password",help="Enter your password")
78
-
79
- if st.button("Login"):
80
- if not username or not password:
81
- st.error("Username and password are required for login.")
82
- return
83
-
84
- try:
85
- with sqlite3.connect("login.db") as conn:
86
- cursor = conn.cursor()
87
- cursor.execute("SELECT * FROM users WHERE username = ?", (username,))
88
- user = cursor.fetchone()
89
-
90
- if user and user[2] == password:
91
- st.success(LOGIN_SUCCESS_MSG)
92
- st.write(f"You are logged in as: {user[1]}")
93
- st.session_state.username = username
94
- st.session_state.selected_tab = "Generate Caption"
95
- st.balloons()
96
- else:
97
- st.error(LOGIN_ERROR_INVALID_CREDENTIALS)
98
- except sqlite3.OperationalError as e:
99
- st.error(f"An error occurred while trying to log in: {e}")
100
-
101
-
102
-
103
- def predict(cap_col):
104
- captions = []
105
- pred_caption = generate_caption('tmp.jpg', caption_model)
106
-
107
- cap_col.markdown('#### Predicted Captions:')
108
- captions.append(pred_caption)
109
-
110
- for _ in range(4):
111
- pred_caption = generate_caption('tmp.jpg', caption_model, add_noise=True)
112
- if pred_caption not in captions:
113
- captions.append(pred_caption)
114
-
115
- cap_col.markdown('<div class="caption-container">', unsafe_allow_html=True)
116
- for c in captions:
117
- cap_col.markdown(f'<div class="cap-line" style="color: black; background-color: light grey; padding: 5px; margin-bottom: 5px; font-family: \'Palatino Linotype\', \'Book Antiqua\', Palatino, serif;">{c}</div>', unsafe_allow_html=True)
118
- cap_col.markdown('</div>', unsafe_allow_html=True)
119
-
120
-
121
-
122
- def main():
123
- # Create the database table if it doesn't exist
124
- create_table()
125
-
126
- # Define the navigation tabs
127
- tabs = ["Signup", "Login", "Generate Caption"]
128
-
129
- # Select the active tab based on user input
130
- selected_tab = st.sidebar.selectbox("Navigation", tabs)
131
-
132
- # Route to the appropriate section based on the selected tab
133
- if selected_tab == "Signup":
134
- signup_section()
135
- elif selected_tab == "Login":
136
- login_section()
137
- elif selected_tab == "Generate Caption":
138
- # Check if a user is logged in before accessing the caption generation feature
139
- if hasattr(st.session_state, "username"):
140
- st.markdown(f"<p style='{heading_style}'>Generate Caption</p>", unsafe_allow_html=True)
141
- st.markdown("Upload an image to generate a caption:")
142
-
143
- with st.sidebar:
144
- st.title("Options")
145
- selected_languages = st.multiselect("Select languages for translation:", ['en', 'ta', 'hi', 'zh-cn', 'es', 'fr', 'de', 'it', 'ja'])
146
- img_url = st.text_input("Enter Image URL:")
147
- img_upload = st.file_uploader("Upload Image:", type=['jpg', 'png', 'jpeg'])
148
-
149
- col1, col2 = st.columns(2)
150
- if img_url or img_upload:
151
- if img_url:
152
- img = Image.open(requests.get(img_url, stream=True).raw)
153
- else:
154
- img = Image.open(img_upload)
155
-
156
- img = img.convert('RGB')
157
- col1.image(img, caption="Input Image", use_column_width=True)
158
- img.save('tmp.jpg')
159
- predict(col2)
160
-
161
- if generated_caption:
162
- col2.markdown('<div style="margin-top: 15px; padding: 10px; background-color: #e6f7ff; border-radius: 5px;">' + generated_caption + '</div>', unsafe_allow_html=True)
163
- else:
164
- col2.markdown('<div style="margin-top: 15px; padding: 10px; background-color: #e6f7ff; border-radius: 5px;">Caption generation failed.</div>', unsafe_allow_html=True)
165
-
166
- if generated_caption:
167
- st.markdown("<p style='font-size: 24px; font-weight: bold; margin-bottom: 20px;'>Generated Caption:</p>", unsafe_allow_html=True)
168
- st.write(generated_caption)
169
-
170
- if "en" in selected_languages:
171
- st.markdown("<p style='font-size: 24px; font-weight: bold; margin-bottom: 20px;'>Edit Caption:</p>", unsafe_allow_html=True)
172
- edited_caption = st.text_area("Edit the caption", value=generated_caption)
173
-
174
- if edited_caption:
175
- st.markdown("<p style='font-size: 24px; font-weight: bold; margin-bottom: 20px;'>Edited Caption:</p>", unsafe_allow_html=True)
176
- st.write(edited_caption)
177
-
178
- for lang in selected_languages:
179
- if lang != "en":
180
- translated_caption = translator.translate(edited_caption, src="en", dest=lang)
181
- st.markdown(f"<p style='font-size: 24px; font-weight: bold; margin-bottom: 20px;'>{lang.upper()} Translation:</p>", unsafe_allow_html=True)
182
- st.write(translated_caption.text)
183
-
184
- username = st.session_state.username
185
- update_caption(username, edited_caption) # Update the caption in the database
186
-
187
- st.success("Caption updated and saved successfully!")
188
- else:
189
- st.info("Caption editing is only available for English language captions.")
190
- else:
191
- st.write("Please login to access this feature.")
192
-
193
- # Remove temporary image file
194
- if img_url or img_upload:
195
- os.remove('tmp.jpg')
196
-
197
- if __name__ == "__main__":
198
- main()
199
-
200
-