Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification, AutoModelForSeq2SeqLM
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
import gradio as gr
|
6 |
+
import faiss
|
7 |
+
import numpy as np
|
8 |
+
|
9 |
+
# Load models
|
10 |
+
lang_detect_model = AutoModelForSequenceClassification.from_pretrained("papluca/xlm-roberta-base-language-detection")
|
11 |
+
lang_detect_tokenizer = AutoTokenizer.from_pretrained("papluca/xlm-roberta-base-language-detection")
|
12 |
+
trans_model = AutoModelForSeq2SeqLM.from_pretrained("facebook/nllb-200-distilled-600M")
|
13 |
+
trans_tokenizer = AutoTokenizer.from_pretrained("facebook/nllb-200-distilled-600M")
|
14 |
+
embed_model = SentenceTransformer("sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2")
|
15 |
+
|
16 |
+
# Language mappings
|
17 |
+
id2lang = lang_detect_model.config.id2label
|
18 |
+
xlm_to_nllb = {
|
19 |
+
"en": "eng_Latn", "fr": "fra_Latn", "hi": "hin_Deva", "es": "spa_Latn", "de": "deu_Latn",
|
20 |
+
"ta": "tam_Taml", "te": "tel_Telu", "ja": "jpn_Jpan", "zh": "zho_Hans", "ar": "arb_Arab",
|
21 |
+
"sa": "san_Deva"
|
22 |
+
}
|
23 |
+
nllb_langs = {
|
24 |
+
"eng_Latn": "English", "fra_Latn": "French", "hin_Deva": "Hindi",
|
25 |
+
"spa_Latn": "Spanish", "deu_Latn": "German", "tam_Taml": "Tamil",
|
26 |
+
"tel_Telu": "Telugu", "jpn_Jpan": "Japanese", "zho_Hans": "Chinese",
|
27 |
+
"arb_Arab": "Arabic", "san_Deva": "Sanskrit"
|
28 |
+
}
|
29 |
+
|
30 |
+
# Sample knowledge corpus
|
31 |
+
corpus = [
|
32 |
+
"धर्म एव हतो हन्ति धर्मो रक्षति रक्षितः",
|
33 |
+
"Dharma when destroyed, destroys; when protected, protects.",
|
34 |
+
"The moon affects tides and mood, according to Jyotisha",
|
35 |
+
"One should eat according to the season – Rituacharya",
|
36 |
+
"Balance of Tridosha is health – Ayurveda principle",
|
37 |
+
"Ethics in Mahabharata reflect situational dharma",
|
38 |
+
"Meditation improves memory and mental clarity",
|
39 |
+
"Jyotisha links planetary motion with life patterns"
|
40 |
+
]
|
41 |
+
|
42 |
+
# Semantic index
|
43 |
+
corpus_embeddings = embed_model.encode(corpus, convert_to_numpy=True)
|
44 |
+
dimension = corpus_embeddings.shape[1]
|
45 |
+
index = faiss.IndexFlatL2(dimension)
|
46 |
+
index.add(corpus_embeddings)
|
47 |
+
|
48 |
+
# Language Detection
|
49 |
+
def detect_language(text):
|
50 |
+
inputs = lang_detect_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
51 |
+
with torch.no_grad():
|
52 |
+
outputs = lang_detect_model(**inputs)
|
53 |
+
probs = F.softmax(outputs.logits, dim=1)
|
54 |
+
pred = torch.argmax(probs, dim=1).item()
|
55 |
+
return id2lang[pred]
|
56 |
+
|
57 |
+
# Translation
|
58 |
+
def translate(text, src_code, tgt_code):
|
59 |
+
trans_tokenizer.src_lang = src_code
|
60 |
+
encoded = trans_tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
61 |
+
target_lang_id = trans_tokenizer.convert_tokens_to_ids([tgt_code])[0]
|
62 |
+
generated = trans_model.generate(**encoded, forced_bos_token_id=target_lang_id)
|
63 |
+
return trans_tokenizer.decode(generated[0], skip_special_tokens=True)
|
64 |
+
|
65 |
+
# Semantic Search
|
66 |
+
def search_semantic(query, top_k=3):
|
67 |
+
query_embedding = embed_model.encode([query])
|
68 |
+
distances, indices = index.search(query_embedding, top_k)
|
69 |
+
results = []
|
70 |
+
for i, idx in enumerate(indices[0]):
|
71 |
+
results.append(f"{i+1}. {corpus[idx]} (Score: {distances[0][i]:.2f})")
|
72 |
+
return "\n".join(results)
|
73 |
+
|
74 |
+
# Main function
|
75 |
+
def pipeline(text, target_lang_code):
|
76 |
+
if not text.strip():
|
77 |
+
return "Empty input", "", "", ""
|
78 |
+
detected = detect_language(text)
|
79 |
+
src_code = xlm_to_nllb.get(detected, "eng_Latn")
|
80 |
+
translated = translate(text, src_code, target_lang_code)
|
81 |
+
matches = search_semantic(translated)
|
82 |
+
return text, detected, translated, matches
|
83 |
+
|
84 |
+
# Language Dropdown
|
85 |
+
lang_choices = list(nllb_langs.keys())
|
86 |
+
|
87 |
+
# Gradio UI
|
88 |
+
iface = gr.Interface(
|
89 |
+
fn=pipeline,
|
90 |
+
inputs=[
|
91 |
+
gr.Textbox(label="Enter your sentence"),
|
92 |
+
gr.Dropdown(choices=lang_choices, value="san_Deva", label="Target Language")
|
93 |
+
],
|
94 |
+
outputs=[
|
95 |
+
gr.Textbox(label="Input"),
|
96 |
+
gr.Textbox(label="Detected Language"),
|
97 |
+
gr.Textbox(label="Translated Output"),
|
98 |
+
gr.Textbox(label="Semantic Matches")
|
99 |
+
],
|
100 |
+
title="🌍 Sanskrit Translator + Semantic Search"
|
101 |
+
)
|
102 |
+
|
103 |
+
iface.launch()
|