Spaces:
Runtime error
Runtime error
File size: 16,213 Bytes
0e751e1 acfd285 c8d8296 2611c3d 44fddb5 c8d8296 2611c3d c8d8296 def5e7b 33f430f def5e7b 003a9d2 def5e7b 003a9d2 def5e7b 33f430f def5e7b 55372df 0e751e1 33f430f 55372df 33f430f def5e7b 33f430f def5e7b 55372df def5e7b 33f430f def5e7b 205289c def5e7b c8d8296 44fddb5 c8d8296 2611c3d c8d8296 44fddb5 2611c3d def5e7b 215420c 2611c3d c8d8296 2611c3d 565036f 2611c3d ee9eb8d 660d778 13e6865 85de656 55f2881 a6a0d40 55f2881 13e6865 18893af 85de656 def5e7b 2611c3d def5e7b 2611c3d c8d8296 2611c3d c8d8296 2611c3d c8d8296 2611c3d c8d8296 def5e7b c8d8296 def5e7b c8d8296 def5e7b 2611c3d c8d8296 2611c3d 0e751e1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 | # import gradio as gr
# from fastapi import FastAPI
# from fastapi.middleware.cors import CORSMiddleware
# from pydantic import BaseModel
# from gradio_client import Client
# import uvicorn
# import os
# ############ logging, and committing translation ##############
# from huggingface_hub import HfApi, CommitOperationAdd
# import time
# from datetime import datetime
# from langdetect import detect
# from huggingface_hub import update_dataset_card
# import json
# import threading
# import queue
# import hashlib
# HF_DATASET = "Juna190825/zomi-translation-logs"
# HF_TOKEN = os.getenv("HF_TOKEN")
# ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD")
# api = HfApi(token=HF_TOKEN)
# log_queue = queue.Queue()
# LOG_DIR = "/data"
# BUFFER_FILE = os.path.join(LOG_DIR, "log_buffer.jsonl")
# COMMIT_INTERVAL_SECONDS = 900 # every 15 minutes
# def append_log(input_text: str, output_text: str):
# os.makedirs(LOG_DIR, exist_ok=True)
# record = {
# "ts": datetime.utcnow().isoformat() + "Z",
# "src_text": input_text[:500],
# "tgt_text": output_text[:500],
# "app": "zomi-translator",
# "version": "1.0.0"
# }
# with open(BUFFER_FILE, "a", encoding="utf-8") as f:
# f.write(json.dumps(record, ensure_ascii=False) + "\n")
# def commit_logs_to_hf(manual=False):
# if not HF_TOKEN or not os.path.exists(BUFFER_FILE):
# return "No logs to commit."
# if not os.path.exists(BUFFER_FILE) or os.path.getsize(BUFFER_FILE) < 10:
# return "No new logs."
# with open(BUFFER_FILE, "r", encoding="utf-8") as f:
# data = f.read().strip()
# if not data:
# return "No new logs."
# date_str = datetime.utcnow().strftime("%Y-%m-%d")
# repo_path = f"logs/{date_str}.jsonl"
# api.upload_file(
# path_or_fileobj=BUFFER_FILE,
# path_in_repo=repo_path,
# repo_id=HF_DATASET,
# repo_type="dataset",
# commit_message="Manual log commit" if manual else "Auto daily log commit"
# )
# # Clear buffer after successful commit
# open(BUFFER_FILE, "w").close()
# return f"Committed logs to {repo_path}"
# def update_dataset_card_info():
# api = HfApi()
# # Build the README.md content dynamically
# readme = f"""
# # Zomi Translator Logs
# **License:** MIT
# **Languages:** Zomi, English
# Daily logs of Zomi β English translations.
# """
# api.create_commit(
# repo_id=HF_DATASET,
# repo_type="dataset",
# commit_message="Update dataset card metadata",
# operations=[
# CommitOperationAdd(
# path_in_repo="README.md",
# path_or_fileobj=readme.encode("utf-8")
# )
# ]
# )
# def manual_commit(password: str):
# if not ADMIN_PASSWORD:
# return "β Admin password not configured."
# if password != ADMIN_PASSWORD:
# return "β Invalid admin password."
# result = commit_logs_to_hf(manual=True)
# return f"β
{result}"
# def append_log_async(input_text, output_text, direction):
# log_queue.put({
# "ts": datetime.utcnow().isoformat() + "Z",
# # "src_text_hash": hashlib.sha256(input_text.encode("utf-8")).hexdigest(),
# "src_text": input_text,
# "tgt_text": output_text[:500],
# "direction": direction,
# "app": "zomi-translator",
# "version": "1.0.0"
# })
# def async_commit_worker():
# buffer = []
# while True:
# try:
# # Collect up to 50 logs or 60 seconds
# start = time.time()
# while len(buffer) < 50 and (time.time() - start < 60):
# try:
# buffer.append(log_queue.get(timeout=1))
# except queue.Empty:
# pass
# if buffer:
# os.makedirs(LOG_DIR, exist_ok=True)
# date_str = datetime.utcnow().strftime("%Y-%m-%d")
# batch_file = os.path.join(LOG_DIR, f"{date_str}.jsonl")
# with open(batch_file, "a", encoding="utf-8") as f:
# for record in buffer:
# f.write(json.dumps(record, ensure_ascii=False) + "\n")
# commit_logs_to_hf() # commits the batch file
# update_dataset_card_info()
# buffer.clear()
# except Exception as e:
# print("Async commit failed:", e)
# ###############################################################
# app = FastAPI()
# # Enable CORS
# app.add_middleware(
# CORSMiddleware,
# allow_origins=["*"],
# allow_credentials=True,
# allow_methods=["*"],
# allow_headers=["*"],
# )
# # Initialize client once
# translator_client = Client("Chatboong/Gemini_Translator")
# def call_translator(text: str):
# msg = f"Translate Zomi to English, if it is English translate it to Zomi: '{text}'\n"
# stream = translator_client.predict(
# message=msg,
# lang="English",
# is_streaming=True,
# api_name="/chat",
# )
# output = ""
# for chunk in stream:
# output += str(chunk)
# # Remove prefix
# prefix = "Translate Zomi to English, if it is English translate it to Zomi: "
# prefix2 = "Zomi pan English in tei in, English ahih leh Zomi in tei in: "
# prefix3 = 'Zomi-in tei in, English ahih leh Zomi-in tei in: '
# if output.startswith(prefix):
# output = output[len(prefix):].strip()
# # Remove surrounding quotes
# if (output.startswith('"') and output.endswith('"')) or (output.startswith("'") and output.endswith("'")):
# output = output[1:-1].strip()
# elif output.startswith(prefix2):
# output = output[len(prefix2):].strip()
# # Remove surrounding quotes
# if (output.startswith('"') and output.endswith('"')) or (output.startswith("'") and output.endswith("'")):
# output = output[1:-1].strip()
# elif output.startswith(prefix3):
# output = output[len(prefix3):].strip()
# # Remove surrounding quotes
# if (output.startswith('"') and output.endswith('"')) or (output.startswith("'") and output.endswith("'")):
# output = output[1:-1].strip()
# append_log(text, output)
# return output
# def detect_direction(text: str) -> str:
# try:
# lang = detect(text)
# if lang == "en":
# return "en-zomi"
# else:
# return "zomi-en"
# except:
# return "en-zomi"
# def translate_zomi(text: str):
# direction = detect_direction(text)
# output = call_translator(text) # your existing streaming code
# append_log_async(text, output, direction)
# return output
# class ChatRequest(BaseModel):
# message: str
# @app.post("/chat")
# async def chat_api(req: ChatRequest):
# translation = translate_zomi(req.message)
# return {"translation": translation}
# def chat_ui(message: str):
# return translate_zomi(message)
# with gr.Blocks() as demo:
# gr.Markdown("### Zomi Translator")
# inp = gr.Textbox(label="Input")
# out = gr.Textbox(label="Output")
# inp.submit(chat_ui, inp, out)
# if ADMIN_PASSWORD:
# gr.Markdown("### Admin (Protected)")
# admin_pw = gr.Textbox(
# label="Admin Password",
# type="password",
# placeholder="Enter admin password"
# )
# commit_btn = gr.Button("π¦ Commit Logs Now")
# status = gr.Textbox(label="Commit Status", interactive=False)
# commit_btn.click(
# manual_commit,
# inputs=admin_pw,
# outputs=status
# ).then(
# lambda: "",
# None,
# admin_pw
# )
# if HF_TOKEN:
# threading.Thread(target=async_commit_worker, daemon=True).start()
# # Mount Gradio under the FastAPI app
# app = gr.mount_gradio_app(app, demo, path="/")
# if __name__ == "__main__":
# # Respect PORT env var (used by Hugging Face Spaces)
# port = int(os.getenv("PORT", "7860"))
# uvicorn.run(app, host="0.0.0.0", port=port)
import gradio as gr
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from gradio_client import Client
import uvicorn
import os
############ logging, and committing translation ##############
from huggingface_hub import HfApi, CommitOperationAdd, RepoCard
import time
from datetime import datetime
from langdetect import detect
import json
import threading
import queue
import hashlib
HF_DATASET = "Juna190825/zomi-translation-logs"
HF_TOKEN = os.getenv("HF_TOKEN")
ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD")
api = HfApi(token=HF_TOKEN)
log_queue = queue.Queue()
LOG_DIR = "/data"
BUFFER_FILE = os.path.join(LOG_DIR, "log_buffer.jsonl")
COMMIT_INTERVAL_SECONDS = 900 # every 15 minutes
def append_log(input_text: str, output_text: str):
os.makedirs(LOG_DIR, exist_ok=True)
record = {
"ts": datetime.utcnow().isoformat() + "Z",
"src_text": input_text[:500],
"tgt_text": output_text[:500],
"app": "zomi-translator",
"version": "1.0.0"
}
with open(BUFFER_FILE, "a", encoding="utf-8") as f:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
def commit_logs_to_hf(manual=False):
if not HF_TOKEN or not os.path.exists(BUFFER_FILE):
return "No logs to commit."
if not os.path.exists(BUFFER_FILE) or os.path.getsize(BUFFER_FILE) < 10:
return "No new logs."
with open(BUFFER_FILE, "r", encoding="utf-8") as f:
data = f.read().strip()
if not data:
return "No new logs."
date_str = datetime.utcnow().strftime("%Y-%m-%d")
# Add timestamp to make filename unique
if manual:
timestamp = datetime.utcnow().strftime("%Y%m%d-%H%M%S")
repo_path = f"logs/manual_{date_str}_{timestamp}.jsonl"
commit_msg = f"Manual log commit {timestamp}"
else:
timestamp = datetime.utcnow().strftime("%Y%m%d-%H%M%S")
repo_path = f"logs/auto_{date_str}_{timestamp}.jsonl"
commit_msg = f"Auto log commit {timestamp}"
api.upload_file(
path_or_fileobj=BUFFER_FILE,
path_in_repo=repo_path,
repo_id=HF_DATASET,
repo_type="dataset",
commit_message=commit_msg
)
# Clear buffer after successful commit
open(BUFFER_FILE, "w").close()
return f"Committed logs to {repo_path}"
def update_dataset_card_info():
# Build the README.md content dynamically
readme_content = f"""
# Zomi Translator Logs
**License:** MIT
**Languages:** Zomi, English
Daily logs of Zomi β English translations.
"""
# Create a RepoCard object
card = RepoCard(readme_content)
api = HfApi()
# Upload README.md to the dataset repo
api.upload_file(
path_or_fileobj=card.content.encode("utf-8"),
path_in_repo="README.md",
repo_id=HF_DATASET,
repo_type="dataset"
)
def manual_commit(password: str):
if not ADMIN_PASSWORD:
return "β Admin password not configured."
if password != ADMIN_PASSWORD:
return "β Invalid admin password."
result = commit_logs_to_hf(manual=True)
return f"β
{result}"
def append_log_async(input_text, output_text, direction):
log_queue.put({
"ts": datetime.utcnow().isoformat() + "Z",
"src_text": input_text,
"tgt_text": output_text[:500],
"direction": direction,
"app": "zomi-translator",
"version": "1.0.0"
})
def async_commit_worker():
buffer = []
while True:
try:
# Collect up to 50 logs or 60 seconds
start = time.time()
while len(buffer) < 50 and (time.time() - start < 60):
try:
buffer.append(log_queue.get(timeout=1))
except queue.Empty:
pass
if buffer:
os.makedirs(LOG_DIR, exist_ok=True)
date_str = datetime.utcnow().strftime("%Y-%m-%d")
batch_file = os.path.join(LOG_DIR, f"{date_str}.jsonl")
with open(batch_file, "a", encoding="utf-8") as f:
for record in buffer:
f.write(json.dumps(record, ensure_ascii=False) + "\n")
commit_logs_to_hf() # commits the batch file
update_dataset_card_info()
buffer.clear()
except Exception as e:
print("Async commit failed:", e)
###############################################################
app = FastAPI()
# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize client once
translator_client = Client("Chatboong/Gemini_Translator")
def call_translator(text: str):
msg = f"Translate Zomi to English, if it is English translate it to Zomi: '{text}'\n"
stream = translator_client.predict(
message=msg,
lang="English",
is_streaming=True,
api_name="/chat",
)
output = ""
for chunk in stream:
output += str(chunk)
# Remove prefix
prefix = "Translate Zomi to English, if it is English translate it to Zomi: "
prefix2 = "Zomi pan English in tei in, English ahih leh Zomi in tei in: "
prefix3 = 'Zomi-in tei in, English ahih leh Zomi-in tei in: '
if output.startswith(prefix):
output = output[len(prefix):].strip()
# Remove surrounding quotes
if (output.startswith('"') and output.endswith('"')) or (output.startswith("'") and output.endswith("'")):
output = output[1:-1].strip()
elif output.startswith(prefix2):
output = output[len(prefix2):].strip()
# Remove surrounding quotes
if (output.startswith('"') and output.endswith('"')) or (output.startswith("'") and output.endswith("'")):
output = output[1:-1].strip()
elif output.startswith(prefix3):
output = output[len(prefix3):].strip()
# Remove surrounding quotes
if (output.startswith('"') and output.endswith('"')) or (output.startswith("'") and output.endswith("'")):
output = output[1:-1].strip()
append_log(text, output)
return output
def detect_direction(text: str) -> str:
try:
lang = detect(text)
if lang == "en":
return "en-zomi"
else:
return "zomi-en"
except:
return "en-zomi"
def translate_zomi(text: str):
direction = detect_direction(text)
output = call_translator(text) # your existing streaming code
append_log_async(text, output, direction)
return output
class ChatRequest(BaseModel):
message: str
@app.post("/chat")
async def chat_api(req: ChatRequest):
translation = translate_zomi(req.message)
return {"translation": translation}
def chat_ui(message: str):
return translate_zomi(message)
with gr.Blocks() as demo:
gr.Markdown("### Zomi Translator")
inp = gr.Textbox(label="Input")
out = gr.Textbox(label="Output")
inp.submit(chat_ui, inp, out)
if ADMIN_PASSWORD:
gr.Markdown("### Admin (Protected)")
admin_pw = gr.Textbox(
label="Admin Password",
type="password",
placeholder="Enter admin password"
)
commit_btn = gr.Button("π¦ Commit Logs Now")
status = gr.Textbox(label="Commit Status", interactive=False)
commit_btn.click(
manual_commit,
inputs=admin_pw,
outputs=status
).then(
lambda: "",
None,
admin_pw
)
if HF_TOKEN:
threading.Thread(target=async_commit_worker, daemon=True).start()
# Mount Gradio under the FastAPI app
app = gr.mount_gradio_app(app, demo, path="/")
if __name__ == "__main__":
# Respect PORT env var (used by Hugging Face Spaces)
port = int(os.getenv("PORT", "7860"))
uvicorn.run(app, host="0.0.0.0", port=port) |