main.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. import logging
  2. import os
  3. import json
  4. import re
  5. import uuid
  6. import random
  7. import openai
  8. import requests
  9. from openai import OpenAI
  10. from flask import Flask, request, jsonify, send_from_directory, url_for
  11. from convert import alpaca_to_chatgpt, csv_to_jsonl
  12. app = Flask(__name__)
  13. ssl = None
  14. # ssl =('/etc/ssl/sample.crt', '/etc/ssl/sample.pem')
  15. app.openai_key = os.environ.get("OPENAI_KEY", "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")
  16. app.openai_client = OpenAI(api_key=app.openai_key)
  17. #logging.basicConfig(level=logging.DEBUG, filename='/jkt-disk-01/app/mms/chatgpt-apache/chatgpt.log', format='%(asctime)s %(message)s')
  18. app.chat_messages = [
  19. {"role": "system",
  20. "content": "Please respond professionally and in a friendly manner, using the same language as the original request. Use emoji responsibly."}
  21. ]
  22. app.translate_messages = [
  23. {"role": "system",
  24. "content": "Please translate using the requested language."}
  25. ]
  26. app.suggest_messages = [
  27. {"role": "system",
  28. "content": "Please suggest reply messages based on the previous conversations and the user's request."}
  29. ]
  30. app.recommend_messages = [
  31. {"role": "system",
  32. "content": "Give normalized total weight of each category in json based on headlines"
  33. }
  34. ]
  35. app.summary_messages = [
  36. {"role": "system",
  37. "content": "Please summarize an article."
  38. }
  39. ]
  40. UPLOAD_FOLDER = 'files'
  41. app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
  42. @app.route('/files/<name>')
  43. def download_file(name):
  44. return send_from_directory(app.config["UPLOAD_FOLDER"], name)
  45. @app.route('/', methods=['GET', 'POST'])
  46. def test():
  47. return jsonify({"status": "0"})
  48. def roulette() -> str:
  49. roulette_arr = [(80, "gpt-4o-mini"), (20, "gpt-4o")]
  50. rand_num = random.randrange(0, 99)
  51. model_name = ""
  52. n = 0
  53. j = 0
  54. while rand_num > n:
  55. n += roulette_arr[j][0]
  56. model_name = roulette_arr[j][1]
  57. print(model_name)
  58. j += 1
  59. return model_name
  60. def recommend(headlines, category):
  61. chat_messages = app.recommend_messages.copy()
  62. try:
  63. json_payload = {
  64. "role": "user",
  65. "content": f"""{headlines}
  66. Berikan nilai berat masing-masing kategori, jumlahkan dan normalisasikan:
  67. {category}
  68. Berikan dalam bentuk json
  69. """
  70. }
  71. chat_messages.append(json_payload)
  72. json_response = app.openai_client.chat.completions.create(model="gpt-4o-mini",
  73. messages=chat_messages,
  74. response_format={"type": "json_object"}
  75. )
  76. result = {"status": "ok", "message": json.loads(json_response.choices[0].message.content)}
  77. except openai.APITimeoutError as e:
  78. app.logger.exception("error")
  79. result = {"status": "error", "message": e.message}, 408
  80. except openai.NotFoundError as e:
  81. app.logger.exception("error")
  82. result = {"status": "error", "message": json.loads(e.response.content)['error']['message']}, e.status_code
  83. except Exception as error_print:
  84. app.logger.exception("error")
  85. result = {"status": "error", "message": "Please try again"}, 405
  86. return result
  87. def vision(message, image_url=None, image_b64=None):
  88. chat_messages = app.chat_messages.copy()
  89. url = ""
  90. if image_url:
  91. url = f"{image_url}"
  92. elif image_b64:
  93. url = f"data:image/jpeg;base64,{image_b64}"
  94. try:
  95. json_payload = {
  96. "role": "user",
  97. "content": [
  98. {"type": "text", "text": message},
  99. {
  100. "type": "image_url",
  101. "image_url": {
  102. "url": url,
  103. },
  104. },
  105. ],
  106. }
  107. chat_messages.append(json_payload)
  108. json_response = app.openai_client.chat.completions.create(
  109. model="gpt-4o",
  110. messages=chat_messages,
  111. max_tokens=500
  112. )
  113. result = {"role": "assistant", "content": json_response.choices[0].message.content}
  114. except openai.APITimeoutError as e:
  115. app.logger.exception("error")
  116. result = {"status": "error", "message": e.message}, 408
  117. except openai.NotFoundError as e:
  118. app.logger.exception("error")
  119. result = {"status": "error", "message": json.loads(e.response.content)['error']['message']}, e.status_code
  120. except Exception as e:
  121. app.logger.exception("error")
  122. result = {"status": "error", "message": "Please try again"}, 405
  123. return result
  124. @app.route('/gpt', methods=['POST'])
  125. def gpt():
  126. assistant_id = ""
  127. assistant = None
  128. chat_messages = []
  129. chat_model = "gpt-4o-mini"
  130. use_video = False
  131. suggest = False
  132. summarize = False
  133. predict_q = 0
  134. max_char_msg = 500
  135. max_resp_token = 600
  136. category = []
  137. headlines = []
  138. image_url = ""
  139. num_choices = 1
  140. json_payload = request.get_json()
  141. if not json_payload:
  142. json_payload = []
  143. has_named_params = False
  144. if isinstance(json_payload, dict):
  145. has_named_params = 'payload' in json_payload
  146. if 'payload' in json_payload:
  147. if 'predict_q' in json_payload:
  148. predict_q = 5 if json_payload['predict_q'] > 4 else 0 if json_payload['predict_q'] < 1 else \
  149. json_payload['predict_q']
  150. if 'num_choices' in json_payload:
  151. num_choices = 5 if json_payload['num_choices'] > 4 else 1 if json_payload['num_choices'] < 2 else \
  152. json_payload['num_choices']
  153. if 'use_video' in json_payload:
  154. use_video = json_payload['use_video'] == "1"
  155. if 'chat_model' in json_payload and 'assistant_id' not in json_payload:
  156. chat_model = json_payload['chat_model']
  157. max_resp_token = 2048
  158. if 'translate' in json_payload:
  159. chat_messages = app.translate_messages.copy()
  160. json_payload['payload'][-1]['content'] = json_payload['payload'][-1][
  161. 'content'] + f" (Translate to {json_payload['translate']})"
  162. elif 'suggest' in json_payload:
  163. suggest = json_payload['suggest'] == "1"
  164. if suggest:
  165. chat_messages = app.suggest_messages.copy()
  166. else:
  167. chat_messages = app.chat_messages.copy()
  168. json_payload['payload'][-1]['content'] = json_payload['payload'][-1][
  169. 'content'] + f" What can I say to him/her?"
  170. elif 'summarize' in json_payload:
  171. summarize = json_payload['summarize'] == "1"
  172. if summarize:
  173. chat_messages = app.summary_messages.copy()
  174. max_char_msg = 2000
  175. max_resp_token = 1000
  176. else:
  177. chat_messages = app.chat_messages.copy()
  178. json_payload['payload'][-1]['content'] = f"Please summarize this article:\n" + \
  179. json_payload['payload'][-1]['content']
  180. elif 'assistant_id' in json_payload:
  181. assistant_id = json_payload['assistant_id']
  182. assistant = app.openai_client.beta.assistants.retrieve(assistant_id=assistant_id)
  183. chat_model = assistant.model
  184. else:
  185. chat_messages = app.chat_messages.copy()
  186. json_payload = json_payload['payload']
  187. if isinstance(json_payload, dict):
  188. json_payload = [json_payload]
  189. elif 'greeting' in json_payload:
  190. chat_messages = app.chat_messages.copy()
  191. company_name = json_payload['greeting']['company_name']
  192. timestamp = json_payload['greeting']['timestamp']
  193. islamic_message = f"Apakah Nama '{company_name}' terdapat unsur islami? Jawab dengan 'Ya' atau 'Tidak'"
  194. islam_messages = app.chat_messages.copy()
  195. islam_messages.append({
  196. "role": "user",
  197. "content": islamic_message
  198. })
  199. islamic_response = app.openai_client.chat.completions.create(model="gpt-4o-mini",
  200. messages=islam_messages,
  201. max_tokens=2, temperature=0.5)
  202. if 'Ya' in islamic_response.choices[0].message.content:
  203. greeting_message = f"Buatkan respons chatbot berupa greeting dari chat perusahaan bernama {company_name} pada jam {timestamp}, tidak perlu mention waktu, dan jawab dengan 'Assalamu'alaikum...' terlebih dahulu"
  204. else:
  205. greeting_message = f"Buatkan respons chatbot berupa greeting dari chat perusahaan bernama {company_name} pada jam {timestamp}, tidak perlu mention waktu"
  206. json_payload = [
  207. {
  208. "role": "user",
  209. "content": greeting_message
  210. }
  211. ]
  212. elif 'recommend' in json_payload:
  213. headlines = json_payload['recommend']['headlines']
  214. category = json_payload['recommend']['category']
  215. return recommend(headlines, category)
  216. elif 'image_url' in json_payload:
  217. image = json_payload['image_url']
  218. message = json_payload["message"] if 'message' in json_payload else "Ini gambar apa?"
  219. return vision(message, image_url=image)
  220. elif 'image_b64' in json_payload:
  221. image = json_payload['image_b64']
  222. message = json_payload["message"] if 'message' in json_payload else "Ini gambar apa?"
  223. return vision(message, image_b64=image_url)
  224. else:
  225. chat_messages = app.chat_messages.copy()
  226. json_payload = [json_payload]
  227. json_payload = json_payload[-5:]
  228. for message in json_payload:
  229. if message['role'] == 'user':
  230. content = message['content'].lower()
  231. else:
  232. content = message['content']
  233. content_arr = content.split(" ")
  234. new_content_arr = content[:max_char_msg].split(" ")
  235. new_content_len = len(new_content_arr)
  236. arr = []
  237. for i in range(new_content_len):
  238. arr.append(content_arr[i])
  239. message['content'] = " ".join(arr)
  240. chat_messages.append(message)
  241. app.logger.info(chat_messages)
  242. result = {}
  243. try:
  244. n = num_choices
  245. if "gpt-3.5-turbo" or "gpt-4o-mini" in chat_model:
  246. chat_model = roulette()
  247. app.logger.info(f"Model used: {chat_model}")
  248. if assistant_id and not suggest:
  249. runs = app.openai_client.beta.threads.create_and_run_poll(
  250. assistant_id=assistant_id,
  251. thread={
  252. "messages": chat_messages
  253. }
  254. )
  255. messages = list(app.openai_client.beta.threads.messages.list(thread_id=runs.thread_id, run_id=runs.id))
  256. message_content = messages[0].content[0].text
  257. app.logger.info(message_content.value)
  258. pattern = re.compile(r"【\d+:\d+†\(?source\)?】")
  259. filtered_message = pattern.sub("", message_content.value)
  260. result = {"role": "assistant", "content": filtered_message}
  261. else:
  262. json_response = app.openai_client.chat.completions.create(model=chat_model,
  263. messages=chat_messages,
  264. max_tokens=max_resp_token, temperature=0.7, n=n)
  265. app.logger.info(json_response.choices[0].message)
  266. if has_named_params:
  267. if suggest:
  268. choices = json_response.choices
  269. messages = [i.message for i in choices]
  270. json_formatted = []
  271. for message in messages:
  272. json_formatted.append({"role": "assistant", "content": message.content})
  273. result = {"url": "", "message": json_formatted}
  274. else:
  275. if use_video:
  276. # TODO: to be implemented
  277. result = {"url": url_for('download_file', name="test.mp4", _external=True),
  278. "message": {"role": "assistant", "content": json_response.choices[0].message.content}}
  279. else:
  280. result = {"role": "assistant", "content": json_response.choices[0].message.content}
  281. else:
  282. result = {"role": "assistant", "content": json_response.choices[0].message.content}
  283. if predict_q:
  284. if assistant_id:
  285. query_q = {
  286. "role": "user",
  287. "content": f"Berikan {predict_q} pertanyaan random yang akan saya ajukan sesuai topik asisten dalam bentuk json array"
  288. }
  289. else:
  290. query_q = {
  291. "role": "user",
  292. "content": f"Berikan {predict_q} pertanyaan lain yang akan saya ajukan berdasarkan percakapan kali ini dalam bentuk json array"
  293. }
  294. chat_messages.append(result)
  295. chat_messages.append(query_q)
  296. if assistant_id:
  297. runs = app.openai_client.beta.threads.create_and_run_poll(
  298. assistant_id=assistant_id,
  299. thread={
  300. "messages": chat_messages
  301. }
  302. )
  303. messages = list(app.openai_client.beta.threads.messages.list(thread_id=runs.thread_id, run_id=runs.id))
  304. message_content = messages[0].content[0].text
  305. app.logger.info(message_content.value)
  306. pattern = re.compile(r"【\d+:\d+†\(?source\)?】")
  307. filtered_message = pattern.sub("", message_content.value)
  308. predict_q_arr = [
  309. {
  310. "role": "system",
  311. "content": assistant.instructions
  312. },
  313. {
  314. "role": "assistant",
  315. "content": filtered_message
  316. },
  317. {
  318. "role": "user",
  319. "content": f"Ekstrak {predict_q} pertanyaan tersebut dalam bentuk json array"
  320. }
  321. ]
  322. json_response_q = app.openai_client.chat.completions.create(
  323. model=chat_model,
  324. messages=predict_q_arr,
  325. temperature=0.2,
  326. response_format={"type": "json_object"}
  327. )
  328. else:
  329. json_response_q = app.openai_client.chat.completions.create(model=chat_model,
  330. messages=chat_messages,
  331. max_tokens=max_resp_token,
  332. temperature=0.2,
  333. response_format={"type": "json_object"})
  334. json_response_dict = json.loads(json_response_q.choices[0].message.content)
  335. if json_response_dict is not None:
  336. if isinstance(json_response_dict, dict):
  337. if len(json_response_dict) > 1:
  338. qs = []
  339. for q in json_response_dict.values():
  340. qs.append(q)
  341. json_response_dict = qs
  342. else:
  343. try:
  344. first_key = next(iter(json_response_dict))
  345. json_response_dict = json_response_dict[first_key]
  346. except StopIteration:
  347. json_response_dict = []
  348. elif isinstance(json_response_dict, str):
  349. json_response_dict = [json_response_dict]
  350. result["predict_q"] = json_response_dict
  351. except openai.APITimeoutError as e:
  352. app.logger.exception("error")
  353. result = {"status": "error", "message": e.message}, 408
  354. except openai.NotFoundError as e:
  355. app.logger.exception("error")
  356. result = {"status": "error", "message": json.loads(e.response.content)['error']['message']}, e.status_code
  357. except Exception:
  358. app.logger.exception("error")
  359. result = {"status": "error", "message": "Please try again"}, 405
  360. return result
  361. @app.route('/train', methods=['POST'])
  362. def train():
  363. prev_model = "gpt-3.5-turbo"
  364. instructions = None
  365. if 'job_id' in request.form:
  366. return train_with_id(job_id=request.form['job_id'])
  367. elif 'train_file' in request.files:
  368. train_file = request.files['train_file']
  369. app.logger.info({"filename": train_file.filename})
  370. if 'instructions' in request.form:
  371. instructions = request.form['instructions']
  372. openai_file = None
  373. if train_file.filename.split('.')[1] == 'jsonl':
  374. openai_file = train_file.stream.read()
  375. elif train_file.filename.split('.')[1] == 'csv':
  376. openai_file = csv_to_jsonl(train_file.stream.read(), instructions)
  377. elif train_file.filename.split('.')[1] == 'json':
  378. openai_file = alpaca_to_chatgpt(train_file, instructions)
  379. if 'prev_model' in request.form:
  380. prev_model = request.form['prev_model']
  381. app.logger.info(f"Previous model: {prev_model}")
  382. if 'mock' not in request.form:
  383. f = app.openai_client.files.create(
  384. file=openai_file,
  385. purpose="fine-tune"
  386. )
  387. job = app.openai_client.fine_tuning.jobs.create(
  388. training_file=f.id,
  389. model=prev_model,
  390. hyperparameters={
  391. "n_epochs": 5
  392. }
  393. )
  394. app.logger.info({"mock": "no", "status": job.status, "job_id": job.id})
  395. retval = {"status": job.status, "job_id": job.id}
  396. return retval
  397. else:
  398. app.logger.info({"mock": "yes", "status": "ok"})
  399. return {"status": "ok"}
  400. else:
  401. app.logger.error({"status": "error", "message": "Training file not found"})
  402. return {"status": "error", "message": "Training file not found"}
  403. def train_with_id(job_id):
  404. try:
  405. job = app.openai_client.fine_tuning.jobs.retrieve(job_id)
  406. if job.fine_tuned_model is None:
  407. app.logger.info({"job_id": job_id, "status": job.status})
  408. return {"status": job.status}
  409. else:
  410. app.logger.info({"job_id": job_id, "status": job.status, "model_name": job.fine_tuned_model})
  411. return {"status": job.status, "model_name": job.fine_tuned_model}
  412. except Exception as error_print:
  413. app.logger.exception("error")
  414. return {"status": "Could not find job from id"}
  415. @app.route('/assistant/create', methods=['POST'])
  416. def assistant_create():
  417. model_name = "gpt-4o-mini"
  418. assistant_name = "Assistant"
  419. assistant_ins = "Please respond professionally and in a friendly manner, using the same language as the original request."
  420. if request.is_json:
  421. request_form = request.json
  422. else:
  423. request_form = request.form.copy()
  424. assistant_name = request_form.pop('name', assistant_name)
  425. assistant_ins = request_form.pop('instructions', assistant_ins)
  426. model_name = request_form.pop('model_name', model_name)
  427. vector_store_id = request_form.pop('vector_store_id', "")
  428. file_batch_id = ""
  429. try:
  430. temperature = float(request_form.pop('temperature', 1.0))
  431. if temperature < 0.0:
  432. temperature = 0.0
  433. elif temperature > 1.0:
  434. temperature = 1.0
  435. except ValueError:
  436. temperature = 1.0
  437. tool_resources = {"tool_resources": {"file_search": {"vector_store_ids": [vector_store_id]}}} \
  438. if vector_store_id \
  439. else {}
  440. try:
  441. assistant = app.openai_client.beta.assistants.create(
  442. name=assistant_name,
  443. instructions=assistant_ins,
  444. model=model_name,
  445. tools=[{"type": "file_search"}],
  446. temperature=temperature,
  447. **tool_resources,
  448. **request_form
  449. )
  450. if 'attachment1' in request.files and not vector_store_id:
  451. resp_att = assistant_att()
  452. retval = {}
  453. if resp_att['status'] == 'completed':
  454. resp_upd = assistant_update(assistant.id, resp_att['vector_store_id'])
  455. assistant_updated = "1" if resp_upd['status'] == 'ok' else "0"
  456. else:
  457. assistant_updated = "0"
  458. if 'vector_store_id' in resp_att:
  459. retval['vector_store_id'] = resp_att['vector_store_id']
  460. if 'file_batch_id' in resp_att:
  461. retval['file_batch_id'] = resp_att['file_batch_id']
  462. retval['status'] = "ok"
  463. retval['assistant_id'] = assistant.id
  464. retval['assistant_updated'] = assistant_updated
  465. return retval
  466. else:
  467. return {"status": "ok", "assistant_id": assistant.id, "assistant_updated": "1" if vector_store_id else "0"}
  468. except ValueError as e:
  469. app.logger.exception("error")
  470. return {"status": "error",
  471. "message": "Failed to create assistant, please check whether your parameters are correct"}
  472. except openai.NotFoundError as e:
  473. app.logger.exception("error")
  474. return {"status": "error", "message": json.loads(e.response.content)['error']['message']}, e.status_code
  475. except Exception:
  476. app.logger.exception("error")
  477. return {"status": "error", "message": "Failed to create assistant, please try again"}, 405
  478. @app.route('/assistant/attachment', methods=['POST'])
  479. def assistant_att():
  480. vector_store_id = request.form.get('vector_store_id', '')
  481. file_batch_id = request.form.get('file_batch_id', '')
  482. attachments: list[str] = []
  483. try:
  484. if not file_batch_id:
  485. if 'attachment1' not in request.files:
  486. return {"status": "error", "message": "No file for attachments"}
  487. else:
  488. has_attachments = True
  489. n = 1
  490. while has_attachments:
  491. if f'attachment{n}' in request.files:
  492. retf = app.openai_client.files.create(
  493. file=(request.files[f'attachment{n}'].filename,
  494. request.files[f'attachment{n}'].read()),
  495. purpose="assistants"
  496. )
  497. retf.filename = request.files[f'attachment{n}'].filename
  498. attachments.append(retf.id)
  499. n = n + 1
  500. else:
  501. has_attachments = False
  502. if vector_store_id:
  503. vector_store = app.openai_client.beta.vector_stores.retrieve(vector_store_id=vector_store_id)
  504. else:
  505. vector_store = app.openai_client.beta.vector_stores.create(
  506. expires_after={
  507. "anchor": "last_active_at",
  508. "days": 365
  509. }
  510. )
  511. file_batch = app.openai_client.beta.vector_stores.file_batches.create_and_poll(
  512. vector_store_id=vector_store.id,
  513. file_ids=attachments
  514. )
  515. return {"status": file_batch.status, "vector_store_id": vector_store.id, "file_batch_id": file_batch.id}
  516. else:
  517. file_batch = app.openai_client.beta.vector_stores.file_batches.retrieve(file_batch_id,
  518. vector_store_id=vector_store_id)
  519. return {"status": file_batch.status}
  520. except Exception as e:
  521. app.logger.exception("error")
  522. return {"status": "error", "message": "Upload attachment failed, please try again"}
  523. @app.route('/assistant/update', methods=['POST'])
  524. def assistant_update(aid=None, vid=None):
  525. try:
  526. request_form = request.form.copy()
  527. if aid is not None and vid is not None:
  528. assistant_id = aid
  529. vector_store_id = vid
  530. else:
  531. assistant_id = request_form.pop('assistant_id')
  532. vector_store_id = request_form.pop('vector_store_id', None)
  533. kwargs = {"assistant_id": assistant_id}
  534. if vector_store_id is not None:
  535. kwargs['tool_resources'] = {"file_search": {"vector_store_ids": [vector_store_id]}}
  536. if 'name' in request_form:
  537. kwargs['name'] = request_form.pop('name')
  538. if 'instructions' in request_form:
  539. kwargs['instructions'] = request_form.pop('instructions')
  540. app.openai_client.beta.assistants.update(**kwargs)
  541. return {"status": "ok"}
  542. except Exception as e:
  543. app.logger.exception("error")
  544. return {"status": "error", "message": "Update assistant failed, please try again"}
  545. @app.route('/llama', methods=['POST'])
  546. def llama():
  547. max_char_msg = 500
  548. max_resp_token = 600
  549. json_payload = request.get_json()
  550. if not json_payload:
  551. json_payload = []
  552. has_named_params = False
  553. if isinstance(json_payload, dict):
  554. has_named_params = 'payload' in json_payload
  555. if 'payload' in json_payload:
  556. json_payload = json_payload['payload']
  557. if isinstance(json_payload, dict):
  558. json_payload = [json_payload]
  559. else:
  560. json_payload = [json_payload]
  561. message = json_payload[-1]
  562. content = message['content']
  563. content_arr = content.split(" ")
  564. new_content_arr = content[:max_char_msg].split(" ")
  565. new_content_len = len(new_content_arr)
  566. arr = []
  567. for i in range(new_content_len):
  568. arr.append(content_arr[i])
  569. content = " ".join(arr)
  570. content = content + " Jawab dengan Bahasa Indonesia"
  571. try:
  572. json_request = {
  573. "model": "llama3.1",
  574. "prompt": content,
  575. "stream": False
  576. }
  577. r = requests.post("http://localhost:11434/api/generate", json=json_request)
  578. if r.status_code == 200:
  579. result = {
  580. "role": "assistant",
  581. "content": r.json()["response"]
  582. }
  583. else:
  584. result = {}, r.status_code
  585. except Exception as e:
  586. app.logger.exception("error")
  587. result = {"status": "error", "message": "Please try again"}, 405
  588. return result
  589. @app.route('/speech', methods=['POST'])
  590. def speech(text=""):
  591. if not text and 'text' not in request.form:
  592. audio_file = request.files.get('audio')
  593. res = app.openai_client.audio.transcriptions.create(
  594. model="whisper-1",
  595. file=(audio_file.filename, audio_file.stream.read())
  596. )
  597. return {"status": "ok", "message": res.text}
  598. elif 'text' in request.form or text:
  599. text = request.form['text'] if 'text' in request.form else text
  600. uu_id = str(uuid.uuid4())
  601. print(text)
  602. with app.openai_client.audio.speech.with_streaming_response.create(
  603. model="tts-1-hd",
  604. voice="echo",
  605. speed=0.8,
  606. input=text
  607. ) as res:
  608. res.stream_to_file(os.path.join(app.config['UPLOAD_FOLDER'], f"{uu_id}.mp3"))
  609. return download_file(f"{uu_id}.mp3")
  610. # Press the green button in the gutter to run the script.
  611. if __name__ == '__main__':
  612. app.run(host='0.0.0.0', port=8348, debug=True, ssl_context=ssl)
  613. # See PyCharm help at https://www.jetbrains.com/help/pycharm/