philipobiorah commited on
Commit
b44978e
·
verified ·
1 Parent(s): 665bb42

fix upload file errors

Browse files

fix: Not Found
The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

Files changed (1) hide show
  1. main.py +59 -17
main.py CHANGED
@@ -22,7 +22,7 @@ os.makedirs(os.environ["MPLCONFIGDIR"], exist_ok=True)
22
 
23
  app = Flask(__name__)
24
 
25
- # Load Model from Hugging Face (Ensure the model is accessible)
26
  MODEL_NAME = "philipobiorah/bert-imdb-model"
27
  tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
28
  model = BertForSequenceClassification.from_pretrained(MODEL_NAME)
@@ -31,21 +31,16 @@ model.eval()
31
 
32
  # Function to Predict Sentiment
33
  def predict_sentiment(text):
34
- tokens = tokenizer.encode(text, add_special_tokens=True)
35
- chunks = [tokens[i:i + 512] for i in range(0, len(tokens), 512)]
36
-
37
- sentiments = []
38
- for chunk in chunks:
39
- inputs = tokenizer.decode(chunk, skip_special_tokens=True, clean_up_tokenization_spaces=True)
40
- inputs = tokenizer(inputs, return_tensors="pt", truncation=True, padding=True, max_length=512)
41
-
42
- with torch.no_grad():
43
- outputs = model(**inputs)
44
-
45
- sentiments.append(outputs.logits.argmax(dim=1).item())
46
-
47
- majority_sentiment = Counter(sentiments).most_common(1)[0][0]
48
- return 'Positive' if majority_sentiment == 1 else 'Negative'
49
 
50
  @app.route('/')
51
  def upload_file():
@@ -53,9 +48,56 @@ def upload_file():
53
 
54
  @app.route('/analyze_text', methods=['POST'])
55
  def analyze_text():
56
- text = request.form['text']
 
 
 
 
57
  sentiment = predict_sentiment(text)
58
  return render_template('upload.html', sentiment=sentiment)
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  if __name__ == '__main__':
61
  app.run(host='0.0.0.0', port=7860, debug=True)
 
22
 
23
  app = Flask(__name__)
24
 
25
+ # Load Model from Hugging Face
26
  MODEL_NAME = "philipobiorah/bert-imdb-model"
27
  tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
28
  model = BertForSequenceClassification.from_pretrained(MODEL_NAME)
 
31
 
32
  # Function to Predict Sentiment
33
  def predict_sentiment(text):
34
+ if not text.strip():
35
+ return "Neutral" # Avoid processing empty text
36
+
37
+ inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True, max_length=512)
38
+
39
+ with torch.no_grad():
40
+ outputs = model(**inputs)
41
+
42
+ sentiment = outputs.logits.argmax(dim=1).item()
43
+ return "Positive" if sentiment == 1 else "Negative"
 
 
 
 
 
44
 
45
  @app.route('/')
46
  def upload_file():
 
48
 
49
  @app.route('/analyze_text', methods=['POST'])
50
  def analyze_text():
51
+ text = request.form.get('text', '').strip()
52
+
53
+ if not text:
54
+ return render_template('upload.html', sentiment="Error: No text provided!")
55
+
56
  sentiment = predict_sentiment(text)
57
  return render_template('upload.html', sentiment=sentiment)
58
 
59
+ @app.route('/uploader', methods=['POST'])
60
+ def upload_file_post():
61
+ if 'file' not in request.files:
62
+ return "Error: No file uploaded!", 400
63
+
64
+ f = request.files['file']
65
+ if f.filename == '':
66
+ return "Error: No file selected!", 400
67
+
68
+ try:
69
+ data = pd.read_csv(f)
70
+
71
+ # Ensure 'review' column exists
72
+ if 'review' not in data.columns:
73
+ return "Error: CSV file must contain a 'review' column!", 400
74
+
75
+ # Predict sentiment for each review
76
+ data['sentiment'] = data['review'].astype(str).apply(predict_sentiment)
77
+
78
+ # Generate summary
79
+ sentiment_counts = data['sentiment'].value_counts().to_dict()
80
+ summary = f"Total Reviews: {len(data)}<br>" \
81
+ f"Positive: {sentiment_counts.get('Positive', 0)}<br>" \
82
+ f"Negative: {sentiment_counts.get('Negative', 0)}<br>"
83
+
84
+ # Generate sentiment plot
85
+ fig, ax = plt.subplots()
86
+ ax.bar(sentiment_counts.keys(), sentiment_counts.values(), color=['red', 'blue'])
87
+ ax.set_ylabel('Counts')
88
+ ax.set_title('Sentiment Analysis Summary')
89
+
90
+ # Save plot as an image
91
+ img = BytesIO()
92
+ plt.savefig(img, format='png', bbox_inches='tight')
93
+ img.seek(0)
94
+ plot_url = base64.b64encode(img.getvalue()).decode('utf8')
95
+ plt.close(fig)
96
+
97
+ return render_template('result.html', tables=[data.to_html(classes='data')], titles=data.columns.values, summary=summary, plot_url=plot_url)
98
+
99
+ except Exception as e:
100
+ return f"Error processing file: {str(e)}", 500
101
+
102
  if __name__ == '__main__':
103
  app.run(host='0.0.0.0', port=7860, debug=True)