Views
No views yet
For the reverse direction (Marathi → Bhili), see ai4bharat/bhili-translate-mar-bhb.
num_beams=4) instead of greedy.glossary.json, included in this repo) containing 6,400+ Bhili↔Marathi term pairs reviewed by native Bhili speakers.post_edit.py, included in this repo) that substitutes terms the model left in the source language with their target-language equivalents from the glossary.pip install torch transformers peft accelerate huggingface_hub1import torch
2from transformers import AutoModelForCausalLM, AutoTokenizer
3from peft import PeftModel
4from huggingface_hub import hf_hub_download
5
6# Load base model + adapter
7base_model_name = "sarvamai/sarvam-translate"
8adapter_name = "ai4bharat/bhili-translate-bhb-mar"
9
10tokenizer = AutoTokenizer.from_pretrained(base_model_name)
11model = AutoModelForCausalLM.from_pretrained(
12 base_model_name,
13 torch_dtype=torch.bfloat16,
14 device_map="auto",
15)
16model = PeftModel.from_pretrained(model, adapter_name)
17model.eval()
18
19# Load glossary + post-edit module from this repo
20glossary_path = hf_hub_download(adapter_name, "glossary.json")
21post_edit_path = hf_hub_download(adapter_name, "post_edit.py")
22
23import importlib.util
24spec = importlib.util.spec_from_file_location("post_edit", post_edit_path)
25pe = importlib.util.module_from_spec(spec)
26spec.loader.exec_module(pe)
27
28glossary = pe.load_glossary(glossary_path)
29
30# Translate
31def translate(text: str) -> str:
32 messages = [
33 {
34 "role": "system",
35 "content": (
36 "You are a professional Bhili (bhb) to Marathi (mr) translator. "
37 "Your goal is to accurately convey the meaning and nuances of the "
38 "original Bhili text while adhering to Marathi grammar, vocabulary, "
39 "and cultural sensitivities. Produce only the Marathi translation, "
40 "without any additional explanations or commentary. Please translate "
41 "the following Bhili text into Marathi:"
42 ),
43 },
44 {"role": "user", "content": text},
45 ]
46 prompt = tokenizer.apply_chat_template(
47 messages, tokenize=False, add_generation_prompt=True
48 )
49 inputs = tokenizer([prompt], return_tensors="pt").to(model.device)
50 with torch.no_grad():
51 output = model.generate(
52 **inputs,
53 max_new_tokens=256,
54 do_sample=False,
55 num_beams=4,
56 early_stopping=True,
57 )
58 raw = tokenizer.decode(
59 output[0][len(inputs.input_ids[0]):],
60 skip_special_tokens=True,
61 ).strip()
62 # Apply glossary post-edit
63 edited, _edits = pe.post_edit(
64 text, raw, glossary["bhb2mar_sorted_keys"], glossary["bhb2mar"]
65 )
66 return edited
67
68# Example
69print(translate("खेडूतांन वेगीवेळ फवारणी केरनु जोजे हाय."))
70print(translate("कोपास्यापापे गुलाबी बोंडअळीखातोर कॉपर ऑक्सिक्लोराईड फवारा."))