VDNT11 commited on
Commit
059ddc0
·
verified ·
1 Parent(s): 2f388b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -131
app.py CHANGED
@@ -8,151 +8,80 @@ from gtts import gTTS
8
  import soundfile as sf
9
  from transformers import VitsTokenizer, VitsModel, set_seed
10
 
11
- # Clone and Install IndicTransToolkit repository
12
- if not os.path.exists('IndicTransToolkit'):
13
- os.system('git clone https://github.com/VarunGumma/IndicTransToolkit')
14
- os.system('cd IndicTransToolkit && python3 -m pip install --editable ./')
15
 
16
- # Initialize BLIP for image captioning
17
- blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
18
- blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to("cuda" if torch.cuda.is_available() else "cpu")
19
 
20
- # Function to generate captions
21
- def generate_caption(image_path):
22
- image = Image.open(image_path).convert("RGB")
23
- inputs = blip_processor(image, "image of", return_tensors="pt").to("cuda" if torch.cuda.is_available() else "cpu")
24
- with torch.no_grad():
25
- generated_ids = blip_model.generate(**inputs)
26
- caption = blip_processor.decode(generated_ids[0], skip_special_tokens=True)
27
- return caption
28
 
29
- # Function for translation using IndicTrans2
30
- def translate_caption(caption, target_languages):
31
- # Load model and tokenizer
32
- model_name = "ai4bharat/indictrans2-en-indic-1B"
33
- tokenizer_IT2 = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
34
- model_IT2 = AutoModelForSeq2SeqLM.from_pretrained(model_name, trust_remote_code=True)
35
- model_IT2 = torch.quantization.quantize_dynamic(
36
- model_IT2, {torch.nn.Linear}, dtype=torch.qint8
37
- )
38
-
39
- ip = IndicProcessor(inference=True)
40
-
41
- # Source language (English)
42
- src_lang = "eng_Latn"
43
- DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
44
- model_IT2.to(DEVICE) # Move model to the device
45
-
46
- # Integrating with workflow now
47
- input_sentences = [caption]
48
- translations = {}
49
-
50
- for tgt_lang in target_languages:
51
- # Preprocess input sentences
52
- batch = ip.preprocess_batch(input_sentences, src_lang=src_lang, tgt_lang=tgt_lang)
53
-
54
- # Tokenize the sentences and generate input encodings
55
- inputs = tokenizer_IT2(batch, truncation=True, padding="longest", return_tensors="pt").to(DEVICE)
56
-
57
- # Generate translations using the model
58
  with torch.no_grad():
59
- generated_tokens = model_IT2.generate(
60
- **inputs,
61
- use_cache=True,
62
- min_length=0,
63
- max_length=256,
64
- num_beams=5,
65
- num_return_sequences=1,
66
- )
67
-
68
- # Decode the generated tokens into text
69
- with tokenizer_IT2.as_target_tokenizer():
70
- generated_tokens = tokenizer_IT2.batch_decode(generated_tokens.detach().cpu().tolist(), skip_special_tokens=True, clean_up_tokenization_spaces=True)
71
-
72
- # Postprocess the translations
73
- translated_texts = ip.postprocess_batch(generated_tokens, lang=tgt_lang)
74
- translations[tgt_lang] = translated_texts[0]
75
-
76
- return translations
77
-
78
- # Function to generate audio using gTTS
79
- def generate_audio_gtts(text, lang_code, output_file):
80
- tts = gTTS(text=text, lang=lang_code)
81
- tts.save(output_file)
82
- return output_file
83
-
84
- # Function to generate audio using Facebook MMS-TTS
85
- def generate_audio_fbmms(text, model_name, output_file):
86
- tokenizer = VitsTokenizer.from_pretrained(model_name)
87
- model = VitsModel.from_pretrained(model_name)
88
- inputs = tokenizer(text=text, return_tensors="pt")
89
- set_seed(555)
90
- with torch.no_grad():
91
- outputs = model(**inputs)
92
- waveform = outputs.waveform[0].cpu().numpy()
93
- sf.write(output_file, waveform, samplerate=model.config.sampling_rate)
94
- return output_file
95
-
96
- # Streamlit UI
97
- st.title("Multilingual Assistive Model")
98
-
99
- uploaded_image = st.file_uploader("Upload an Image", type=["jpg", "jpeg", "png"])
100
-
101
- if uploaded_image is not None:
102
- # Display the uploaded image
103
- image = Image.open(uploaded_image)
104
- st.image(image, caption="Uploaded Image", use_column_width=True)
105
-
106
- # Generate Caption
107
- st.write("Generating Caption...")
108
- caption = generate_caption(uploaded_image)
109
- st.write(f"Caption: {caption}")
110
 
111
- # Select target languages for translation
112
  language_options = {
113
  "hin_Deva": "Hindi (Devanagari)",
114
  "mar_Deva": "Marathi (Devanagari)",
115
- "guj_Gujr": "Gujarati (Gujrati)",
116
- "urd_Arab": "Urdu (Arabic)",
117
  }
118
-
119
  target_languages = st.multiselect(
120
- "Select target languages for translation",
121
- list(language_options.keys()),
122
- ["hin_Deva", "mar_Deva"]
123
  )
124
 
125
- # Generate Translations
126
- if target_languages:
127
- st.write("Translating Caption...")
128
- translations = translate_caption(caption, target_languages)
129
- st.write("Translations:")
130
  for lang in target_languages:
131
- st.write(f"{language_options[lang]}: {translations[lang]}")
132
-
133
- # Select audio generation method
134
- audio_method = st.radio("Choose Audio Generation Method", ("gTTS (Default)", "Facebook MMS-TTS"))
135
-
136
- # Generate audio for each target language
137
- for lang in target_languages:
138
- st.write(f"Generating audio for {language_options[lang]}...")
139
-
140
- lang_code = {
141
- "hin_Deva": "hi", # Hindi
142
- "mar_Deva": "mr", # Marathi
143
- "guj_Gujr": "gu", # Gujarati
144
- "urd_Arab": "ur" # Urdu
145
- }.get(lang, "en")
146
-
147
  output_file = f"{lang}_audio.mp3"
148
 
149
- if audio_method == "gTTS (Default)":
 
 
 
 
 
 
150
  audio_file = generate_audio_gtts(translations[lang], lang_code, output_file)
151
  else:
152
- model_name = "your_facebook_mms_model_name" # Update this to the correct model name
153
- audio_file = generate_audio_fbmms(translations[lang], model_name, output_file)
154
-
155
- st.write(f"Playing {language_options[lang]} audio:")
156
- st.audio(audio_file)
157
- else:
158
- st.write("Upload an image to start.")
 
8
  import soundfile as sf
9
  from transformers import VitsTokenizer, VitsModel, set_seed
10
 
11
+ # Set Hugging Face token (via environment or user input)
12
+ hf_token = st.text_input("Enter your Hugging Face API token", type="password")
 
 
13
 
14
+ # Ensure token is provided
15
+ if hf_token:
 
16
 
17
+ # Initialize BLIP for image captioning
18
+ blip_processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
19
+ blip_model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to("cuda" if torch.cuda.is_available() else "cpu")
 
 
 
 
 
20
 
21
+ # Function to generate captions
22
+ def generate_caption(image_path):
23
+ image = Image.open(image_path).convert("RGB")
24
+ inputs = blip_processor(image, "image of", return_tensors="pt").to("cuda" if torch.cuda.is_available() else "cpu")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  with torch.no_grad():
26
+ generated_ids = blip_model.generate(**inputs)
27
+ caption = blip_processor.decode(generated_ids[0], skip_special_tokens=True)
28
+ return caption
29
+
30
+ # Function to load FB MMS TTS model with Hugging Face token
31
+ def load_fbmms_model(model_name, hf_token):
32
+ tokenizer = VitsTokenizer.from_pretrained(model_name, use_auth_token=hf_token)
33
+ model = VitsModel.from_pretrained(model_name, use_auth_token=hf_token)
34
+ return tokenizer, model
35
+
36
+ # Function to generate audio using Facebook MMS-TTS
37
+ def generate_audio_fbmms(text, model_name, hf_token, output_file):
38
+ tokenizer, model = load_fbmms_model(model_name, hf_token)
39
+ inputs = tokenizer(text=text, return_tensors="pt")
40
+ set_seed(555)
41
+ with torch.no_grad():
42
+ outputs = model(**inputs)
43
+ waveform = outputs.waveform[0].cpu().numpy()
44
+ sf.write(output_file, waveform, samplerate=model.config.sampling_rate)
45
+ return output_file
46
+
47
+ # Streamlit UI for TTS method
48
+ tts_method = st.selectbox(
49
+ "Choose Text-to-Speech Method",
50
+ options=["gTTS (Google)", "Facebook MMS TTS"],
51
+ index=0 # Default to gTTS
52
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
+ # Select target languages with human-readable names
55
  language_options = {
56
  "hin_Deva": "Hindi (Devanagari)",
57
  "mar_Deva": "Marathi (Devanagari)",
58
+ "guj_Gujr": "Gujarati (Gujarati)",
59
+ "urd_Arab": "Urdu (Arabic)"
60
  }
61
+
62
  target_languages = st.multiselect(
63
+ "Select target languages for translation",
64
+ options=list(language_options.keys()),
65
+ format_func=lambda x: language_options[x]
66
  )
67
 
68
+ if uploaded_image is not None and target_languages:
69
+ caption = generate_caption(uploaded_image)
 
 
 
70
  for lang in target_languages:
71
+ st.write(f"Generating audio for {lang}...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  output_file = f"{lang}_audio.mp3"
73
 
74
+ if tts_method == "gTTS (Google)":
75
+ lang_code = {
76
+ "hin_Deva": "hi",
77
+ "mar_Deva": "mr",
78
+ "guj_Gujr": "gu",
79
+ "urd_Arab": "ur"
80
+ }.get(lang, "en")
81
  audio_file = generate_audio_gtts(translations[lang], lang_code, output_file)
82
  else:
83
+ model_name = f"facebook/mms-tts-{lang}"
84
+ audio_file = generate_audio_fbmms(translations[lang], model_name, hf_token, output_file)
85
+
86
+ if audio_file:
87
+ st.audio(audio_file)