import json import os import requests import time from environs import Env env = Env() env.read_env() LANGLINK_HEADERS = { "Content-Type": "application/json", "x-langlink-access-key": env("LANGLINK_ACCESS_KEY"), "x-langlink-access-secret": env("LANGLINK_ACCESS_SEC"), "x-langlink-user": env("LANGLINK_REPORT_USER"), } OUTPUT_NODE_ID = env("LANGLINK_REPORT_OUTPUT_ID") RERUN_TIME = 3 RETRY_INTERVAL = 5000 RETRY_TIME = 24 def execute_langlink_app(app_id: str, input_text: str): def rerun_loop(rerun_time=0): while rerun_time < RERUN_TIME: try: result = run_langlink_app(app_id, input_text) return result except Exception as e: print(e) rerun_time += 1 rerun_loop(rerun_time) print(input_text) raise Exception(f"Maximum rerun attempts reached: {RERUN_TIME}.") return rerun_loop() def run_langlink_app(app_id: str, input_text: str): data = { "input": input_text } url = os.path.join(env.str('LANGLINK_ENDPOINT'), "applications", app_id, 'async') headers = LANGLINK_HEADERS res = requests.post(url, data=json.dumps(data), headers=headers, verify=False) data = res.json() retry_time = 0 while retry_time < RETRY_TIME: result = get_langlink_result(app_id, data["id"]) if result: return result[0]["output"] time.sleep(RETRY_INTERVAL / 1000) retry_time += 1 raise Exception(f"Maximum retry attempts reached: {RETRY_TIME}.") def get_langlink_result(app_id: str, id: str): url = os.path.join(env.str('LANGLINK_ENDPOINT'), "applications", app_id, 'debug', id) headers = LANGLINK_HEADERS res = requests.get(url, headers=headers, verify=False) data = res.json() if res.status_code != 200: raise Exception(json.dumps(data)) return data["debug"]