-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
226 lines (188 loc) · 8.29 KB
/
Copy pathmain.py
File metadata and controls
226 lines (188 loc) · 8.29 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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
"""
MAGI System 2.0 - Main Application Server
Dash & Flask server managing retro Evangelion UI components, reactive consensus state callbacks,
and REST endpoints for audio transcription.
"""
import os
from dotenv import load_dotenv
from dash_extensions.enrich import Dash, Input, Output, State, Trigger, callback, ALL, MATCH
from dash import dcc
from dash.html import Div, Label, Button
from dash_local_react_components import load_react_component
import ai
load_dotenv()
app = Dash(
__name__,
title='MAGI System',
meta_tags=[
{'name': 'viewport', 'content': 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no'},
{'name': 'theme-color', 'content': '#000000'},
{'name': 'mobile-web-app-capable', 'content': 'yes'},
{'name': 'apple-mobile-web-app-capable', 'content': 'yes'},
{'name': 'apple-mobile-web-app-status-bar-style', 'content': 'black-translucent'}
]
)
Magi = load_react_component(app, 'components', 'magi.js')
WiseMan = load_react_component(app, 'components', 'wise_man.js')
Response = load_react_component(app, 'components', 'response.js')
Modal = load_react_component(app, 'components', 'modal.js')
Header = load_react_component(app, 'components', 'header.js')
Status = load_react_component(app, 'components', 'status.js')
app.layout = Div(
className='system',
children=[
Magi(id='magi', children=[
Header(side='left', title='質 問'),
Header(side='right', title='解 決'),
Status(id='status'),
WiseMan(
id={'type': 'wise-man', 'name': 'melchior'},
name='melchior',
order_number=1,
personality='You are a scientist. Your goal is to further our understanding of the universe and advance our technological progress.'),
WiseMan(
id={'type': 'wise-man', 'name': 'balthasar'},
name='balthasar',
order_number=2,
personality='You are a mother. Your goal is to protect your children and ensure their well-being.'),
WiseMan(
id={'type': 'wise-man', 'name': 'casper'},
name='casper',
order_number=3,
personality='You are a woman. Your goal is to pursue love, dreams and desires.'),
Response(id='response', status='info')
]),
Div(className='input-container', children=[
Label('access code: '),
dcc.Input(id='key', autoComplete='off', type='password', value=os.getenv('OPENROUTER_API_KEY', os.getenv('OPENAI_API_KEY', ''))),
Label('question: '),
Div(className='query-wrapper', children=[
dcc.Input(id='query', type='text', value='', debounce=True, autoComplete='off'),
Button('音 声', id='stt-btn', className='evangelion-stt-btn', n_clicks=0),
Button('発 送', id='send-btn', className='evangelion-send-btn', n_clicks=0),
Button('デバッグ', id='debug-btn', className='evangelion-debug-btn', n_clicks=0),
]),
]),
Div(id='stt-debug-log', className='stt-log-box stt-log-hidden', children='[STT STATUS: LISTO] Pulsa 音 声 para iniciar micrófono'),
Modal(id={'type': 'modal', 'name': 'melchior'}, name='melchior'),
Modal(id={'type': 'modal', 'name': 'balthasar'}, name='balthasar'),
Modal(id={'type': 'modal', 'name': 'casper'}, name='casper'),
dcc.Store(id='question', data={'id': 0, 'query': ''}),
dcc.Store(id='annotated-question', data={'id': 0, 'query': '', 'is_yes_or_no_question': False}),
dcc.Store(id='is_yes_or_no_question', data=False),
dcc.Store(id='question-id', data=0),
])
@callback(
Output('question', 'data'),
Input('query', 'value'),
State('question', 'data'),
prevent_initial_call=True)
def question(query: str, question: dict):
return {'id': question['id'] + 1, 'query': query}
@callback(
Output('annotated-question', 'data'),
Input('question', 'data'),
State('key', 'value'),
prevent_initial_call=True)
def annotated_question(question: dict, key: str):
try:
is_yes_or_no_question = ai.is_yes_or_no_question(question['query'], key)
return {
'id': question['id'],
'query': question['query'],
'is_yes_or_no_question': is_yes_or_no_question,
'error': None
}
except Exception as e:
return {
'id': question['id'],
'query': question['query'],
'is_yes_or_no_question': False,
'error': str(e)
}
@callback(
Output('status', 'extention'),
Input('question', 'data'),
Input('annotated-question', 'data'))
def extention(question: dict, annotated_question: dict):
if question['id'] != annotated_question['id']:
return '????'
return '7312' if annotated_question['is_yes_or_no_question'] else '3023'
@callback(
Output({'type': 'wise-man', 'name': MATCH}, 'answer'),
Input('annotated-question', 'data'),
State({'type': 'wise-man', 'name': MATCH}, 'personality'),
State({'type': 'wise-man', 'name': MATCH}, 'name'),
State('key', 'value'),
prevent_initial_call=True)
def wise_man_answer(question: dict, personality: str, wise_man_name: str, key: str):
if question['error']:
return {'id': question['id'], 'response': question['error'], 'status': 'error'}
try:
answer = ai.get_answer(question['query'], personality, key, wise_man_name=wise_man_name)
if question['is_yes_or_no_question']:
classification = ai.classify_answer(question['query'], personality, answer, key, wise_man_name=wise_man_name)
else:
classification = {'status': 'info', 'conditions': None}
return {'id': question['id'], 'response': answer, 'status': classification['status'], 'conditions': classification['conditions'], 'error': None}
except Exception as e:
return {'id': question['id'], 'response': None, 'status': 'error', 'conditions': 'None', 'error': str(e)}
@callback(
Output({'type': 'wise-man', 'name': MATCH}, 'question_id'),
Input('question', 'data'))
def wise_man_question_id(question: dict):
return question['id']
@callback(
Output('response', 'question_id'),
Input('question', 'data'))
def response_question_id(question: dict):
return question['id']
@callback(
Output('response', 'status'),
Output('response', 'answer_id'),
Input({'type': 'wise-man', 'name': ALL}, 'answer'),
prevent_initial_call=True)
def response_status(answers: list):
answer_id = min([answer['id'] for answer in answers])
status = 'info'
if any([answer['status'] == 'error' for answer in answers]):
status = 'error'
elif any([answer['status'] == 'no' for answer in answers]):
status = 'no'
elif any([answer['status'] == 'conditional' for answer in answers]):
status = 'conditional'
elif all([answer['status'] == 'yes' for answer in answers]):
status = 'yes'
return status, answer_id
@callback(
Output({'type': 'modal', 'name': MATCH}, 'is_open'),
Trigger({'type': 'wise-man', 'name': MATCH}, 'n_clicks'),
prevent_initial_call=True)
def modal_visibility():
return True
@callback(
Output({'type': 'modal', 'name': MATCH}, 'question'),
Output({'type': 'modal', 'name': MATCH}, 'answer'),
Input('question', 'data'),
Input({'type': 'wise-man', 'name': MATCH}, 'answer'))
def modal_content(question: dict, answer: dict):
return question, answer
@app.server.route('/api/transcribe', methods=['POST'])
def api_transcribe():
from flask import request, jsonify
try:
audio_file = request.files.get('audio')
api_key = request.headers.get('X-API-Key') or os.getenv('STT_API_KEY') or os.getenv('OPENAI_API_KEY')
if not audio_file:
return jsonify({'error': 'No audio file provided'}), 400
audio_bytes = audio_file.read()
text = ai.transcribe_audio(
audio_bytes,
key=api_key,
filename=audio_file.filename or 'speech.webm',
content_type=audio_file.mimetype or 'audio/webm')
return jsonify({'text': text})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run_server(debug=True, dev_tools_ui=False)