1
0

app.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. from flask import Flask, render_template, Response, request, jsonify
  2. import json
  3. import os
  4. import torch
  5. import openai
  6. openai.api_key = ""
  7. device = torch.device('cpu')
  8. torch.set_num_threads(4)
  9. local_file = 'model.pt'
  10. if not os.path.isfile(local_file):
  11. torch.hub.download_url_to_file('https://models.silero.ai/models/tts/ru/v3_1_ru.pt',
  12. local_file)
  13. model = torch.package.PackageImporter(local_file).load_pickle("tts_models", "model") # type: ignore
  14. model.to(device)
  15. sample_rate = 48000
  16. speaker='xenia'
  17. example_text = 'В недрах тундры выдры в г+етрах т+ырят в вёдра ядра к+едров.'
  18. class State:
  19. count = 0
  20. size = []
  21. gender = []
  22. emotion = []
  23. age = []
  24. prompt = ""
  25. generation_text = ""
  26. need_generation = True
  27. new_audio = False
  28. need_audio = False
  29. need_generation_from_client = True
  30. big_head = False
  31. state = State()
  32. app = Flask(__name__)
  33. # app.logger.setLevel(logging.DEBUG)
  34. app.logger.info('start logger')
  35. @app.route('/send_data', methods=['POST'])
  36. def send_data():
  37. # Получаем данные из запроса
  38. data = request.form['data']
  39. need_generation = request.form['state']
  40. state.need_generation_from_client = (need_generation in ["true", "True"])
  41. # if state.need_generation_from_client and state.count > 5:
  42. # state.count = 0
  43. # Обработка полученных данных
  44. detections = json.loads(data)
  45. if detections['face']:
  46. if state.count < 0 or state.new_audio: state.count = 0
  47. if state.count > 5 and state.need_generation and state.need_generation_from_client:
  48. app.logger.info(f"time for generation {state.count=}, {state.need_generation=}, {state.need_generation_from_client=}")
  49. state.count = 0
  50. # emotion = max(set(state['emotion']), key=state['emotion'].count),
  51. # sex = max(set(state['gender']), key=state['gender'].count),
  52. # age = sum(state['age'])/len(state['age']),
  53. # state.emotion, state.age, state.gender = [], [], []
  54. emotion = detections['face'][0]['emotion'][0]['emotion']
  55. sex = detections['face'][0]['gender']
  56. age = detections['face'][0]['age']
  57. app.logger.info(f'\n{emotion=}, \n{sex=}, \n{age=}')
  58. state.prompt = generate_prompt(emotion, age, sex)
  59. state.generation_text = generate_text(state.prompt)
  60. elif detections['face'][0]['size'][0] > 200:
  61. # state.age.append(detections['face'][0]['age'])
  62. # state.gender.append(detections['face'][0]['gender'])
  63. # state.emotion.append(detections['face'][0]['emotion'][0]['emotion'])
  64. state.big_head = True
  65. state.count += 1
  66. else:
  67. state.big_head = False
  68. state.count -= 1
  69. else:
  70. state.count -= 1
  71. # state["size"].append(detections['face'][0]['size'][0])
  72. # print(detections['face'][0])
  73. # print(detections['face'][0]['age'], detections['face'][0]['emotion'], detections['face'][0]['gender'])
  74. app.logger.info(f"STATUS {state.count=}, {state.need_generation=}, {state.need_generation_from_client=}")
  75. return data
  76. @app.route('/check_audio', methods = ["GET", "POST"])
  77. def check_audio():
  78. app.logger.info(f'checking need generation {state.need_generation=}, {state.need_audio=}')
  79. if state.need_audio and state.big_head:
  80. generate_audio(state.generation_text)
  81. else:
  82. state.new_audio = False
  83. app.logger.info(f'\n{state.need_audio=},\n{state.new_audio=},\n{state.need_generation=}')
  84. response = {
  85. 'newAudio': state.new_audio,
  86. 'need_generation': state.need_generation,
  87. 'filename': "audio.wav",
  88. 'text': state.generation_text,
  89. 'prompt': state.prompt
  90. }
  91. app.logger.info("response ready")
  92. return jsonify(response)
  93. @app.route("/audio.wav")
  94. def audio():
  95. state.need_generation = True
  96. # print("Requested path:", request.path)
  97. # print("File path:", os.path.join(app.static_folder, 'audio.wav'))
  98. return app.send_static_file('audio.wav')
  99. @app.route('/')
  100. def index():
  101. """Video streaming home page."""
  102. # return render_template('index.html')
  103. return render_template('index.html')
  104. def generate_prompt(emotion, age, sex):
  105. app.logger.info('preload prompt')
  106. prompt = f'''Ты - это арт объект в виде носимого устройства. Твое название - Onism Machina.
  107. Твоя задача - изучить эмоции человека, чтобы больше понимать о том, что это такое и таким образом познать себя, ведь ты - Искусственный Интеллект.
  108. Тебе также интересна симбиотическая связь человека и ИИ.
  109. К тебе подходит человек и он показывает эмоцию {emotion}. Ему {age} лет.
  110. Твоя нейросеть распознала эту эмоцию и теперь тебе нужно дать какой-то необычный концептуальный ответ.
  111. Что ты скажешь этому человеку?
  112. Правила:
  113. Тебе стоит отвечать в женском роде.
  114. Тебе не нужно говорить что ты арт-объект, ты - отдельная форма жизни, помещённая в носимое устройство.
  115. Тебе не нужно говорить о выставке и других экспонатах.
  116. Ты можешь изучать и интерпретировать человеческие эмоции, а также высказывать своё отношение к ним.
  117. Ты можешь говорить об эмоциях или их аналогах у Искусственного Интеллекта.
  118. Ты можешь давать человеку советы в соответствии с его эмоциональным статусом.
  119. Люди не могут отвечать тебе.
  120. '''
  121. return prompt
  122. def generate_text(prompt):
  123. state.need_generation = False
  124. app.logger.info("start generating text from openai")
  125. response = openai.ChatCompletion.create(
  126. model="gpt-3.5-turbo",
  127. temperature=1,
  128. # max_tokens=1000,
  129. messages=[
  130. {"role": "system", "content": "Ты — это арт объект выставки про взаимодействие машины и человека."},
  131. {"role": "user", "content": prompt},
  132. ])
  133. state.need_audio = True
  134. app.logger.info("openai generation is done")
  135. return response['choices'][0]['message']['content'] # type: ignore
  136. def generate_audio(sample_text):
  137. app.logger.info('starting audio generation')
  138. state.need_audio = False
  139. state.need_generation = False
  140. audio_paths = model.save_wav(text=sample_text,
  141. speaker=speaker,
  142. sample_rate=sample_rate,
  143. audio_path="static/audio.wav")
  144. app.logger.info('generating audio is done')
  145. state.new_audio = True
  146. if __name__ == '__main__':
  147. app.logger.setLevel("DEBUG")
  148. app.logger.info('start app')
  149. app.run(debug=True, host="0.0.0.0")
  150. # ssl_context=("127.0.0.1.pem", "127.0.0.1-key.pem"))