Views
No views yet
1import torch
2from transformers import AutoProcessor, Gemma3nForConditionalGeneration
3
4MODEL_ID = "oddadmix/egyptian-code-switching-b4-g2-merged"
5
6def load_model_and_processor(model_id=MODEL_ID, device=None):
7 if device is None:
8 device = "cuda" if torch.cuda.is_available() else "cpu"
9
10 print(f"Loading model {model_id} to device {device}...")
11
12 model = Gemma3nForConditionalGeneration.from_pretrained(
13 model_id,
14 torch_dtype=torch.bfloat16 if device == "cuda" else None,
15 device_map="auto" if device == "cuda" else None,
16 ).eval()
17
18 if not any(p.device.type == "cuda" for p in model.parameters()) and device == "cuda":
19 model.to("cuda")
20
21 processor = AutoProcessor.from_pretrained(model_id)
22 return model, processor, device
23
24
25def transcribe_file(model, processor, audio_path, max_new_tokens=128):
26 if not audio_path:
27 raise ValueError("audio_path must point to an audio file")
28
29 messages = [
30 {
31 "role": "system",
32 "content": [
33 {"type": "text", "text": "You are an assistant that transcribes speech accurately."}
34 ],
35 },
36 {
37 "role": "user",
38 "content": [
39 {"type": "audio", "url": audio_path},
40 {"type": "text", "text": "Please transcribe this audio."}
41 ],
42 },
43 ]
44
45 inputs = processor.apply_chat_template(
46 messages,
47 add_generation_prompt=True,
48 tokenize=True,
49 return_dict=True,
50 return_tensors="pt",
51 )
52
53 device = next(model.parameters()).device
54 inputs = {k: v.to(device) for k, v in inputs.items()}
55 input_len = inputs["input_ids"].shape[-1]
56
57 with torch.inference_mode():
58 generated = model.generate(
59 **inputs,
60 max_new_tokens=max_new_tokens,
61 do_sample=False,
62 )
63
64 gen_tokens = generated[0][input_len:]
65 text = processor.decode(gen_tokens, skip_special_tokens=True)
66 return text
67
68
69if __name__ == "__main__":
70 audio_path = "path/to/audio.wav"
71 model, processor, device = load_model_and_processor()
72 transcription = transcribe_file(model, processor, audio_path, max_new_tokens=256)
73 print("Transcription:", transcription)