philipobiorah commited on
Commit
db87bba
·
verified ·
1 Parent(s): bd7368b

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +22 -18
main.py CHANGED
@@ -10,28 +10,32 @@ import matplotlib.pyplot as plt
10
  import base64
11
  from io import BytesIO
12
 
13
- # Set writable cache directories
14
- os.environ["HF_HOME"] = "/root/.cache/huggingface"
15
- os.environ["MPLCONFIGDIR"] = "/tmp/matplotlib" # Use /tmp instead of /root
 
16
 
17
- # Use Hugging Face token from Secrets (instead of the protected /root path)
 
 
 
 
18
  HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN", None)
19
 
20
  app = Flask(__name__)
21
 
22
- # Load Model from Hugging Face with Explicit Token
23
- MODEL_HF_REPO = "philipobiorah/bert-imdb-model" # Replace with your Hugging Face model repo
24
-
25
-
26
-
27
-
28
 
29
  print("🚀 Loading model from Hugging Face Hub with authentication...")
30
-
31
- model = BertForSequenceClassification.from_pretrained(
32
- MODEL_HF_REPO,
33
- token=os.getenv("HUGGINGFACE_TOKEN", None)
34
- )
 
 
 
35
 
36
  model.eval()
37
  tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
@@ -73,19 +77,19 @@ def upload_file_post():
73
  # Predict sentiment for each review
74
  data['sentiment'] = data['review'].apply(predict_sentiment)
75
 
76
- # Sentiment Analysis Summary
77
  sentiment_counts = data['sentiment'].value_counts().to_dict()
78
  summary = f"Total Reviews: {len(data)}<br>" \
79
  f"Positive: {sentiment_counts.get('Positive', 0)}<br>" \
80
  f"Negative: {sentiment_counts.get('Negative', 0)}<br>"
81
 
82
- # Generate bar chart
83
  fig, ax = plt.subplots()
84
  ax.bar(sentiment_counts.keys(), sentiment_counts.values(), color=['red', 'blue'])
85
  ax.set_ylabel('Counts')
86
  ax.set_title('Sentiment Analysis Summary')
87
 
88
- # Convert plot to base64 for embedding
89
  img = BytesIO()
90
  plt.savefig(img, format='png', bbox_inches='tight')
91
  img.seek(0)
 
10
  import base64
11
  from io import BytesIO
12
 
13
+ # Set writable cache directories for Hugging Face and Matplotlib
14
+ os.environ["TRANSFORMERS_CACHE"] = "/tmp/huggingface_cache"
15
+ os.environ["HF_HOME"] = "/tmp/huggingface_cache"
16
+ os.environ["MPLCONFIGDIR"] = "/tmp/matplotlib"
17
 
18
+ # Ensure the directories exist
19
+ os.makedirs("/tmp/huggingface_cache", exist_ok=True)
20
+ os.makedirs("/tmp/matplotlib", exist_ok=True)
21
+
22
+ # Retrieve Hugging Face Token securely from environment variables
23
  HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN", None)
24
 
25
  app = Flask(__name__)
26
 
27
+ # Fix the Hugging Face Model Repository Name
28
+ MODEL_HF_REPO = "philipobiorah/bert-imdb-model" # Ensure this exists on Hugging Face
 
 
 
 
29
 
30
  print("🚀 Loading model from Hugging Face Hub with authentication...")
31
+ try:
32
+ model = BertForSequenceClassification.from_pretrained(
33
+ MODEL_HF_REPO,
34
+ token=HF_TOKEN, # Ensure correct authentication
35
+ )
36
+ except Exception as e:
37
+ print(f"❌ Error loading model: {e}")
38
+ exit(1)
39
 
40
  model.eval()
41
  tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
 
77
  # Predict sentiment for each review
78
  data['sentiment'] = data['review'].apply(predict_sentiment)
79
 
80
+ # Sentiment Analysis Summary
81
  sentiment_counts = data['sentiment'].value_counts().to_dict()
82
  summary = f"Total Reviews: {len(data)}<br>" \
83
  f"Positive: {sentiment_counts.get('Positive', 0)}<br>" \
84
  f"Negative: {sentiment_counts.get('Negative', 0)}<br>"
85
 
86
+ # Generate bar chart
87
  fig, ax = plt.subplots()
88
  ax.bar(sentiment_counts.keys(), sentiment_counts.values(), color=['red', 'blue'])
89
  ax.set_ylabel('Counts')
90
  ax.set_title('Sentiment Analysis Summary')
91
 
92
+ # Convert plot to base64 for embedding
93
  img = BytesIO()
94
  plt.savefig(img, format='png', bbox_inches='tight')
95
  img.seek(0)