DevxAman commited on
Commit
523a6d7
Β·
verified Β·
1 Parent(s): 47bc018

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -23
app.py CHANGED
@@ -1,6 +1,6 @@
1
  """
2
  HuggingFace Space App - News Sentiment Analyzer
3
- ZeroGPU Compatible Version
4
  """
5
 
6
  import gradio as gr
@@ -37,6 +37,7 @@ print("βœ… Siebert model loaded!")
37
 
38
  print("🎯 All models ready!")
39
 
 
40
  # ============================================
41
  # SENTIMENT ANALYSIS FUNCTIONS
42
  # ============================================
@@ -143,7 +144,7 @@ def get_ensemble_sentiment(text):
143
 
144
 
145
  def predict_single(text):
146
- """Predict sentiment for single text"""
147
  if not text or len(text.strip()) < 5:
148
  return "⚠️ Please enter some text to analyze."
149
 
@@ -185,36 +186,100 @@ def predict_single(text):
185
  """
186
 
187
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  # ============================================
189
  # GRADIO INTERFACE
190
  # ============================================
191
 
192
- demo = gr.Interface(
193
- fn=predict_single,
194
- inputs=gr.Textbox(
195
- label="πŸ“ Enter News Text",
196
- placeholder="Paste your news article here...",
197
- lines=8,
198
- max_lines=20
199
- ),
200
- outputs=gr.Markdown(label="πŸ“ˆ Analysis Results"),
201
- title="πŸ“° News Sentiment Analyzer",
202
- description="""
203
  ### 🎯 Ensemble Model: RoBERTa + Siebert
204
 
205
  This analyzer uses two powerful models combined for accurate sentiment analysis:
206
  - **RoBERTa**: Twitter-based sentiment model (negative, neutral, positive)
207
  - **Siebert**: Large-scale sentiment model (negative, positive)
208
- """,
209
- examples=[
210
- ["Apple reported record profits with revenue growth of 15% this quarter."],
211
- ["The company faces severe criticism over data breach affecting millions of users."],
212
- ["Government announced new policies to boost economic growth."],
213
- ["Defense ministry successfully tested new hypersonic missile system."]
214
- ],
215
- theme="soft",
216
- cache_examples=True
217
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
 
219
  if __name__ == "__main__":
 
 
 
 
 
 
 
220
  demo.launch(share=True)
 
1
  """
2
  HuggingFace Space App - News Sentiment Analyzer
3
+ Compatible with Gradio 6.20.0
4
  """
5
 
6
  import gradio as gr
 
37
 
38
  print("🎯 All models ready!")
39
 
40
+
41
  # ============================================
42
  # SENTIMENT ANALYSIS FUNCTIONS
43
  # ============================================
 
144
 
145
 
146
  def predict_single(text):
147
+ """Predict sentiment for single text - returns formatted string for Gradio"""
148
  if not text or len(text.strip()) < 5:
149
  return "⚠️ Please enter some text to analyze."
150
 
 
186
  """
187
 
188
 
189
+ # ============================================
190
+ # API ENDPOINT FOR EXTERNAL CALLS
191
+ # ============================================
192
+
193
+ def api_predict(text):
194
+ """API endpoint for external calls (JSON response)"""
195
+ if not text or len(text.strip()) < 5:
196
+ return {
197
+ 'error': 'Text too short or empty',
198
+ 'sentiment': 'Neutral',
199
+ 'confidence': 0.0
200
+ }
201
+
202
+ return get_ensemble_sentiment(text)
203
+
204
+
205
  # ============================================
206
  # GRADIO INTERFACE
207
  # ============================================
208
 
209
+ # Create the interface with Gradio 6.20.0 syntax
210
+ with gr.Blocks(title="πŸ“° News Sentiment Analyzer", theme="soft") as demo:
211
+ gr.Markdown("""
212
+ # πŸ“° News Sentiment Analyzer
213
+
 
 
 
 
 
 
214
  ### 🎯 Ensemble Model: RoBERTa + Siebert
215
 
216
  This analyzer uses two powerful models combined for accurate sentiment analysis:
217
  - **RoBERTa**: Twitter-based sentiment model (negative, neutral, positive)
218
  - **Siebert**: Large-scale sentiment model (negative, positive)
219
+
220
+ The ensemble approach provides more robust results by combining both models.
221
+ """)
222
+
223
+ with gr.Row():
224
+ with gr.Column(scale=2):
225
+ text_input = gr.Textbox(
226
+ label="πŸ“ Enter News Text",
227
+ placeholder="Paste your news article here...",
228
+ lines=10,
229
+ max_lines=20
230
+ )
231
+
232
+ with gr.Row():
233
+ submit_btn = gr.Button("πŸ” Analyze Sentiment", variant="primary")
234
+ clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
235
+
236
+ # Examples section
237
+ gr.Markdown("### πŸ’‘ Try these examples:")
238
+ examples = [
239
+ "Apple reported record profits with revenue growth of 15% this quarter. The tech giant exceeded market expectations.",
240
+ "The company faces severe criticism over data breach affecting millions of users. Stocks fell sharply.",
241
+ "Government announced new policies to boost economic growth and create jobs. Markets reacted positively.",
242
+ "Defense ministry successfully tested new hypersonic missile system. Strategic capabilities enhanced.",
243
+ "The bank reported $2 billion in losses due to failed investments. CEO resigned amid controversy."
244
+ ]
245
+
246
+ for i, example in enumerate(examples):
247
+ gr.Examples(
248
+ inputs=text_input,
249
+ examples=[[example]],
250
+ label=f"Example {i+1}"
251
+ )
252
+
253
+ with gr.Column(scale=1):
254
+ output = gr.Markdown(label="πŸ“ˆ Analysis Results", value="Enter text and click 'Analyze Sentiment' to see results here.")
255
+
256
+ # Connect functions
257
+ submit_btn.click(
258
+ fn=predict_single,
259
+ inputs=text_input,
260
+ outputs=output
261
+ )
262
+
263
+ clear_btn.click(
264
+ fn=lambda: "",
265
+ inputs=[],
266
+ outputs=text_input
267
+ )
268
+
269
+ # Also allow Enter key to submit
270
+ text_input.submit(
271
+ fn=predict_single,
272
+ inputs=text_input,
273
+ outputs=output
274
+ )
275
+
276
 
277
  if __name__ == "__main__":
278
+ print("\n" + "="*60)
279
+ print("πŸš€ News Sentiment Analyzer")
280
+ print("="*60)
281
+ print("πŸ“± Device:", device)
282
+ print("πŸ€– Models: RoBERTa + Siebert")
283
+ print("="*60 + "\n")
284
+
285
  demo.launch(share=True)