fitsblb commited on
Commit
14cc031
Β·
1 Parent(s): c0f0990

Fix HF Spaces deployment: Add __init__.py and simplify app.py for better compatibility

Browse files
Files changed (2) hide show
  1. app.py +56 -50
  2. app/__init__.py +1 -0
app.py CHANGED
@@ -1,59 +1,70 @@
1
  import gradio as gr
2
- import sys
3
  import os
 
4
 
5
- # Add the current directory to Python path
6
- sys.path.append(os.path.dirname(os.path.abspath(__file__)))
 
7
 
8
- # Import your advanced model system
9
  try:
10
- from app.advanced_model import predict_advanced, get_advanced_analyzer
11
- ADVANCED_AVAILABLE = True
12
- except ImportError:
13
- # Fallback to basic model if advanced isn't available
14
  from app.model import predict
15
- ADVANCED_AVAILABLE = False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  def analyze_sentiment(text):
18
- """Analyze sentiment using the advanced multi-model system"""
19
  if not text.strip():
20
  return "Please enter some text to analyze!"
21
 
22
  try:
23
- if ADVANCED_AVAILABLE:
24
- # Use advanced multi-model system
25
- result = predict_advanced(text)
26
-
27
- # Format results for display
28
- model_results = []
29
- for model_result in result.results:
30
- model_results.append(f"**{model_result.model_name}**: {model_result.sentiment} ({model_result.confidence:.3f})")
 
 
 
 
 
 
 
 
31
 
32
- output = f"""
33
- ## 🎯 Consensus Result
34
- **Sentiment**: {result.consensus_sentiment}
35
- **Confidence**: {result.average_confidence:.3f}
36
- **Agreement Score**: {result.agreement_score:.3f}
37
- **Processing Time**: {result.processing_time:.3f}s
38
-
39
- ## πŸ€– Individual Model Results
40
- {chr(10).join(model_results)}
41
-
42
- ---
43
- *Powered by 4 AI models working together for superior accuracy!*
44
- """
45
- return output
46
- else:
47
- # Fallback to basic model
48
- sentiment, confidence = predict(text)
49
- return f"""
50
- ## πŸ“Š Sentiment Analysis Result
51
  **Sentiment**: {sentiment}
52
- **Confidence**: {confidence:.3f}
 
53
 
54
- *Using YelpReviewsAnalyzer model*
55
- """
56
-
 
 
57
  except Exception as e:
58
  return f"❌ Error analyzing sentiment: {str(e)}"
59
 
@@ -66,17 +77,12 @@ demo = gr.Interface(
66
  lines=3
67
  ),
68
  outputs=gr.Markdown(label="🎯 Analysis Results"),
69
- title="πŸš€ Advanced Sentiment Analyzer",
70
  description="""
71
- **Multi-Model AI System for Superior Sentiment Analysis**
72
-
73
- This system uses up to 4 different AI models working together to provide more accurate sentiment predictions:
74
- - 🎯 YelpReviewsAnalyzer (custom fine-tuned model)
75
- - πŸ€– DistilBERT (general-purpose)
76
- - 🐦 Twitter-RoBERTa (social media optimized)
77
- - πŸ’° FinBERT (financial sentiment)
78
 
79
- The models vote on the final prediction using a consensus algorithm for higher accuracy!
 
80
  """,
81
  examples=[
82
  ["This restaurant has absolutely amazing food and incredible service!"],
 
1
  import gradio as gr
 
2
  import os
3
+ import sys
4
 
5
+ # Add current directory to path
6
+ current_dir = os.path.dirname(os.path.abspath(__file__))
7
+ sys.path.insert(0, current_dir)
8
 
9
+ # Try to import advanced model, fallback to basic if needed
10
  try:
 
 
 
 
11
  from app.model import predict
12
+ from transformers import pipeline, AutoTokenizer, AutoModelForSequenceClassification
13
+
14
+ # Try to load your custom model first
15
+ try:
16
+ MODEL_NAME = "fitsblb/YelpReviewsAnalyzer"
17
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
18
+ model = AutoModelForSequenceClassification.from_pretrained(MODEL_NAME)
19
+ sentiment_pipeline = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
20
+ CUSTOM_MODEL_AVAILABLE = True
21
+ except:
22
+ # Fallback to a general model
23
+ sentiment_pipeline = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment-latest")
24
+ CUSTOM_MODEL_AVAILABLE = False
25
+
26
+ except ImportError:
27
+ # Ultimate fallback
28
+ from transformers import pipeline
29
+ sentiment_pipeline = pipeline("sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment-latest")
30
+ CUSTOM_MODEL_AVAILABLE = False
31
 
32
  def analyze_sentiment(text):
33
+ """Analyze sentiment using available models"""
34
  if not text.strip():
35
  return "Please enter some text to analyze!"
36
 
37
  try:
38
+ # Use the pipeline
39
+ result = sentiment_pipeline(text)
40
+
41
+ if isinstance(result, list) and len(result) > 0:
42
+ result = result[0]
43
+
44
+ sentiment = result['label']
45
+ confidence = result['score']
46
+
47
+ # Map labels to consistent format
48
+ if sentiment.upper() in ['POSITIVE', 'POS']:
49
+ sentiment = "Positive"
50
+ elif sentiment.upper() in ['NEGATIVE', 'NEG']:
51
+ sentiment = "Negative"
52
+ elif sentiment.upper() in ['NEUTRAL', 'NEU']:
53
+ sentiment = "Neutral"
54
 
55
+ model_info = "YelpReviewsAnalyzer (Custom)" if CUSTOM_MODEL_AVAILABLE else "RoBERTa (Fallback)"
56
+
57
+ output = f"""
58
+ ## 🎯 Sentiment Analysis Result
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  **Sentiment**: {sentiment}
60
+ **Confidence**: {confidence:.3f}
61
+ **Model**: {model_info}
62
 
63
+ ---
64
+ *Analyzing sentiment with AI models*
65
+ """
66
+ return output
67
+
68
  except Exception as e:
69
  return f"❌ Error analyzing sentiment: {str(e)}"
70
 
 
77
  lines=3
78
  ),
79
  outputs=gr.Markdown(label="🎯 Analysis Results"),
80
+ title="πŸš€ Sentiment Analyzer",
81
  description="""
82
+ **AI-Powered Sentiment Analysis**
 
 
 
 
 
 
83
 
84
+ This system analyzes the sentiment of your text using transformer models.
85
+ Enter any text and get instant sentiment predictions with confidence scores!
86
  """,
87
  examples=[
88
  ["This restaurant has absolutely amazing food and incredible service!"],
app/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Empty file to make this directory a Python package