main.py 27 KB

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