flask_app.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. from flask import Flask, request, send_from_directory, render_template
  2. import speech_recognition as sr
  3. import openai
  4. import os
  5. import json
  6. import tiktoken
  7. from gtts import gTTS
  8. import uuid
  9. import subprocess
  10. from pydub import AudioSegment
  11. # from OpenSSL import SSL
  12. app = Flask(__name__)
  13. app.config['UPLOAD_FOLDER'] = "files"
  14. PROJECT_ABSPATH = os.path.abspath(".")
  15. WAV2LIP_ABSPATH = "/home/maronakins/Documents/Wav2Lip"
  16. # ALLOWED_EXTENSIONS = {'mp3', 'wav'}
  17. # context = SSL.Context(SSL.TLSv1_2_METHOD)
  18. # context.load_cert_chain('certificate.crt', 'private.key')
  19. with open('open_ai_key') as f:
  20. openai.api_key = f.readline()
  21. chat_messages = [
  22. {"role": "system", "content": "Kamu adalah asisten yang baik hati, tapi jawaban nya jangan panjang-panjang ya"}
  23. ]
  24. encoding = tiktoken.encoding_for_model("gpt-3.5-turbo")
  25. def verify_token(token):
  26. # Verify that the token is valid (e.g. by checking against a database)
  27. return True
  28. @app.route('/', methods=['GET', 'POST'])
  29. def index():
  30. if request.method == 'GET':
  31. return render_template("index.html")
  32. else:
  33. return "Unsupported request", 415
  34. @app.route('/process', methods=['POST'])
  35. def process_input():
  36. if request.is_json:
  37. msg_json = request.get_json(force=True)
  38. print(msg_json)
  39. else:
  40. return "Unsupported request", 415
  41. # result = process_input(msg_json)
  42. # Verify the token
  43. # token = request.headers.get('Authorization')
  44. # if not verify_token(token):
  45. # return 'Invalid token', 401
  46. req_id = str(uuid.uuid4())
  47. use_video = True if msg_json["use_video"] == "1" else False
  48. print(msg_json)
  49. payload = msg_json["payload"]
  50. msg = chat_messages.copy()
  51. for i in payload:
  52. msg.append(i)
  53. print(msg)
  54. completed = False
  55. completion = None
  56. chat_response = ""
  57. while not completed:
  58. try:
  59. completion = openai.ChatCompletion.create(
  60. model="gpt-3.5-turbo",
  61. messages=msg,
  62. max_tokens=400
  63. )
  64. chat_response = completion.choices[0].message.content
  65. completed = True
  66. except openai.error.RateLimitError as e:
  67. pass
  68. print(f'{completion["usage"]["prompt_tokens"]} prompt tokens counted by the OpenAI API.')
  69. print(f'{completion["usage"]["completion_tokens"]} completion tokens counted by the OpenAI API.')
  70. print(f'{completion["usage"]["total_tokens"]} total tokens counted by the OpenAI API.')
  71. print(f'ChatGPT: {chat_response}')
  72. language = 'id'
  73. myobj = gTTS(text=chat_response, lang=language, slow=False)
  74. audio_filename = f"chat-{req_id}.mp3"
  75. video_filename = ""
  76. myobj.save(os.path.join(app.config["UPLOAD_FOLDER"], audio_filename))
  77. try:
  78. if use_video:
  79. video_filename = f"video-{req_id}.mp4"
  80. wavlip_python = os.path.join(WAV2LIP_ABSPATH, "venv", "bin", "python")
  81. wavlip_pyfile = os.path.join(WAV2LIP_ABSPATH, "inference.py")
  82. wavlip_checkpoint = os.path.join(WAV2LIP_ABSPATH, "checkpoints", "wav2lip_gan.pth")
  83. wavlip_temp = os.path.join(WAV2LIP_ABSPATH, "temp")
  84. wavlip_face = os.path.join(WAV2LIP_ABSPATH, "ganjarstill.mp4")
  85. wavlip_audio = os.path.join(PROJECT_ABSPATH, "files", audio_filename)
  86. wavlip_outfile = os.path.join(PROJECT_ABSPATH, "files", video_filename)
  87. subprocess.run([wavlip_python, wavlip_pyfile,
  88. "--checkpoint_path", wavlip_checkpoint,
  89. "--temp", wavlip_temp,
  90. "--face_det_batch_size", "64", "--resize_factor", "2",
  91. "--face", wavlip_face,
  92. "--audio", wavlip_audio,
  93. "--outfile", wavlip_outfile], check=True)
  94. except Exception as e:
  95. print(str(e))
  96. video_filename = ""
  97. return {"role": "assistant", "content": f'{chat_response}', "audio": audio_filename, "video": video_filename}
  98. @app.route('/files/<filename>', methods=["GET"])
  99. def files(filename):
  100. return send_from_directory(directory=app.config["UPLOAD_FOLDER"], path=filename)
  101. if __name__ == '__main__':
  102. app.run(debug=True, host='0.0.0.0', port=46294)
  103. # app.run(debug=True, host='0.0.0.0', port=8080, ssl_context=context)