hashirlodhi commited on
Commit
289ffa3
·
verified ·
1 Parent(s): 726d820

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -147
app.py CHANGED
@@ -1,162 +1,43 @@
 
1
  import gradio as gr
2
- import joblib
3
- import nltk
4
- from nltk.stem import WordNetLemmatizer
5
- from nltk.tokenize import word_tokenize
6
- from nltk.corpus import stopwords
7
- import string
8
- import numpy as np
9
 
10
- # Download required NLTK data
11
- nltk.download('punkt')
12
- nltk.download('wordnet')
13
- nltk.download('stopwords')
14
 
15
- # Define positive and negative word lists
16
- POSITIVE_WORDS = [
17
- 'great', 'excellent', 'amazing', 'wonderful', 'fantastic', 'superb', 'brilliant',
18
- 'awesome', 'outstanding', 'perfect', 'terrific', 'fabulous', 'marvelous', 'stellar',
19
- 'enjoyable', 'engaging', 'incredible', 'delightful', 'impressive', 'inspiring',
20
- 'touching', 'heartwarming', 'fun', 'entertaining', 'captivating', 'masterpiece',
21
- 'beautiful', 'charming', 'uplifting', 'memorable', 'well-done', 'well-made',
22
- 'well-acted', 'well-written', 'clever', 'smart', 'thoughtful', 'moving', 'hilarious',
23
- 'funny', 'laugh', 'loved', 'love', 'favorite', 'recommend', 'must-see', 'enjoyed',
24
- 'spectacular', 'breathtaking', 'refreshing', 'unique', 'creative', 'original',
25
- 'strong', 'powerful', 'emotional', 'satisfying', 'rewarding', 'solid', 'top-notch',
26
- 'phenomenal', 'riveting', 'absorbing', 'gripping', 'remarkable', 'exceptional',
27
- 'flawless', 'genius', 'well-crafted', 'well-executed', 'well-directed', 'well-cast',
28
- 'well-paced', 'well-shot', 'well-produced', 'well-developed', 'well-performed',
29
- 'enchanting', 'magical', 'bravo', 'enriching', 'enlightening', 'enjoy', 'pleasure',
30
- 'pleasing', 'pleased', 'sublime', 'exquisite', 'glorious', 'outstanding', 'superior',
31
- 'commendable', 'noteworthy', 'notable', 'admirable', 'commend', 'praise', 'applaud',
32
- 'acclaimed', 'acclaim', 'favorite', 'best', 'top', 'winner', 'winning', 'award-winning',
33
- 'blockbuster', 'hit', 'crowd-pleaser', 'must', 'mustwatch', 'mustsee', 'worthwhile',
34
- 'worth', 'enjoyment', 'joy', 'cheerful', 'positive', 'optimistic', 'hopeful',
35
- 'heartfelt', 'satisfy', 'satisfying', 'satisfied', 'impressed', 'impress', 'impressive',
36
- 'commend', 'commendable', 'commendation', 'applause', 'applaud', 'applauded',
37
- 'recommendation', 'recommended', 'recommend', 'favorite', 'favorites', 'fav', 'fave',
38
- 'gem', 'hidden gem', 'classic', 'timeless', 'iconic', 'legendary', 'epic', 'must-own',
39
- 'must-have', 'must-see', 'must-watch', 'must experience', 'must try', 'must buy',
40
- 'must read', 'must listen', 'must play', 'must visit', 'must go', 'must do',
41
- 'must attend', 'must eat', 'must drink', 'must taste', 'must feel', 'must love',
42
- 'must enjoy', 'must appreciate', 'must admire', 'must respect', 'must cherish',
43
- 'must treasure', 'must value', 'must honor', 'must celebrate', 'must embrace',
44
- 'must support', 'must encourage', 'must inspire', 'must motivate', 'must uplift',
45
- 'must empower', 'must enlighten', 'must educate', 'must inform', 'must entertain',
46
- 'must amuse', 'must delight', 'must please', 'must satisfy', 'must gratify',
47
- 'must fulfill', 'must enrich', 'must enhance', 'must improve', 'must better',
48
- 'must advance', 'must progress', 'must develop', 'must grow', 'must evolve',
49
- 'must transform', 'must change', 'must innovate', 'must create', 'must build',
50
- 'must make', 'must produce', 'must generate', 'must invent', 'must discover',
51
- 'must explore', 'must learn', 'must teach', 'must share', 'must give', 'must help',
52
- 'must serve', 'must care', 'must love', 'must like', 'must prefer', 'must choose',
53
- 'must select', 'must pick', 'must opt', 'must decide', 'must determine', 'must resolve',
54
- 'must solve', 'must fix', 'must repair', 'must mend', 'must heal', 'must cure',
55
- 'must treat', 'must prevent', 'must protect', 'must defend', 'must guard', 'must shield',
56
- 'must save', 'must rescue', 'must recover', 'must restore', 'must revive', 'must renew',
57
- 'must refresh', 'must rejuvenate', 'must revitalize', 'must energize', 'must invigorate',
58
- 'must stimulate', 'must excite', 'must thrill', 'must exhilarate', 'must inspire',
59
- 'must motivate', 'must encourage', 'must support', 'must help', 'must assist',
60
- 'must aid', 'must benefit', 'must profit', 'must gain', 'must win', 'must succeed',
61
- 'must achieve', 'must accomplish', 'must attain', 'must reach', 'must realize',
62
- 'must fulfill', 'must complete', 'must finish', 'must end', 'must conclude',
63
- 'must close', 'must wrap', 'must finalize', 'must settle', 'must resolve',
64
- 'must solve', 'must fix', 'must repair', 'must mend', 'must heal', 'must cure',
65
- 'must treat', 'must prevent', 'must protect', 'must defend', 'must guard', 'must shield',
66
- ]
67
 
68
- NEGATIVE_WORDS = [
69
- 'bad', 'worst', 'awful', 'terrible', 'horrible', 'atrocious', 'dreadful',
70
- 'abysmal', 'lousy', 'poor', 'subpar', 'mediocre', 'unacceptable', 'disappointing',
71
- 'boring', 'predictable', 'uninteresting', 'forgettable', 'tedious', 'slow',
72
- 'annoying', 'unbearable', 'painful', 'mess', 'flawed', 'weak', 'unconvincing',
73
- 'overrated', 'underwhelming', 'cliché', 'cliche', 'ridiculous', 'nonsense',
74
- 'unrealistic', 'waste', 'pointless', 'dull', 'unimpressive', 'cringe', 'cringeworthy',
75
- 'unoriginal', 'incoherent', 'confusing', 'unfunny', 'forced', 'flat', 'shallow',
76
- 'forgettable', 'unnecessary', 'unpleasant', 'unwatchable', 'cheesy', 'corny',
77
- 'painstaking', 'tedium', 'drag', 'lackluster', 'insipid', 'overlong', 'bloated',
78
- 'contrived', 'derivative', 'sloppy', 'amateurish', 'unfocused', 'awkward',
79
- 'unresolved', 'unfulfilled', 'unremarkable', 'unengaging', 'unappealing',
80
- 'unbelievable', 'unbalanced', 'unpolished', 'unrefined', 'unprofessional',
81
- 'unmemorable', 'unrelatable', 'unreal', 'unconvincing', 'unbearable', 'unimaginative',
82
- 'unintelligent', 'unnecessary', 'unpleasant', 'unrewarding', 'unsettling',
83
- 'unsubtle', 'unworthy', 'unwelcome', 'unwise', 'unwieldy', 'unworthy', 'unjustified',
84
- 'unjust', 'unforgivable', 'unforgiving', 'unfortunate', 'unfriendly', 'unfulfilled',
85
- 'unimpressed', 'uninspired', 'uninspiring', 'uninteresting', 'unlikable', 'unlucky',
86
- 'unmotivated', 'unoriginal', 'unpleasant', 'unrealistic', 'unsatisfying', 'unsuccessful',
87
- 'unsuitable', 'unsurprising', 'untalented', 'unwatchable', 'upsetting', 'useless',
88
- 'vapid', 'weak', 'worthless', 'yawn', 'disaster', 'disastrous', 'disgusting',
89
- 'distasteful', 'disturbing', 'dreary', 'embarrassing', 'excruciating', 'fail',
90
- 'failure', 'flop', 'garbage', 'hackneyed', 'hated', 'hate', 'illogical', 'inferior',
91
- 'irritating', 'lame', 'lacking', 'letdown', 'messy', 'monotonous', 'nonsensical',
92
- 'offensive', 'painful', 'pathetic', 'poorly', 'regret', 'regrettable', 'repetitive',
93
- 'shame', 'shameful', 'stupid', 'tiresome', 'trash', 'trite', 'unbearable', 'unconvincing',
94
- 'unimpressive', 'uninteresting', 'unlikable', 'unoriginal', 'unpleasant', 'unwatchable',
95
- 'waste', 'worthless'
96
- ]
97
 
98
- # Sentiment analyzer class
99
- class EnhancedSentimentAnalyzer:
100
- def __init__(self):
101
- self.lemmatizer = WordNetLemmatizer()
102
- self.stop_words = set(stopwords.words('english'))
103
- self.punctuation = set(string.punctuation)
104
- self.positive_words = set(POSITIVE_WORDS)
105
- self.negative_words = set(NEGATIVE_WORDS)
106
-
107
- def preprocess(self, text):
108
- tokens = word_tokenize(text.lower())
109
- processed_tokens = [
110
- self.lemmatizer.lemmatize(token) for token in tokens
111
- if token not in self.punctuation and token not in self.stop_words and len(token) > 2
112
- ]
113
- return ' '.join(processed_tokens)
114
-
115
- # Load the pre-trained model
116
- model = joblib.load('sentiment_model.pkl')
117
-
118
- # Analyze sentiment function
119
- def analyze_sentiment(text):
120
  if not text.strip():
121
- return "Error: Please enter a non-empty review text."
122
-
123
- preprocessor = EnhancedSentimentAnalyzer()
124
- processed_text = preprocessor.preprocess(text)
125
-
126
- proba = model.predict_proba([processed_text])[0]
127
- prediction = model.predict([processed_text])[0]
128
 
129
- tokens = processed_text.split()
130
- pos_words = [w for w in tokens if w in POSITIVE_WORDS]
131
- neg_words = [w for w in tokens if w in NEGATIVE_WORDS]
132
 
133
- result = {
134
- "prediction": "Positive" if prediction == 1 else "Negative",
135
- "confidence": float(max(proba)),
136
- "positive_words": list(set(pos_words)),
137
- "negative_words": list(set(neg_words))
138
- }
139
-
140
- # Format output
141
- output = f"Prediction: {result['prediction']} (Confidence: {result['confidence']:.2f})\n"
142
- if result['positive_words']:
143
- output += f"Positive words found: {', '.join(result['positive_words'])}\n"
144
- else:
145
- output += "Positive words found: None\n"
146
- if result['negative_words']:
147
- output += f"Negative words found: {', '.join(result['negative_words'])}\n"
148
- else:
149
- output += "Negative words found: None\n"
150
-
151
- return output
152
 
153
  # Define Gradio interface
154
  iface = gr.Interface(
155
- fn=analyze_sentiment,
156
- inputs=gr.Textbox(lines=5, placeholder="Enter your movie review here...", label="Movie Review"),
157
  outputs=gr.Textbox(label="Sentiment Analysis Result"),
158
- title="Movie Review Sentiment Analyzer",
159
- description="Enter a movie review to predict its sentiment (Positive or Negative) using a pre-trained model."
160
  )
161
 
162
  # Launch the interface
 
1
+ import os
2
  import gradio as gr
3
+ import google.generativeai as genai
 
 
 
 
 
 
4
 
5
+ # Configure the Gemini API with environment variable
6
+ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
7
+ if not GOOGLE_API_KEY:
8
+ raise ValueError("GOOGLE_API_KEY environment variable not set. Please configure it in the Hugging Face Space settings.")
9
 
10
+ genai.configure(api_key=GOOGLE_API_KEY)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # Use Gemini 1.5 Flash model
13
+ model = genai.GenerativeModel('gemini-1.5-flash-latest')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
 
15
+ def sentiment_analysis(text):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  if not text.strip():
17
+ return "Error: Please enter a non-empty text for analysis."
 
 
 
 
 
 
18
 
19
+ prompt = f"""
20
+ Analyze the sentiment of the following text and respond in this format:
 
21
 
22
+ Sentiment: [Positive / Negative / Neutral]
23
+ Reason: [Brief explanation of why you classified it this way]
24
+
25
+ Text: \"{text}\"
26
+ """
27
+
28
+ try:
29
+ response = model.generate_content(prompt)
30
+ return response.text.strip()
31
+ except Exception as e:
32
+ return f"Error: {str(e)}\nTip: Ensure your API key is valid at https://aistudio.google.com/"
 
 
 
 
 
 
 
 
33
 
34
  # Define Gradio interface
35
  iface = gr.Interface(
36
+ fn=sentiment_analysis,
37
+ inputs=gr.Textbox(lines=5, placeholder="Enter text for sentiment analysis...", label="Text Input"),
38
  outputs=gr.Textbox(label="Sentiment Analysis Result"),
39
+ title="Gemini Sentiment Analyzer",
40
+ description="Enter text to analyze its sentiment using Google's Gemini 1.5 Flash model. Provide a valid GOOGLE_API_KEY in the Hugging Face Space settings."
41
  )
42
 
43
  # Launch the interface