anhdt-dsai-02 commited on
Commit
a3ea924
·
verified ·
1 Parent(s): 0ee88ed

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +172 -0
app.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from collections import defaultdict
3
+ import random
4
+ import pandas as pd
5
+ import os
6
+ import cloudinary
7
+ import cloudinary.uploader
8
+ from cloudinary.utils import cloudinary_url
9
+ import io
10
+ import time
11
+ import requests
12
+
13
+
14
+
15
+ # Configuration
16
+ cloudinary.config(
17
+ cloud_name = "dnzirogvb",
18
+ api_key = os.environ["api_key"] ,
19
+ api_secret = os.environ["api_secret"] ,
20
+ secure=True
21
+ )
22
+
23
+ from datetime import datetime
24
+ import pytz
25
+
26
+ # Define the GMT+7 timezone
27
+ gmt_plus7 = pytz.timezone('Etc/GMT-7') # 'Etc/GMT-7' represents GMT+7
28
+
29
+
30
+
31
+ def authenticate(user_id):
32
+
33
+ url = "https://intern-api.imtaedu.com/api/subnets/1/authenticate"
34
+ headers = {
35
+ "Content-Type": "application/json",
36
+ "Accept": "application/json",
37
+ "X-Public-Api-Key": os.environ['ADMIN']
38
+ }
39
+ payload = { "token": user_id }
40
+ response = requests.post(url, json=payload, headers=headers)
41
+
42
+ return response.status_code == 200
43
+
44
+ def login(username, state, package):
45
+ state[0] = username
46
+ #package[0] = get_next_package(user_id=username)
47
+
48
+ #temp
49
+ gr.Info("Login successfully. Welcome!")
50
+ return f"Welcome, {username}!", gr.update(visible=False), gr.update(visible=True)
51
+ #temp
52
+
53
+ # Authenticate user
54
+ if authenticate(username):
55
+ #user_sessions[username] = True
56
+ gr.Info("Login successfully. Welcome!")
57
+ return gr.update(visible=False), gr.update(visible=True), get_next_en_text(username), package[0][2]
58
+ else:
59
+ raise gr.Error("Username or Password is invalid! Try again!")
60
+ return "Invalid username or password.", gr.update(visible=True), gr.update(visible=False), "", ""
61
+
62
+ def logout(username):
63
+ # Log out user and reset session
64
+ if username in user_sessions:
65
+ del user_sessions[username]
66
+ gr.Warning("You need to login to access this subnet and do task ⛔️!", duration=5)
67
+ return "Logged out. Please log in again.", gr.update(visible=True), gr.update(visible=False)
68
+
69
+ def get_image_bytes(image):
70
+ if image is None:
71
+ return "No image uploaded!"
72
+
73
+ # Convert the image to bytes
74
+ img_byte_arr = io.BytesIO()
75
+ image.save(img_byte_arr, format='PNG') # Save as PNG or desired format
76
+ img_bytes = img_byte_arr.getvalue()
77
+
78
+ return img_bytes
79
+
80
+
81
+ # Define a function to handle image and text caption
82
+ def process_image_and_caption(username_input, image, caption):
83
+ if image is None:
84
+ gr.Warning("No image uploaded!", duration=5)
85
+ return "No image uploaded!"
86
+ if caption is None:
87
+ gr.Warning("No caption uploaded!", duration=5)
88
+ return "No caption uploaded!"
89
+ # Get current time in GMT+7
90
+ current_time = datetime.now(gmt_plus7)
91
+
92
+ # Print the time
93
+ time = current_time.strftime('-%Y-%m-%d-%H-%M-%S')
94
+ name = username_input + time
95
+ # Upload an image
96
+ img_bytes = get_image_bytes(image)
97
+ upload_image_result = cloudinary.uploader.upload(img_bytes, public_id = name, asset_folder = "image_for_captioning")
98
+
99
+
100
+ # Upload caption
101
+ # Convert to bytes
102
+ caption_bytes = caption.encode('utf-8')
103
+ # Create a byte array buffer (like a binary file stream)
104
+ byte_buffer = io.BytesIO(caption_bytes)
105
+ upload_caption_result = cloudinary.uploader.upload(byte_buffer, public_id = name, asset_folder = "caption", resource_type = "raw")
106
+ send_score(username_input, 0.1)
107
+ gr.Info("Submit successfully")
108
+ return f'You just upload an Image with Caption: "{caption}" \nIntime {time}', None, None
109
+
110
+ def send_score(user_id, score):
111
+ max_retries = 10
112
+ while max_retries > 0:
113
+ url = "https://intern-api.imtaedu.com/api/subnets/2/grade"
114
+
115
+ payload = {
116
+ "token": user_id,
117
+ "comment": "Good job!",
118
+ "grade": score,
119
+ "submitted_at": "2021-01-01 00:00:00",
120
+ "graded_at": "2021-01-01 00:00:00"
121
+ }
122
+ headers = {
123
+ "Content-Type": "application/json",
124
+ "Accept": "application/json",
125
+ "X-Public-Api-Key": os.environ['ADMIN']
126
+ }
127
+
128
+ response = requests.post(url, json=payload, headers=headers)
129
+ if response.status_code == 200:
130
+ return True
131
+ print(response)
132
+ max_retries -= 1
133
+ return False
134
+
135
+ # Define the Gradio interface
136
+ with gr.Blocks() as demo:
137
+ state = gr.State([None])
138
+ package = gr.State([None])
139
+ # Login section
140
+ with gr.Column(visible=True) as login_section:
141
+ username_input = gr.Textbox(placeholder="Enter your token", label="Token ID", type="password")
142
+ login_button = gr.Button("Login")
143
+ login_output = gr.Textbox(label="Login Status", interactive=False)
144
+
145
+ # Upload section (initially hidden)
146
+ with gr.Column(visible=False) as upload_section:
147
+ with gr.Row():
148
+ image_input = gr.Image(type="pil", label="Upload Image")
149
+ caption_input = gr.Textbox(label="Enter Caption")
150
+
151
+ submit_button = gr.Button("Submit")
152
+ output = gr.Textbox(label="Output")
153
+
154
+ # Button functions
155
+
156
+
157
+ submit_button.click(
158
+ process_image_and_caption,
159
+ inputs=[username_input, image_input, caption_input],
160
+ outputs=[output, image_input, caption_input]
161
+ )
162
+
163
+ username_input.submit(
164
+ login, inputs=[username_input, state, package], outputs=[login_output, login_section, upload_section] #, translation_section, en_input, vi_input]
165
+ )
166
+
167
+ login_button.click(
168
+ login, inputs=[username_input, state, package], outputs=[login_output, login_section, upload_section] #, translation_section, en_input, vi_input]
169
+ )
170
+
171
+
172
+ demo.launch(debug=True)