Spaces:
Sleeping
Sleeping
Inital commit
Browse files- .gitignore +7 -0
- app.py +88 -0
- functions.py +193 -0
.gitignore
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.idea/
|
2 |
+
__pycache__/
|
3 |
+
|
4 |
+
data.json
|
5 |
+
audio.wav
|
6 |
+
video.mp4
|
7 |
+
infinite_loop.mp4
|
app.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functions import *
|
2 |
+
|
3 |
+
|
4 |
+
scores_parameters, authors = get_main_data()
|
5 |
+
|
6 |
+
with (gr.Blocks() as app):
|
7 |
+
user_id = gr.State('') # id used to find the chat into the database
|
8 |
+
|
9 |
+
with gr.Tab('Test Chats'):
|
10 |
+
with gr.Row() as select_author:
|
11 |
+
author = gr.Dropdown(authors, value=authors[0], label='Author', interactive=True)
|
12 |
+
chat_btn = gr.Button(value='Start chat')
|
13 |
+
|
14 |
+
# ------------------------------------- Chat -------------------------------------------
|
15 |
+
with gr.Row(visible=False) as chatbot:
|
16 |
+
with gr.Column():
|
17 |
+
with gr.Row():
|
18 |
+
video = gr.Video(
|
19 |
+
interactive=False, label='Video', autoplay=True, value='infinite_loop.mp4'
|
20 |
+
)
|
21 |
+
with gr.Row():
|
22 |
+
output_audio = gr.Audio(interactive=False, label='Audio', autoplay=True)
|
23 |
+
with gr.Row():
|
24 |
+
checkbox = gr.Checkbox(label='Get video', info='Remember that this has a cost')
|
25 |
+
|
26 |
+
with gr.Column():
|
27 |
+
with gr.Row():
|
28 |
+
chat = gr.Chatbot(label='Chat')
|
29 |
+
with gr.Row():
|
30 |
+
text = gr.Text(label='Write your question')
|
31 |
+
audio = gr.Audio(sources=['microphone'], type='filepath', label='Tell me your question')
|
32 |
+
with gr.Row():
|
33 |
+
button_text = gr.Button(value='Submit text')
|
34 |
+
button_audio = gr.Button(value='Submit audio')
|
35 |
+
|
36 |
+
# ------------------------------------- Result's tab ---------------------------------------
|
37 |
+
with gr.Tab('Save results'):
|
38 |
+
with gr.Row(visible=False) as scores_row:
|
39 |
+
with gr.Column(scale=75):
|
40 |
+
with gr.Row():
|
41 |
+
scores = [
|
42 |
+
gr.Radio(choices=['Aprobado', 'No aprobado'], label=parameter)
|
43 |
+
for parameter in scores_parameters
|
44 |
+
]
|
45 |
+
|
46 |
+
with gr.Column(scale=25):
|
47 |
+
opinion_box = gr.Textbox(label='Opinion')
|
48 |
+
scores_btn = gr.Button(value='Send scores')
|
49 |
+
scores_box = gr.Textbox(label='Status', interactive=False)
|
50 |
+
|
51 |
+
# -------------------------------------- Actions -----------------------------------------
|
52 |
+
chat_btn.click(
|
53 |
+
make_invisible, None, select_author
|
54 |
+
).then(
|
55 |
+
make_visible, None, [chatbot, scores_row]
|
56 |
+
).then(
|
57 |
+
init_chatbot, [chat], [video, chat, user_id]
|
58 |
+
)
|
59 |
+
|
60 |
+
button_text.click(
|
61 |
+
get_answer_text,
|
62 |
+
[text, chat, user_id, checkbox],
|
63 |
+
[video, output_audio, chat, text]
|
64 |
+
)
|
65 |
+
|
66 |
+
button_audio.click(
|
67 |
+
get_answer_audio,
|
68 |
+
[audio, chat, user_id, checkbox],
|
69 |
+
[video, output_audio, chat, audio]
|
70 |
+
)
|
71 |
+
|
72 |
+
scores_btn.click(
|
73 |
+
save_scores,
|
74 |
+
[author, chat, opinion_box] + scores,
|
75 |
+
scores_box
|
76 |
+
)
|
77 |
+
|
78 |
+
video.end(
|
79 |
+
lambda: 'infinite_loop.mp4', None, video
|
80 |
+
)
|
81 |
+
|
82 |
+
output_audio.stop(
|
83 |
+
lambda: None, None, output_audio
|
84 |
+
)
|
85 |
+
|
86 |
+
|
87 |
+
app.queue()
|
88 |
+
app.launch(debug=True, auth=(os.environ.get('USERNAME'), os.environ.get('PASSWORD')))
|
functions.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import base64
|
4 |
+
import shutil
|
5 |
+
import requests
|
6 |
+
import gradio as gr
|
7 |
+
from datetime import datetime
|
8 |
+
from huggingface_hub import hf_hub_download, HfApi
|
9 |
+
|
10 |
+
API_TOKEN = os.getenv('API_TOKEN')
|
11 |
+
API_URL = os.getenv('API_URL')
|
12 |
+
|
13 |
+
headers = {
|
14 |
+
"Authorization": f"Bearer {API_TOKEN}",
|
15 |
+
"Content-Type": "application/json"
|
16 |
+
}
|
17 |
+
|
18 |
+
|
19 |
+
def get_main_data():
|
20 |
+
"""
|
21 |
+
Returns the scores parameters and authors
|
22 |
+
"""
|
23 |
+
scores_parameters = [
|
24 |
+
'Personalidad', 'Intereses', 'Lenguaje/Estilo', 'Autenticidad', 'Habilidad de conversación',
|
25 |
+
'Marca/Producto', 'Identificación', 'Experiencia de uso', 'Recomendación', 'Conversación orgánica'
|
26 |
+
]
|
27 |
+
authors = ['Sofia', 'Eliza', 'Sindy', 'Carlos', 'Andres', 'Adriana', 'Carolina', 'Valeria']
|
28 |
+
|
29 |
+
return scores_parameters, authors
|
30 |
+
|
31 |
+
|
32 |
+
def make_invisible():
|
33 |
+
"""
|
34 |
+
Makes visible a row
|
35 |
+
"""
|
36 |
+
return gr.Row.update(visible=False)
|
37 |
+
|
38 |
+
|
39 |
+
def make_visible():
|
40 |
+
"""
|
41 |
+
Makes visibles 2 rows
|
42 |
+
"""
|
43 |
+
return gr.Row.update(visible=True), gr.Row.update(visible=True)
|
44 |
+
|
45 |
+
|
46 |
+
def _query(payload):
|
47 |
+
"""
|
48 |
+
Returns the json from a post request. It is done to the BellaAPI
|
49 |
+
"""
|
50 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
51 |
+
return response.json()
|
52 |
+
|
53 |
+
|
54 |
+
def _download_media(url: str, type_media: str) -> None:
|
55 |
+
"""
|
56 |
+
Downloads a video or audio (depending on the type_media) that can be
|
57 |
+
used inside a gr.Video or gr.Audio
|
58 |
+
"""
|
59 |
+
name = 'video.mp4' if type_media == 'video' else 'audio.wav'
|
60 |
+
with requests.get(url, stream=True) as r, open(name, "wb") as f:
|
61 |
+
shutil.copyfileobj(r.raw, f)
|
62 |
+
|
63 |
+
|
64 |
+
def init_chatbot(chatbot: list[tuple[str, str]]):
|
65 |
+
"""
|
66 |
+
Returns a greeting video, with its transcription and the user_id that
|
67 |
+
will be used later in the other requests
|
68 |
+
"""
|
69 |
+
# Call API with the following json
|
70 |
+
inputs = {"inputs": {
|
71 |
+
"date": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
72 |
+
'get_video': True
|
73 |
+
}}
|
74 |
+
output = _query(inputs)
|
75 |
+
|
76 |
+
chatbot.append(('', output['answer']))
|
77 |
+
_download_media(output['link_media'], 'video')
|
78 |
+
|
79 |
+
return 'video.mp4', chatbot, output['user_id']
|
80 |
+
|
81 |
+
|
82 |
+
def get_answer_text(question: str, chatbot: list[tuple[str, str]], user_id: str, checkbox: bool):
|
83 |
+
"""
|
84 |
+
Gets the answer of the chatbot
|
85 |
+
"""
|
86 |
+
# Create json and send it to the API
|
87 |
+
inputs = {'inputs': {
|
88 |
+
'text': question, 'user_id': user_id, 'get_video': checkbox
|
89 |
+
}}
|
90 |
+
output = _query(inputs)
|
91 |
+
return _update_elements(question, chatbot, output, checkbox, '')
|
92 |
+
|
93 |
+
|
94 |
+
def get_answer_audio(audio_path, chatbot: list[tuple[str, str]], user_id: str, checkbox: bool):
|
95 |
+
"""
|
96 |
+
Gets the answer of the chatbot
|
97 |
+
"""
|
98 |
+
# Encode audio data to Base64
|
99 |
+
with open(audio_path, 'rb') as audio_file:
|
100 |
+
audio_data = audio_file.read()
|
101 |
+
encoded_audio = base64.b64encode(audio_data).decode('utf-8')
|
102 |
+
|
103 |
+
# Create json and send it to the API
|
104 |
+
inputs = {'inputs': {
|
105 |
+
'is_audio': True, 'audio': encoded_audio, 'user_id': user_id, 'get_video': checkbox
|
106 |
+
}}
|
107 |
+
output = _query(inputs)
|
108 |
+
|
109 |
+
# Transcription of the audio
|
110 |
+
question = output['question']
|
111 |
+
return _update_elements(question, chatbot, output, checkbox, None)
|
112 |
+
|
113 |
+
|
114 |
+
def _update_elements(question, chatbot, output, checkbox, clean):
|
115 |
+
"""
|
116 |
+
Adds the video, output audio, interaction and cleans the text or audio
|
117 |
+
"""
|
118 |
+
chatbot.append((question, output['answer']))
|
119 |
+
link_media = output['link_media']
|
120 |
+
if checkbox:
|
121 |
+
_download_media(link_media, 'video')
|
122 |
+
return 'video.mp4', None, chatbot, clean
|
123 |
+
|
124 |
+
else:
|
125 |
+
_download_media(link_media, 'audio')
|
126 |
+
return 'infinite_loop.mp4', 'audio.wav', chatbot, clean
|
127 |
+
|
128 |
+
|
129 |
+
def save_scores(author: gr.Dropdown, history: gr.Chatbot, opinion: gr.Textbox, *score_values):
|
130 |
+
"""
|
131 |
+
Saves the scores and chat's info into the json file
|
132 |
+
"""
|
133 |
+
# Get the parameters for each score
|
134 |
+
score_parameters, _ = get_main_data()
|
135 |
+
|
136 |
+
# Get the score of each parameter
|
137 |
+
scores = dict()
|
138 |
+
for parameter, score in zip(score_parameters, score_values):
|
139 |
+
|
140 |
+
# Check the score is a valid value if not, raise Error
|
141 |
+
if score is None:
|
142 |
+
raise gr.Error('Asegúrese de haber seleccionado al menos 1 opción en cada categoría')
|
143 |
+
|
144 |
+
scores[parameter] = score
|
145 |
+
|
146 |
+
# Get all the messages including their reaction
|
147 |
+
chat = []
|
148 |
+
for conversation in history:
|
149 |
+
info = {
|
150 |
+
'message': conversation[0],
|
151 |
+
'answer': conversation[1]
|
152 |
+
}
|
153 |
+
chat.append(info)
|
154 |
+
|
155 |
+
date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
156 |
+
|
157 |
+
# Save the info
|
158 |
+
session = dict(
|
159 |
+
opinion=opinion,
|
160 |
+
scores=scores,
|
161 |
+
chat=chat,
|
162 |
+
author=author,
|
163 |
+
date=date
|
164 |
+
)
|
165 |
+
|
166 |
+
# Open the file, add the new info and save it
|
167 |
+
hf_hub_download(
|
168 |
+
repo_id=os.environ.get('DATASET_NAME'),
|
169 |
+
repo_type='dataset',
|
170 |
+
filename="data.json",
|
171 |
+
token=os.environ.get('HUB_TOKEN'),
|
172 |
+
local_dir="./"
|
173 |
+
)
|
174 |
+
|
175 |
+
with open('data.json', 'r') as infile:
|
176 |
+
past_sessions = json.load(infile)
|
177 |
+
|
178 |
+
# Add the new info
|
179 |
+
past_sessions['sessions'].append(session)
|
180 |
+
with open('data.json', 'w', encoding='utf-8') as outfile:
|
181 |
+
json.dump(past_sessions, outfile, indent=4, ensure_ascii=False)
|
182 |
+
|
183 |
+
# Save the updated file
|
184 |
+
api = HfApi(token=os.environ.get('HUB_TOKEN'))
|
185 |
+
api.upload_file(
|
186 |
+
path_or_fileobj="data.json",
|
187 |
+
path_in_repo="data.json",
|
188 |
+
repo_id=os.environ.get('DATASET_NAME'),
|
189 |
+
repo_type='dataset'
|
190 |
+
)
|
191 |
+
|
192 |
+
# Return a confirmation message
|
193 |
+
return 'Done'
|