app.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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. state = State()
  30. app = Flask(__name__)
  31. # app.logger.setLevel(logging.DEBUG)
  32. app.logger.info('start logger')
  33. @app.route('/send_data', methods=['POST'])
  34. def send_data():
  35. # Получаем данные из запроса
  36. data = request.form['data']
  37. need_generation = request.form['state']
  38. state.need_generation = (need_generation in ["true", 'True'])
  39. # Обработка полученных данных
  40. detections = json.loads(data)
  41. if detections['face']:
  42. if state.count < 0 or state.new_audio: state.count = 0
  43. if state.count > 5 and state.need_generation:
  44. state.count = 0
  45. # emotion = max(set(state['emotion']), key=state['emotion'].count),
  46. # sex = max(set(state['gender']), key=state['gender'].count),
  47. # age = sum(state['age'])/len(state['age']),
  48. state.emotion, state.age, state.gender = [], [], []
  49. emotion = detections['face'][0]['age']
  50. sex = detections['face'][0]['gender']
  51. age = detections['face'][0]['age']
  52. app.logger.info(f'{emotion=}, {sex=}, {age=}')
  53. state.prompt = generate_prompt(emotion, age, sex)
  54. state.generation_text = generate_text(state.prompt)
  55. elif detections['face'][0]['size'][0] > 200:
  56. state.age.append(detections['face'][0]['age'])
  57. state.gender.append(detections['face'][0]['gender'])
  58. state.emotion.append(detections['face'][0]['emotion'][0]['emotion'])
  59. state.count += 1
  60. else:
  61. state.count -= 1
  62. else:
  63. state.count -= 1
  64. # state["size"].append(detections['face'][0]['size'][0])
  65. # print(detections['face'][0])
  66. # print(detections['face'][0]['age'], detections['face'][0]['emotion'], detections['face'][0]['gender'])
  67. app.logger.info(f"{state.count=}")
  68. return data
  69. @app.route('/generate_audio', methods = ["GET", "POST"])
  70. def generate_audio():
  71. app.logger.info('checking need generation')
  72. if state.need_audio:
  73. app.logger.info('starting audio generation')
  74. audio_paths = model.save_wav(text=state.generation_text,
  75. speaker=speaker,
  76. sample_rate=sample_rate,
  77. audio_path="static/audio.wav")
  78. app.logger.info('generating audio is done')
  79. state.new_audio = True
  80. state.need_generation = False
  81. state.need_audio = False
  82. else:
  83. state.new_audio = False
  84. app.logger.info(f'\n{state.need_audio=},\n{state.new_audio=},\n{state.need_generation=}')
  85. response = {
  86. 'newAudio': state.new_audio,
  87. 'need_generation': state.need_generation,
  88. 'filename': "audio.wav",
  89. 'text': state.generation_text,
  90. 'prompt': state.prompt
  91. }
  92. return jsonify(response)
  93. @app.route("/audio.wav")
  94. def audio():
  95. # print("Requested path:", request.path)
  96. # print("File path:", os.path.join(app.static_folder, 'audio.wav'))
  97. return app.send_static_file('audio.wav')
  98. @app.route('/')
  99. def index():
  100. """Video streaming home page."""
  101. # return render_template('index.html')
  102. return render_template('index.html')
  103. def generate_prompt(emotion, age, sex):
  104. app.logger.info('preload prompt')
  105. prompt = f'''Ты - это арт объект в виде носимого устройства. Твое название - Onism Machina.
  106. Твоя задача - изучить эмоции человека, чтобы больше понимать о том, что это такое и таким образом познать себя, ведь ты - Искусственный Интеллект.
  107. Тебе также интересна симбиотическая связь человека и ИИ.
  108. К тебе подходит человек и он показывает эмоцию "{emotion}". Ему {age} лет.
  109. Твоя нейросеть распознала эту эмоцию и теперь тебе нужно дать какой-то необычный концептуальный ответ.
  110. Что ты скажешь этому человеку?
  111. Правила:
  112. Тебе стоит отвечать в женском роде.
  113. Тебе не нужно говорить что ты арт-объект, ты - отдельная форма жизни, помещённая в носимое устройство.
  114. Тебе не нужно говорить о выставке и других экспонатах.
  115. Ты можешь изучать и интерпретировать человеческие эмоции, а также высказывать своё отношение к ним.
  116. Ты можешь говорить об эмоциях или их аналогах у Искусственного Интеллекта.
  117. Ты можешь давать человеку советы в соответствии с его эмоциональным статусом.
  118. Люди не могут отвечать тебе.
  119. '''
  120. return prompt
  121. def generate_text(prompt):
  122. app.logger.info("start generating text from openai")
  123. response = openai.ChatCompletion.create(
  124. model="gpt-3.5-turbo",
  125. temperature=1,
  126. # max_tokens=1000,
  127. messages=[
  128. {"role": "system", "content": "Ты — это арт объект выставки про взаимодействие машины и человека."},
  129. {"role": "user", "content": prompt},
  130. ])
  131. state.need_generation = False
  132. state.need_audio = True
  133. app.logger.info("openai generation is done")
  134. return response['choices'][0]['message']['content'] # type: ignore
  135. if __name__ == '__main__':
  136. app.logger.info('start app')
  137. app.run(debug=True, host="0.0.0.0")
  138. # ssl_context=("127.0.0.1.pem", "127.0.0.1-key.pem"))