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IL import Image
|
| 4 |
+
import os
|
| 5 |
+
from transformers import BlipProcessor, BlipForConditionalGeneration, AutoModelForSeq2SeqLM, AutoTokenizer, VitsTokenizer, VitsModel, AutoModelForCausalLM, set_seed
|
| 6 |
+
from IndicTransToolkit import IndicProcessor
|
| 7 |
+
from gtts import gTTS
|
| 8 |
+
import soundfile as sf
|
| 9 |
+
from langchain_community.vectorstores import FAISS
|
| 10 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 11 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 12 |
+
from langchain.docstore.document import Document
|
| 13 |
+
import PyPDF2
|
| 14 |
+
import tempfile
|
| 15 |
+
from bitsandbytes import functional as F
|
| 16 |
+
import bitsandbytes as bnb
|
| 17 |
+
|
| 18 |
+
# Initialize BLIP for image captioning
|
| 19 |
+
blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-large")
|
| 20 |
+
blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-large").to("cuda" if torch.cuda.is_available() else "cpu")
|
| 21 |
+
|
| 22 |
+
# Initialize Mistral-7B for conversational tasks
|
| 23 |
+
mistral_model_name = "mistralai/Mixtral-8x7B-Instruct-v0.1"
|
| 24 |
+
mistral_tokenizer = AutoTokenizer.from_pretrained(mistral_model_name)
|
| 25 |
+
mistral_model = AutoModelForCausalLM.from_pretrained(
|
| 26 |
+
mistral_model_name,
|
| 27 |
+
load_in_4bit=True,
|
| 28 |
+
device_map="auto",
|
| 29 |
+
torch_dtype=torch.bfloat16
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# Initialize vector store and embeddings for RAG
|
| 33 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 34 |
+
vector_store = None
|
| 35 |
+
temp_dir = tempfile.mkdtemp()
|
| 36 |
+
|
| 37 |
+
def generate_caption(image):
|
| 38 |
+
image = image.convert("RGB")
|
| 39 |
+
inputs = blip_processor(image, "image of", return_tensors="pt").to("cuda" if torch.cuda.is_available() else "cpu")
|
| 40 |
+
with torch.no_grad():
|
| 41 |
+
generated_ids = blip_model.generate(**inputs)
|
| 42 |
+
caption = blip_processor.decode(generated_ids[0], skip_special_tokens=True)
|
| 43 |
+
return caption
|
| 44 |
+
|
| 45 |
+
def translate_caption(caption, target_languages):
|
| 46 |
+
model_name = "ai4bharat/indictrans2-en-indic-1B"
|
| 47 |
+
tokenizer_IT2 = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
| 48 |
+
model_IT2 = AutoModelForSeq2SeqLM.from_pretrained(model_name, trust_remote_code=True)
|
| 49 |
+
model_IT2 = torch.quantization.quantize_dynamic(model_IT2, {torch.nn.Linear}, dtype=torch.qint8)
|
| 50 |
+
ip = IndicProcessor(inference=True)
|
| 51 |
+
src_lang = "eng_Latn"
|
| 52 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 53 |
+
model_IT2.to(DEVICE)
|
| 54 |
+
input_sentences = [caption]
|
| 55 |
+
translations = {}
|
| 56 |
+
for tgt_lang in target_languages:
|
| 57 |
+
batch = ip.preprocess_batch(input_sentences, src_lang=src_lang, tgt_lang=tgt_lang)
|
| 58 |
+
inputs = tokenizer_IT2(batch, truncation=True, padding="longest", return_tensors="pt").to(DEVICE)
|
| 59 |
+
with torch.no_grad():
|
| 60 |
+
generated_tokens = model_IT2.generate(**inputs, use_cache=True, min_length=0, max_length=256, num_beams=5, num_return_sequences=1)
|
| 61 |
+
with tokenizer_IT2.as_target_tokenizer():
|
| 62 |
+
generated_tokens = tokenizer_IT2.batch_decode(generated_tokens.detach().cpu().tolist(), skip_special_tokens=True, clean_up_tokenization_spaces=True)
|
| 63 |
+
translated_texts = ip.postprocess_batch(generated_tokens, lang=tgt_lang)
|
| 64 |
+
translations[tgt_lang] = translated_texts[0]
|
| 65 |
+
return translations
|
| 66 |
+
|
| 67 |
+
def generate_audio_gtts(text, lang_code):
|
| 68 |
+
output_file = os.path.join(temp_dir, f"{lang_code}_gTTS.mp3")
|
| 69 |
+
tts = gTTS(text=text, lang=lang_code)
|
| 70 |
+
tts.save(output_file)
|
| 71 |
+
return output_file
|
| 72 |
+
|
| 73 |
+
def generate_audio_fbmms(text, model_name):
|
| 74 |
+
output_file = os.path.join(temp_dir, f"{model_name.split('/')[-1]}.wav")
|
| 75 |
+
tokenizer = VitsTokenizer.from_pretrained(model_name)
|
| 76 |
+
model = VitsModel.from_pretrained(model_name)
|
| 77 |
+
inputs = tokenizer(text=text, return_tensors="pt")
|
| 78 |
+
set_seed(555)
|
| 79 |
+
with torch.no_grad():
|
| 80 |
+
outputs = model(**inputs)
|
| 81 |
+
waveform = outputs.waveform[0].cpu().numpy()
|
| 82 |
+
sf.write(output_file, waveform, samplerate=model.config.sampling_rate)
|
| 83 |
+
return output_file
|
| 84 |
+
|
| 85 |
+
def process_document(file):
|
| 86 |
+
global vector_store
|
| 87 |
+
if file.name.endswith(".pdf"):
|
| 88 |
+
reader = PyPDF2.PdfReader(file)
|
| 89 |
+
text = ""
|
| 90 |
+
for page in reader.pages:
|
| 91 |
+
text += page.extract_text() or ""
|
| 92 |
+
else:
|
| 93 |
+
text = file.read().decode("utf-8")
|
| 94 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 95 |
+
chunks = text_splitter.split_text(text)
|
| 96 |
+
documents = [Document(page_content=chunk) for chunk in chunks]
|
| 97 |
+
vector_store = FAISS.from_documents(documents, embeddings)
|
| 98 |
+
vector_store.save_local(os.path.join(temp_dir, "faiss_index"))
|
| 99 |
+
return "Document processed and indexed successfully."
|
| 100 |
+
|
| 101 |
+
def chat_with_llm(message, history):
|
| 102 |
+
global vector_store
|
| 103 |
+
context = ""
|
| 104 |
+
if vector_store:
|
| 105 |
+
docs = vector_store.similarity_search(message, k=3)
|
| 106 |
+
context = "\n".join([doc.page_content for doc in docs])
|
| 107 |
+
prompt = f"[INST] You are a helpful assistant. Use the following context to answer the question accurately:\n\n{context}\n\nQuestion: {message} [/INST]"
|
| 108 |
+
inputs = mistral_tokenizer(prompt, return_tensors="pt").to("cuda" if torch.cuda.is_available() else "cpu")
|
| 109 |
+
with torch.no_grad():
|
| 110 |
+
outputs = mistral_model.generate(**inputs, max_length=1000, num_return_sequences=1, temperature=0.7)
|
| 111 |
+
response = mistral_tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 112 |
+
return response.replace(prompt, "").strip()
|
| 113 |
+
|
| 114 |
+
def image_tab(image, target_languages):
|
| 115 |
+
if not image:
|
| 116 |
+
return "Please upload an image.", {}, []
|
| 117 |
+
caption = generate_caption(image)
|
| 118 |
+
translations = translate_caption(caption, target_languages) if target_languages else {}
|
| 119 |
+
audio_files = []
|
| 120 |
+
for lang in target_languages:
|
| 121 |
+
lang_code = {"hin_Deva": "hi", "guj_Gujr": "gu", "urd_Arab": "ur"}.get(lang, "en")
|
| 122 |
+
audio_file = generate_audio_gtts(translations[lang], lang_code)
|
| 123 |
+
audio_files.append(audio_file)
|
| 124 |
+
return caption, translations, audio_files
|
| 125 |
+
|
| 126 |
+
with gr.Blocks() as demo:
|
| 127 |
+
gr.Markdown("# Multilingual Assistive Model")
|
| 128 |
+
with gr.Tabs():
|
| 129 |
+
with gr.TabItem("Image Processing"):
|
| 130 |
+
image_input = gr.Image(type="pil", label="Upload Image")
|
| 131 |
+
lang_select = gr.CheckboxGroup(["hin_Deva", "mar_Deva", "guj_Gujr", "urd_Arab"], label="Select Target Languages", value=["hin_Deva", "mar_Deva"])
|
| 132 |
+
process_btn = gr.Button("Process Image")
|
| 133 |
+
caption_output = gr.Textbox(label="Generated Caption")
|
| 134 |
+
translation_output = gr.JSON(label="Translations")
|
| 135 |
+
audio_output = gr.Files(label="Audio Files")
|
| 136 |
+
process_btn.click(image_tab, inputs=[image_input, lang_select], outputs=[caption_output, translation_output, audio_output])
|
| 137 |
+
with gr.TabItem("Document Upload"):
|
| 138 |
+
doc_input = gr.File(label="Upload Document (PDF or TXT)", file_types=[".pdf", ".txt"])
|
| 139 |
+
upload_btn = gr.Button("Process Document")
|
| 140 |
+
doc_status = gr.Textbox(label="Status")
|
| 141 |
+
upload_btn.click(process_document, inputs=doc_input, outputs=doc_status)
|
| 142 |
+
with gr.TabItem("Chat with LLM"):
|
| 143 |
+
chatbot = gr.Chatbot()
|
| 144 |
+
msg = gr.Textbox(label="Your Message")
|
| 145 |
+
clear = gr.Button("Clear")
|
| 146 |
+
msg.submit(chat_with_llm, inputs=[msg, chatbot], outputs=chatbot)
|
| 147 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 148 |
+
|
| 149 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==4.44.0
|
| 2 |
+
torch
|
| 3 |
+
transformers
|
| 4 |
+
Pillow
|
| 5 |
+
git+https://github.com/VarunGumma/IndicTransToolkit.git
|
| 6 |
+
gtts
|
| 7 |
+
soundfile
|
| 8 |
+
langchain
|
| 9 |
+
langchain-community
|
| 10 |
+
sentence-transformers
|
| 11 |
+
faiss-cpu
|
| 12 |
+
PyPDF2
|
| 13 |
+
bitsandbytes
|
| 14 |
+
numpy
|
| 15 |
+
pandas
|