Rakesh2205 commited on
Commit
f0b25f8
·
verified ·
1 Parent(s): c740f15

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +208 -0
app.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM, AutoModelForSeq2SeqLM
3
+ import torch
4
+ import numpy as np
5
+
6
+ # Initialize models
7
+ try:
8
+ # Text Generation with TinyLlama
9
+ generator_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
10
+ tokenizer = AutoTokenizer.from_pretrained(generator_name)
11
+ generator_model = AutoModelForCausalLM.from_pretrained(
12
+ generator_name,
13
+ torch_dtype=torch.float16,
14
+ device_map="auto"
15
+ )
16
+
17
+ # Text Summarization
18
+ summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
19
+
20
+ # Sentiment Analysis
21
+ sentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")
22
+
23
+ # Question Answering
24
+ qa_model = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
25
+
26
+ # Translation (English to multiple languages)
27
+ translator = pipeline("translation", model="Helsinki-NLP/opus-mt-en-ROMANCE")
28
+
29
+ except Exception as e:
30
+ print(f"Error loading models: {str(e)}")
31
+
32
+ def generate_text(prompt, max_length=100, temperature=0.7):
33
+ """Generate text based on a prompt using TinyLlama"""
34
+ try:
35
+ # Format the prompt for chat
36
+ formatted_prompt = f"<human>: {prompt}\n<assistant>:"
37
+
38
+ # Generate text
39
+ inputs = tokenizer(formatted_prompt, return_tensors="pt").to(generator_model.device)
40
+ outputs = generator_model.generate(
41
+ **inputs,
42
+ max_length=max_length,
43
+ temperature=temperature,
44
+ do_sample=True,
45
+ top_p=0.95,
46
+ top_k=50,
47
+ repetition_penalty=1.2,
48
+ num_return_sequences=1,
49
+ pad_token_id=tokenizer.eos_token_id
50
+ )
51
+
52
+ # Decode and clean up the response
53
+ generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
54
+ # Remove the original prompt and clean up
55
+ response = generated_text.split("<assistant>:")[-1].strip()
56
+ return response
57
+ except Exception as e:
58
+ return f"Error in text generation: {str(e)}"
59
+
60
+ def summarize_text(text, max_length=130, min_length=30):
61
+ """Summarize long text"""
62
+ try:
63
+ summary = summarizer(
64
+ text,
65
+ max_length=max_length,
66
+ min_length=min_length,
67
+ do_sample=False
68
+ )
69
+ return summary[0]['summary_text']
70
+ except Exception as e:
71
+ return f"Error in summarization: {str(e)}"
72
+
73
+ def analyze_sentiment(text):
74
+ """Analyze sentiment of text"""
75
+ try:
76
+ result = sentiment_analyzer(text)
77
+ return {
78
+ "Sentiment": result[0]['label'],
79
+ "Confidence": f"{result[0]['score']:.2%}"
80
+ }
81
+ except Exception as e:
82
+ return {"error": str(e)}
83
+
84
+ def answer_question(context, question):
85
+ """Answer questions based on context"""
86
+ try:
87
+ result = qa_model(
88
+ question=question,
89
+ context=context
90
+ )
91
+ return {
92
+ "Answer": result['answer'],
93
+ "Confidence": f"{result['score']:.2%}"
94
+ }
95
+ except Exception as e:
96
+ return {"error": str(e)}
97
+
98
+ def translate_text(text, target_lang):
99
+ """Translate text to target language"""
100
+ try:
101
+ translation = translator(
102
+ text,
103
+ src_lang="en",
104
+ tgt_lang=target_lang
105
+ )
106
+ return translation[0]['translation_text']
107
+ except Exception as e:
108
+ return f"Error in translation: {str(e)}"
109
+
110
+ # Create the Gradio interface
111
+ with gr.Blocks(title="Advanced NLP") as demo:
112
+ gr.Markdown("""
113
+ # 🤖 Advanced NLP
114
+ ## Multi-task Language Model Application
115
+
116
+ This application demonstrates various Natural Language Processing capabilities:
117
+ - Text Generation (TinyLlama)
118
+ - Text Summarization (BART)
119
+ - Sentiment Analysis (DistilBERT)
120
+ - Question Answering
121
+ - Multi-language Translation
122
+
123
+ Try out different tasks using the options below!
124
+ """)
125
+
126
+ with gr.Tab("Text Generation"):
127
+ with gr.Row():
128
+ with gr.Column():
129
+ gen_input = gr.Textbox(label="Enter your prompt", lines=3)
130
+ gen_length = gr.Slider(minimum=10, maximum=200, value=100, step=10, label="Maximum Length")
131
+ gen_temp = gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature")
132
+ gen_button = gr.Button("Generate")
133
+ with gr.Column():
134
+ gen_output = gr.Textbox(label="Generated Text", lines=5)
135
+
136
+ with gr.Tab("Text Summarization"):
137
+ with gr.Row():
138
+ with gr.Column():
139
+ sum_input = gr.Textbox(label="Enter text to summarize", lines=8)
140
+ sum_max_length = gr.Slider(minimum=50, maximum=200, value=130, step=10, label="Maximum Summary Length")
141
+ sum_min_length = gr.Slider(minimum=10, maximum=100, value=30, step=5, label="Minimum Summary Length")
142
+ sum_button = gr.Button("Summarize")
143
+ with gr.Column():
144
+ sum_output = gr.Textbox(label="Summary", lines=4)
145
+
146
+ with gr.Tab("Sentiment Analysis"):
147
+ with gr.Row():
148
+ with gr.Column():
149
+ sent_input = gr.Textbox(label="Enter text for sentiment analysis", lines=3)
150
+ sent_button = gr.Button("Analyze Sentiment")
151
+ with gr.Column():
152
+ sent_output = gr.JSON(label="Sentiment Analysis Results")
153
+
154
+ with gr.Tab("Question Answering"):
155
+ with gr.Row():
156
+ with gr.Column():
157
+ qa_context = gr.Textbox(label="Enter the context", lines=6)
158
+ qa_question = gr.Textbox(label="Enter your question", lines=2)
159
+ qa_button = gr.Button("Get Answer")
160
+ with gr.Column():
161
+ qa_output = gr.JSON(label="Answer")
162
+
163
+ with gr.Tab("Translation"):
164
+ with gr.Row():
165
+ with gr.Column():
166
+ trans_input = gr.Textbox(label="Enter text to translate (English)", lines=3)
167
+ trans_lang = gr.Dropdown(
168
+ choices=["es", "fr", "it", "pt", "ro"],
169
+ value="es",
170
+ label="Target Language"
171
+ )
172
+ trans_button = gr.Button("Translate")
173
+ with gr.Column():
174
+ trans_output = gr.Textbox(label="Translated Text", lines=3)
175
+
176
+ # Set up event handlers
177
+ gen_button.click(
178
+ fn=generate_text,
179
+ inputs=[gen_input, gen_length, gen_temp],
180
+ outputs=gen_output
181
+ )
182
+
183
+ sum_button.click(
184
+ fn=summarize_text,
185
+ inputs=[sum_input, sum_max_length, sum_min_length],
186
+ outputs=sum_output
187
+ )
188
+
189
+ sent_button.click(
190
+ fn=analyze_sentiment,
191
+ inputs=sent_input,
192
+ outputs=sent_output
193
+ )
194
+
195
+ qa_button.click(
196
+ fn=answer_question,
197
+ inputs=[qa_context, qa_question],
198
+ outputs=qa_output
199
+ )
200
+
201
+ trans_button.click(
202
+ fn=translate_text,
203
+ inputs=[trans_input, trans_lang],
204
+ outputs=trans_output
205
+ )
206
+
207
+ if __name__ == "__main__":
208
+ demo.launch(share=True)