import os,json,time,threading,concurrent.futures as cf from openai import OpenAI from translit import tanglish c=OpenAI(base_url="https://router.huggingface.co/v1",api_key=os.environ.get("HF_TOKEN","x"),timeout=240) en={(d["link"],d["question_number"]):d for d in map(json.loads,open("eng_Latn.jsonl"))} ta={(d["link"],d["question_number"]):d for d in map(json.loads,open("tam_Taml.jsonl"))} keys=sorted(k for k in ta if k in en) INS={"en":"Answer with only the number of the correct option (1, 2, 3 or 4).","ta":"சரியான விடையின் எண்ணை மட்டும் (1, 2, 3 அல்லது 4) கூறவும்."} def prompt(k,cond): if cond=="translit": return tanglish(prompt(k,"ta").rsplit("\n\n",1)[0])+"\n\nCorrect option number mattum sollunga (1, 2, 3 illa 4)." P=(ta if cond in("ta","mix") else en)[k]; Q=(ta if cond=="ta" else en)[k] lab={"en":("Passage","Question","Options"),"ta":("பத்தி","கேள்வி","விடைகள்")}["ta" if cond=="ta" else "en"] opts="\n".join(f"{i}. {Q['mc_answer'+str(i)]}" for i in range(1,5)) return f"{lab[0]}:\n{P['flores_passage']}\n\n{lab[1]}: {Q['question']}\n\n{lab[2]}:\n{opts}\n\n{INS['ta' if cond=='ta' else 'en']}" OUT="belebele_raw.jsonl"; done=set(); lock=threading.Lock() if os.path.exists(OUT): for l in open(OUT): r=json.loads(l) if "error" not in r: done.add((r["link"],r["qn"],r["cond"])) jobs=[(k,cd) for k in keys for cd in ("translit",) if (k[0],k[1],cd) not in done] print("todo",len(jobs),flush=True) def run(j): k,cd=j; err=None for a in range(6): try: t=time.time() r=c.chat.completions.create(model="reflection/Beam-1.0-501B-A23B",messages=[{"role":"user","content":prompt(k,cd)}],max_tokens=4000) m=r.choices[0].message;u=r.usage rd=u.completion_tokens_details.reasoning_tokens if u.completion_tokens_details else None rec=dict(link=k[0],qn=k[1],cond=cd,gold=str(en[k]["correct_answer_num"]),output=m.content,prompt_tokens=u.prompt_tokens,completion_tokens=u.completion_tokens,reasoning_tokens=rd,latency=round(time.time()-t,2),finish=r.choices[0].finish_reason) break except Exception as e: err=str(e)[:200]; time.sleep(4*(a+1)) else: rec=dict(link=k[0],qn=k[1],cond=cd,error=err) with lock: open(OUT,"a").write(json.dumps(rec,ensure_ascii=False)+"\n") with cf.ThreadPoolExecutor(12) as ex: list(ex.map(run,jobs)) print("done",flush=True)