NadaAljohani commited on
Commit
2d12348
·
verified ·
1 Parent(s): 680289a

Upload final_project (2).py

Browse files
Files changed (1) hide show
  1. final_project (2).py +213 -0
final_project (2).py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """Final_Project
3
+
4
+ Automatically generated by Colab.
5
+
6
+ Original file is located at
7
+ https://colab.research.google.com/drive/1tj74iJmEDRLjGb_MzT-oLcMF4H7uy3M-
8
+
9
+ ### **Packages:**
10
+ """
11
+
12
+ !pip install transformers
13
+ !pip install gradio
14
+ !pip install torch
15
+ !pip install datasets
16
+ !pip install diffusers
17
+ !pip install diffusers transformers
18
+
19
+ from transformers import pipeline
20
+ from datasets import load_dataset
21
+ import gradio as gr
22
+ import torch
23
+ from diffusers import DiffusionPipeline
24
+
25
+ """### **Arabic: Text-Generation:**
26
+ Generate a poetry in Arabic.
27
+ """
28
+
29
+ pipe_ar = pipeline('text-generation', framework='pt', model='akhooli/ap2023', tokenizer='akhooli/ap2023')
30
+
31
+ """### **English: Text-Generation:**
32
+ Generate a poetry in English.
33
+ """
34
+
35
+ pipe_en = pipeline("text-generation", model="ashiqabdulkhader/GPT2-Poet")
36
+
37
+ """### **Arabic and English: Text-To-Speech:**
38
+ Convert the Arabic/English poetry to speech.
39
+ """
40
+
41
+ # Initialize text-to-speech models for Arabic and English
42
+ # Arabic: text-to-speech
43
+ synthesiser_arabic = pipeline("text-to-speech", model="MBZUAI/speecht5_tts_clartts_ar")
44
+ embeddings_dataset_arabic = load_dataset("herwoww/arabic_xvector_embeddings", split="validation")
45
+ speaker_embedding_arabic = torch.tensor(embeddings_dataset_arabic[105]["speaker_embeddings"]).unsqueeze(0)
46
+
47
+ # English: text-to-speech
48
+ synthesiser_english = pipeline("text-to-speech", model="microsoft/speecht5_tts")
49
+ embeddings_dataset_english = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
50
+ speaker_embedding_english = torch.tensor(embeddings_dataset_english[7306]["xvector"]).unsqueeze(0)
51
+
52
+ """### **English Text-To-Image:**
53
+ convert the starter of the English poetry to an image.
54
+ """
55
+
56
+ pipe_image = DiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
57
+
58
+ """### **Translator from Arabic to English:**
59
+ The text-to-image model dosn't support Arabic, therefore we need to translate the starter of the Arabic poetry to English in order to generate image.
60
+ """
61
+
62
+ pipe_translator = pipeline("translation", model="Helsinki-NLP/opus-mt-ar-en")
63
+
64
+ """### **Primary Function:**
65
+ This function will recives 2 inputs from the gradio interface, and excute the thollowing function and retrun 3 outputs:
66
+ 1. The generted poem.
67
+ 2. The aduio.
68
+ 3. The image.
69
+ """
70
+
71
+ # Generate poem based on language and convert it to audio and image
72
+ def generate_poem(selected_language, text):
73
+ if selected_language == "English":
74
+ poem = generate_poem_english(text) #retrun the generated poem from the generate_poem_english function
75
+ sampling_rate, audio_data = text_to_speech_english(poem) #return the audio from the text_to_speech_english function
76
+ # image = generate_image_from_poem(text) #return the image from the generate_image_from_poem function
77
+ elif selected_language == "Arabic":
78
+ poem = generate_poem_arabic(text) #retrun the generated poem from the generate_poem_arabic function
79
+ sampling_rate, audio_data = text_to_speech_arabic(poem) #return the audio from the text_to_speech_arabic function
80
+ translated_text = translate_arabic_to_english(text) #return the translated poem from arabic to englsih, using translate_arabic_to_english function
81
+ # image = generate_image_from_poem(translated_text) #return the image from the generate_image_from_poem function
82
+
83
+ return poem, (sampling_rate, audio_data)
84
+ # , image
85
+
86
+ """### **Poem Generation Function:**
87
+ This function is responsible for generating a poem (text) in Arabic or English, based on the provided text.
88
+ """
89
+
90
+ # Poem generation for Arabic
91
+ def generate_poem_arabic(text):
92
+ generated_text = pipe_ar(text, max_length=96, do_sample=True, temperature=temp, top_k=topk, top_p=topp, repetition_penalty=penalty,
93
+ min_length = 64, no_repeat_ngram_size = 3, return_full_text=True,
94
+ num_beams=5, num_return_sequences=1)[0]["generated_text"]
95
+ clean_text = generated_text.replace("-", "") #To get rid of the dashs generated by the model.
96
+ return clean_text
97
+
98
+ # Poem generation for English
99
+ def generate_poem_english(text):
100
+ generated_text = pipe_en(text, do_sample=True, max_length=100, top_k=0, top_p=0.9, temperature=1.0, num_return_sequences=3,)[0]['generated_text']
101
+ clean_text = generated_text.replace("</s>", "") #To get rid of the </s> generated by the model.
102
+ return clean_text
103
+
104
+ """### **ِAduio Function:**
105
+ This function is responsible for generating an audio in Arabic or English, based on the provided text.
106
+ """
107
+
108
+ # Text-to-speech conversion for Arabic
109
+ def text_to_speech_arabic(text):
110
+ speech = synthesiser_arabic(text, forward_params={"speaker_embeddings": speaker_embedding_arabic})
111
+ audio_data = speech["audio"]
112
+ sampling_rate = speech["sampling_rate"]
113
+ return (sampling_rate, audio_data)
114
+
115
+ # Text-to-speech conversion for English
116
+ def text_to_speech_english(text):
117
+ speech = synthesiser_english(text, forward_params={"speaker_embeddings": speaker_embedding_english})
118
+ audio_data = speech["audio"]
119
+ sampling_rate = speech["sampling_rate"]
120
+ return (sampling_rate, audio_data)
121
+
122
+ """### **Image Function:**
123
+ This function is responsible for generating an image based on the provided text.
124
+ """
125
+
126
+ #Image Function
127
+ def generate_image_from_poem(poem_text):
128
+ image = pipe_image(poem_text).images[0]
129
+ return image
130
+
131
+ """### **Translation Function:**
132
+ This function is responsible for translating the Arabic input to English, to be used for the image function, which accept only english inputs.
133
+ """
134
+
135
+ #Translation Function from Arabic to English
136
+ def translate_arabic_to_english(text):
137
+ translated_text = pipe_translator(text)[0]['translation_text']
138
+ return translated_text
139
+
140
+ """### **CSS Styling:**"""
141
+
142
+ custom_css = """
143
+ body {
144
+ background-color: #f4f4f9;
145
+ color: #333;
146
+ }
147
+ .gradio-container {
148
+ border-radius: 10px;
149
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
150
+ background-color: #fff;
151
+ }
152
+ label {
153
+ color: #4A90E2;
154
+ font-weight: bold;
155
+ }
156
+
157
+ input[type="text"],
158
+ textarea {
159
+ border: 1px solid #4A90E2;
160
+ }
161
+ textarea {
162
+ height: 150px;
163
+ }
164
+
165
+ button {
166
+ background-color: #4A90E2;
167
+ color: #fff;
168
+ border-radius: 5px;
169
+ cursor: pointer;
170
+ }
171
+ button:hover {
172
+ background-color: #357ABD;
173
+ }
174
+
175
+ .dropdown {
176
+ border: 1px solid #4A90E2;
177
+ border-radius: 4px;
178
+ }
179
+
180
+ """
181
+
182
+ """### **Examples for Gradio:**
183
+ Provide 4 predefined inputs to demonstrate how the interface works.
184
+ """
185
+
186
+ examples = [
187
+ #First parameter is for the dropdown menu, and the second parameter is for the starter of the poem
188
+ ["English", "The shining sun rises over the calm ocean"],
189
+ ["Arabic", "الورود تتفتح في الربيع"],
190
+ ["English", "The night sky is filled with stars and dreams"],
191
+ ["Arabic", "اشعة الشمس المشرقة"]
192
+ ]
193
+
194
+ """### **Gradio Interface:**
195
+ Creating a Gradio interface to generate a poem, reading the poem, and generate an image based on that poem.
196
+ """
197
+
198
+ my_model = gr.Interface(
199
+ fn=generate_poem, #The primary function that will recives the inputs (language and the starter of the poem)
200
+ inputs=[
201
+ gr.Dropdown(["English", "Arabic"], label="Select Language"), #Dropdown menu to select the language, either "English" or "Arabic" for the poem
202
+ gr.Textbox(label="Enter a sentence")], #Textbox where the user will input a sentence or phrase to generate the poem (starter of the peom)
203
+
204
+ outputs=[
205
+ gr.Textbox(label="Generated Poem", lines=10), # Textbox to display the generated poem
206
+ gr.Audio(label="Generated Audio", type="numpy") #Audio output for the generated poem
207
+ # gr.Image(label="Generated Image")
208
+ ], #Display an image generated from the starter of the peom
209
+
210
+ examples=examples, #Predefined examples to guide the user how to use the interface
211
+ css=custom_css #Applying CSS Custeom
212
+ )
213
+ my_model.launch()