GuidK commited on
Commit
2a296fb
·
verified ·
1 Parent(s): dba2bfc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -64
app.py CHANGED
@@ -28,7 +28,7 @@ def analyze_sentiment(text):
28
  if not text or not text.strip():
29
  return {"Error: Please enter text for analysis": 0.0}
30
 
31
- # Escape HTML tags (Protection against injections)
32
  safe_text = html_lib.escape(text)
33
 
34
  try:
@@ -37,6 +37,7 @@ def analyze_sentiment(text):
37
  # Return label and score as a dictionary
38
  return {result["label"]: result["score"]}
39
  except Exception as e:
 
40
  return {f"Processing Error: {str(e)[:100]}": 0.0}
41
 
42
  def summarize_text(text):
@@ -71,6 +72,7 @@ def summarize_text(text):
71
  summary = sum_tokenizer.decode(summary_ids[0], skip_special_tokens=True)
72
  return warning + summary
73
  except Exception as e:
 
74
  return f"Processing Error: {str(e)[:100]}"
75
 
76
  def translate_en_to_uk(text):
@@ -91,6 +93,7 @@ def translate_en_to_uk(text):
91
  # Decode translated tokens back to text
92
  return trans_tokenizer.decode(translated_ids[0], skip_special_tokens=True)
93
  except Exception as e:
 
94
  return f"Processing Error: {str(e)[:100]}"
95
 
96
  # Create Gradio blocks interface with a soft theme
@@ -101,79 +104,68 @@ with gr.Blocks(title="NLP Toolkit", theme=gr.themes.Soft()) as demo:
101
  # Add application description
102
  gr.Markdown('A comprehensive AI-powered tool that allows you to analyze text sentiment, generate short summaries for long articles, and translate text from English to Ukrainian.')
103
 
104
- # Create tabs
105
  with gr.Tabs():
106
  # Create Sentiment Analysis tab
107
  with gr.Tab("Sentiment Analysis"):
108
- # Create column layout
109
- with gr.Column():
110
- input_text = gr.Textbox(label="Input Text", lines=3, placeholder="Type something in English... (e.g., I absolutely love this product!)")
111
- output_label = gr.Label(label="Analysis Result")
112
- btn_sentiment = gr.Button("Analyze Sentiment", variant='primary')
113
- btn_sentiment.click(fn=analyze_sentiment, inputs=input_text, outputs=output_label)
114
-
115
- gr.Examples(
116
- examples=[
117
- ["I absolutely love this new update! It's fantastic."],
118
- ["I'm very disappointed with the service, it was terrible."],
119
- ["The weather today is completely ordinary."]
120
- ],
121
- inputs=input_text
122
- )
 
 
123
 
124
  # Create Summarization tab
125
  with gr.Tab("Summarization"):
126
- # Create column layout
127
- with gr.Column():
128
- input_long = gr.Textbox(label="Long Text (EN)", lines=6, placeholder="Paste a long English article to summarize here...")
129
- output_summary = gr.Textbox(label="Short Summary", lines=3)
130
- btn_summarize = gr.Button("Generate Summary", variant="primary")
131
- btn_summarize.click(fn=summarize_text, inputs=input_long, outputs=output_summary)
132
-
133
- examples = gr.Dataset(
134
- components=[input_long],
135
- samples=[
136
- ["Artificial intelligence is transforming healthcare and transportation."],
137
- ["The James Webb Space Telescope is the largest space telescope ever built."],
138
- ["Climate change is a long-term shift in global temperatures."]
139
  ],
140
- label="Examples"
141
- )
142
-
143
- examples.click(
144
- lambda x: x,
145
- inputs=[examples],
146
- outputs=[input_long]
147
- )
148
 
149
  # Create Translation tab
150
  with gr.Tab("Translation (EN -> UK)"):
151
- # Create column layout
152
- with gr.Column():
153
- input_trans = gr.Textbox(label="English Text", lines=4, placeholder="Enter text in English to translate into Ukrainian...")
154
- output_trans = gr.Textbox(label="Ukrainian Translation", lines=4)
155
- btn_translate = gr.Button("Translate to Ukrainian", variant="primary")
156
- btn_translate.click(fn=translate_en_to_uk, inputs=input_trans, outputs=output_trans)
157
-
158
- example1 = gr.Button("AI Example")
159
- example2 = gr.Button("Space Example")
160
- example3 = gr.Button("Climate Example")
161
-
162
- example1.click(
163
- fn=lambda: "Artificial intelligence is rapidly changing the world.",
164
- outputs=input_long
165
- )
166
-
167
- example2.click(
168
- fn=lambda: "I would like to order a cup of coffee, please.",
169
- outputs=input_long
170
- )
171
-
172
- example3.click(
173
- fn=lambda: "The results of the recent testing phase exceeded all our initial expectations.",
174
- outputs=input_long
175
- )
176
 
177
  if __name__ == "__main__":
178
- # Launch application with public share link
179
  demo.launch(debug=True)
 
28
  if not text or not text.strip():
29
  return {"Error: Please enter text for analysis": 0.0}
30
 
31
+ # Escape HTML tags to protect against injections
32
  safe_text = html_lib.escape(text)
33
 
34
  try:
 
37
  # Return label and score as a dictionary
38
  return {result["label"]: result["score"]}
39
  except Exception as e:
40
+ # Return processing error inside the result dictionary
41
  return {f"Processing Error: {str(e)[:100]}": 0.0}
42
 
43
  def summarize_text(text):
 
72
  summary = sum_tokenizer.decode(summary_ids[0], skip_special_tokens=True)
73
  return warning + summary
74
  except Exception as e:
75
+ # Return processing error as string
76
  return f"Processing Error: {str(e)[:100]}"
77
 
78
  def translate_en_to_uk(text):
 
93
  # Decode translated tokens back to text
94
  return trans_tokenizer.decode(translated_ids[0], skip_special_tokens=True)
95
  except Exception as e:
96
+ # Return processing error as string
97
  return f"Processing Error: {str(e)[:100]}"
98
 
99
  # Create Gradio blocks interface with a soft theme
 
104
  # Add application description
105
  gr.Markdown('A comprehensive AI-powered tool that allows you to analyze text sentiment, generate short summaries for long articles, and translate text from English to Ukrainian.')
106
 
107
+ # Create main tabs container
108
  with gr.Tabs():
109
  # Create Sentiment Analysis tab
110
  with gr.Tab("Sentiment Analysis"):
111
+ input_text = gr.Textbox(label="Input Text", lines=3, placeholder="Type something in English... (e.g., I absolutely love this product!)")
112
+ output_label = gr.Label(label="Analysis Result")
113
+ btn_sentiment = gr.Button("Analyze Sentiment", variant='primary')
114
+
115
+ # Link button click to sentiment analysis function
116
+ btn_sentiment.click(fn=analyze_sentiment, inputs=input_text, outputs=output_label)
117
+
118
+ # Configure examples for sentiment analysis tab
119
+ gr.Examples(
120
+ examples=[
121
+ ["I absolutely love this new update! It's fantastic."],
122
+ ["I'm very disappointed with the service, it was terrible."],
123
+ ["The weather today is completely ordinary."]
124
+ ],
125
+ inputs=input_text,
126
+ cache_examples=False
127
+ )
128
 
129
  # Create Summarization tab
130
  with gr.Tab("Summarization"):
131
+ input_long = gr.Textbox(label="Long Text (EN)", lines=6, placeholder="Paste a long English article to summarize here...")
132
+ output_summary = gr.Textbox(label="Short Summary", lines=3)
133
+ btn_summarize = gr.Button("Generate Summary", variant="primary")
134
+
135
+ # Link button click to summarization function
136
+ btn_summarize.click(fn=summarize_text, inputs=input_long, outputs=output_summary)
137
+
138
+ # Configure examples for summarization tab with formatting bug fixes
139
+ gr.Examples(
140
+ examples=[
141
+ ["Artificial intelligence (AI) has become a transformative force in modern society, influencing everything from healthcare to transportation. In the medical field, AI algorithms can analyze complex data to assist doctors in diagnosing diseases more accurately and quickly. For instance, machine learning models are trained on thousands of medical images to detect early signs of conditions like cancer. Meanwhile, in transportation, autonomous vehicles use AI to navigate roads, avoid obstacles, and reduce the likelihood of accidents caused by human error."],
142
+ ["The James Webb Space Telescope (JWST) is the largest and most powerful space science telescope ever built. Launched on December 25, 2021, it represents a major leap forward in our quest to understand the universe. Unlike its predecessor, the Hubble Space Telescope, which primarily observes visible light, the JWST is designed to detect infrared radiation. This capability allows it to peer through dense clouds of cosmic dust and observe the very first galaxies that formed after the Big Bang."],
143
+ ["Climate change is a long-term shift in global or regional climate patterns. Often climate change refers specifically to the rise in global temperatures from the mid-20th century to present. It is primarily caused by human activities, especially the burning of fossil fuels, which increases levels of heat-trapping greenhouse gases in Earth's atmosphere. The impacts are already being felt globally, including more frequent and severe weather events, rising sea levels, and shifts in wildlife populations."]
144
  ],
145
+ inputs=input_long,
146
+ cache_examples=False
147
+ )
 
 
 
 
 
148
 
149
  # Create Translation tab
150
  with gr.Tab("Translation (EN -> UK)"):
151
+ input_trans = gr.Textbox(label="English Text", lines=4, placeholder="Enter text in English to translate into Ukrainian...")
152
+ output_trans = gr.Textbox(label="Ukrainian Translation", lines=4)
153
+ btn_translate = gr.Button("Translate to Ukrainian", variant="primary")
154
+
155
+ # Link button click to translation function
156
+ btn_translate.click(fn=translate_en_to_uk, inputs=input_trans, outputs=output_trans)
157
+
158
+ # Configure examples for translation tab targeting the correct input component
159
+ gr.Examples(
160
+ examples=[
161
+ ["Artificial intelligence is rapidly changing the world."],
162
+ ["I would like to order a cup of coffee, please."],
163
+ ["The results of the recent testing phase exceeded all our initial expectations."]
164
+ ],
165
+ inputs=input_trans,
166
+ cache_examples=False
167
+ )
 
 
 
 
 
 
 
 
168
 
169
  if __name__ == "__main__":
170
+ # Launch application with active debug mode
171
  demo.launch(debug=True)