File size: 5,038 Bytes
7af55e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForSeq2SeqLM
from sentence_transformers import SentenceTransformer
import gradio as gr
import faiss
import numpy as np
import whisper

# Load models
lang_detect_model = AutoModelForSequenceClassification.from_pretrained("papluca/xlm-roberta-base-language-detection")
lang_detect_tokenizer = AutoTokenizer.from_pretrained("papluca/xlm-roberta-base-language-detection")
trans_model = AutoModelForSeq2SeqLM.from_pretrained("facebook/nllb-200-distilled-600M")
trans_tokenizer = AutoTokenizer.from_pretrained("facebook/nllb-200-distilled-600M")
embed_model = SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")

# Language mappings
id2lang = lang_detect_model.config.id2label
nllb_langs = {
    "eng_Latn": "English", "fra_Latn": "French", "hin_Deva": "Hindi",
    "spa_Latn": "Spanish", "deu_Latn": "German", "tam_Taml": "Tamil",
    "tel_Telu": "Telugu", "jpn_Jpan": "Japanese", "zho_Hans": "Chinese",
    "arb_Arab": "Arabic", "san_Deva": "Sanskrit"
}
xlm_to_nllb = {
    "en": "eng_Latn", "fr": "fra_Latn", "hi": "hin_Deva", "es": "spa_Latn", "de": "deu_Latn",
    "ta": "tam_Taml", "te": "tel_Telu", "ja": "jpn_Jpan", "zh": "zho_Hans", "ar": "arb_Arab",
    "sa": "san_Deva"
}
lang_options = list(nllb_langs.keys())

# Sample corpus
corpus = [
    "เคงเคฐเฅเคฎ เคเคต เคนเคคเฅ‹ เคนเคจเฅเคคเคฟ เคงเคฐเฅเคฎเฅ‹ เคฐเค•เฅเคทเคคเคฟ เคฐเค•เฅเคทเคฟเคคเคƒ",
    "Dharma when destroyed, destroys; when protected, protects.",
    "The moon affects tides and mood, according to Jyotisha",
    "One should eat according to the season โ€“ Rituacharya",
    "Balance of Tridosha is health โ€“ Ayurveda principle",
    "Ethics in Mahabharata reflect situational dharma",
    "Meditation improves memory and mental clarity",
    "Jyotisha links planetary motion with life patterns"
]
corpus_embeddings = embed_model.encode(corpus, convert_to_numpy=True)
dimension = corpus_embeddings.shape[1]
index = faiss.IndexFlatL2(dimension)
index.add(corpus_embeddings)

def detect_language(text):
    inputs = lang_detect_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
    with torch.no_grad():
        outputs = lang_detect_model(**inputs)
        probs = F.softmax(outputs.logits, dim=1)
        pred = torch.argmax(probs, dim=1).item()
    return id2lang[pred]

def translate(text, src_code, tgt_code):
    trans_tokenizer.src_lang = src_code
    encoded = trans_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
    try:
        target_lang_id = trans_tokenizer.convert_tokens_to_ids([tgt_code])[0]
        generated = trans_model.generate(**encoded, forced_bos_token_id=target_lang_id)
        return trans_tokenizer.decode(generated[0], skip_special_tokens=True)
    except:
        return ""

def search_semantic(query, top_k=3):
    query_embedding = embed_model.encode([query])
    distances, indices = index.search(query_embedding, top_k)
    return [(corpus[i], float(distances[0][idx])) for idx, i in enumerate(indices[0])]

def text_pipeline(text, target_code):
    detected_lang = detect_language(text)
    src_nllb = xlm_to_nllb.get(detected_lang, "eng_Latn")
    translated = translate(text, src_nllb, target_code)
    semantic_results = search_semantic(translated)
    matches = "\n".join([f"{i+1}. {txt} (Score: {score:.2f})" for i, (txt, score) in enumerate(semantic_results)])
    return detected_lang, translated, matches

def voice_pipeline(audio_path, target_code):
    model = whisper.load_model("base")
    result = model.transcribe(audio_path)
    input_text = result["text"]
    detected_lang = detect_language(input_text)
    src_nllb = xlm_to_nllb.get(detected_lang, "eng_Latn")
    translated = translate(input_text, src_nllb, target_code)
    semantic_results = search_semantic(translated)
    matches = "\n".join([f"{i+1}. {txt} (Score: {score:.2f})" for i, (txt, score) in enumerate(semantic_results)])
    return input_text, detected_lang, translated, matches

# Gradio Interfaces
voice_tab = gr.Interface(
    fn=voice_pipeline,
    inputs=[
        gr.Audio(source="microphone", type="filepath", label="๐ŸŽ™๏ธ Speak Something"),
        gr.Dropdown(lang_options, value="san_Deva", label="๐ŸŒ Target Language"),
    ],
    outputs=[
        gr.Textbox(label="๐Ÿ“ Detected Text"),
        gr.Textbox(label="๐ŸŒ Detected Language"),
        gr.Textbox(label="๐Ÿ—ฃ๏ธ Translated Output"),
        gr.Textbox(label="๐Ÿง  Semantic Matches"),
    ]
)

text_tab = gr.Interface(
    fn=text_pipeline,
    inputs=[
        gr.Textbox(label="๐Ÿ“ Enter your sentence"),
        gr.Dropdown(lang_options, value="san_Deva", label="๐ŸŒ Target Language")
    ],
    outputs=[
        gr.Textbox(label="๐ŸŒ Detected Language"),
        gr.Textbox(label="๐Ÿ—ฃ๏ธ Translated Output"),
        gr.Textbox(label="๐Ÿง  Semantic Matches")
    ]
)

gr.TabbedInterface([voice_tab, text_tab], ["๐ŸŽค Voice Input", "๐Ÿ“ Text Input"]).launch()