Spaces:
Sleeping
Sleeping
| import os | |
| import requests | |
| BASE = os.getenv("ENBN_API_URL", "https://samin7479-en-bn-translator.hf.space") | |
| HEADERS = {"Content-Type": "application/json"} | |
| def greet(): | |
| try: | |
| r = requests.get(f"{BASE}/greet", headers=HEADERS, timeout=20) | |
| r.raise_for_status() | |
| return r.json() | |
| except Exception as e: | |
| return {"error": str(e)} | |
| def translate(text, max_new_tokens=128, num_beams=4): | |
| try: | |
| payload = { | |
| "text": text, | |
| "max_new_tokens": max_new_tokens, | |
| "num_beams": num_beams, | |
| "do_sample": False | |
| } | |
| r = requests.post(f"{BASE}/translate", json=payload, headers=HEADERS, timeout=60) | |
| r.raise_for_status() | |
| return r.json().get("translation") | |
| except Exception as e: | |
| return f"[error] {e}" | |
| def translate_batch(texts, max_new_tokens=128, num_beams=4): | |
| try: | |
| payload = { | |
| "texts": texts, | |
| "max_new_tokens": max_new_tokens, | |
| "num_beams": num_beams, | |
| "do_sample": False | |
| } | |
| r = requests.post(f"{BASE}/translate_batch", json=payload, headers=HEADERS, timeout=120) | |
| r.raise_for_status() | |
| return r.json().get("translations", []) | |
| except Exception as e: | |
| return [f"[error] {e}"] | |
| if __name__ == "__main__": | |
| # quick smoke test | |
| print("GREET:", greet()) | |
| en = "How are you today?" | |
| bn = translate(en) | |
| print(f"\nSingle:\nEN: {en}\nBN: {bn}") | |
| batch = ["Good morning", "Where is the hospital?", "The weather is nice."] | |
| outs = translate_batch(batch) | |
| print("\nBatch:") | |
| for e, b in zip(batch, outs): | |
| print(f"EN: {e}\nBN: {b}\n") | |