File size: 10,049 Bytes
1976483 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | from huggingface_hub import login, upload_folder
# (optional) Login with your Hugging Face credentials
login()
# Push your model files
upload_folder(folder_path=r"D:\Python\DEEP LEARNING\New folder\sentiment_analyzer", repo_id="kanha1111/sentiment_analysis", repo_type="model")
# import gradio as gr
# import pickle
# import re
# import string
# import nltk
# import numpy as np
# from nltk.corpus import stopwords
# from nltk.stem import WordNetLemmatizer
# # ===============================
# # DOWNLOAD NLTK FILES
# # ===============================
# nltk.download('stopwords')
# nltk.download('wordnet')
# # ===============================
# # LOAD TFLITE MODEL
# # ===============================
# try:
# import tensorflow as tf
# interpreter = tf.lite.Interpreter(model_path="sentiment_model.tflite")
# interpreter.allocate_tensors()
# input_details = interpreter.get_input_details()
# output_details = interpreter.get_output_details()
# MODEL_LOADED = True
# except Exception as e:
# MODEL_LOADED = False
# MODEL_ERROR = str(e)
# # ===============================
# # LOAD TOKENIZER
# # ===============================
# with open("tokenizer.pkl", "rb") as f:
# tokenizer = pickle.load(f)
# # ===============================
# # NLP TOOLS
# # ===============================
# stop_words = set(stopwords.words('english'))
# lemmatizer = WordNetLemmatizer()
# MAX_LEN = 100
# # ===============================
# # PAD SEQUENCES (manual)
# # ===============================
# def manual_pad_sequences(sequences, maxlen):
# padded = np.zeros((len(sequences), maxlen), dtype=np.float32)
# for i, seq in enumerate(sequences):
# if len(seq) > maxlen:
# padded[i] = seq[-maxlen:]
# else:
# padded[i, maxlen - len(seq):] = seq
# return padded
# # ===============================
# # CLEAN TEXT
# # ===============================
# def clean_text(text):
# text = text.lower()
# text = re.sub(r'http\S+', '', text)
# text = re.sub(r'@\w+', '', text)
# text = re.sub(r'#', '', text)
# text = re.sub(r'\d+', '', text)
# text = text.translate(str.maketrans('', '', string.punctuation))
# text = text.strip()
# words = text.split()
# words = [lemmatizer.lemmatize(w) for w in words if w not in stop_words]
# return ' '.join(words)
# # ===============================
# # PREDICT FUNCTION
# # ===============================
# def predict_sentiment(text):
# if not text or text.strip() == "":
# return error_card("Please enter some text to analyze.")
# if not MODEL_LOADED:
# return error_card(f"Model load failed: {MODEL_ERROR}")
# try:
# cleaned = clean_text(text)
# sequence = tokenizer.texts_to_sequences([cleaned])
# padded = manual_pad_sequences(sequence, MAX_LEN)
# # TFLite model expects batch size 256 - pad input accordingly
# batch_size = input_details[0]['shape'][0]
# full_input = np.zeros((batch_size, MAX_LEN), dtype=np.float32)
# full_input[0] = padded[0]
# interpreter.set_tensor(input_details[0]['index'], full_input)
# interpreter.invoke()
# score = float(interpreter.get_tensor(output_details[0]['index'])[0][0])
# is_positive = score > 0.5
# pct = score if is_positive else (1 - score)
# pct_display = f"{pct:.4f}"
# if is_positive:
# sentiment_text = "Positive Sentiment"
# sentiment_color = "#22c55e"
# emoji = "π"
# else:
# sentiment_text = "Negative Sentiment"
# sentiment_color = "#ef4444"
# emoji = "π"
# return f"""
# <div style='
# background:#1e2d40;
# border-radius:14px;
# padding:24px 28px;
# margin-top:8px;
# border:1px solid #2d4a6b;
# font-family:Inter,sans-serif;
# '>
# <h3 style='color:#f1f5f9;margin:0 0 16px 0;font-size:20px;font-weight:700;'>
# {emoji} Prediction Result
# </h3>
# <p style='margin:8px 0;color:#cbd5e1;font-size:14px;line-height:1.8;'>
# <b style='color:#f1f5f9;'>Input Text:</b> {text}
# </p>
# <p style='margin:8px 0;color:#cbd5e1;font-size:14px;line-height:1.8;'>
# <b style='color:#f1f5f9;'>Cleaned Text:</b> {cleaned}
# </p>
# <p style='margin:8px 0;color:#cbd5e1;font-size:14px;line-height:1.8;'>
# <b style='color:#f1f5f9;'>Sentiment:</b>
# <span style='color:{sentiment_color};font-weight:700;'>{sentiment_text}</span>
# </p>
# <p style='margin:8px 0;color:#cbd5e1;font-size:14px;line-height:1.8;'>
# <b style='color:#f1f5f9;'>Confidence Score:</b>
# <span style='color:#60a5fa;font-weight:600;'>{pct_display}</span>
# </p>
# </div>
# """
# except Exception as e:
# return error_card(f"Prediction error: {str(e)}")
# def error_card(msg):
# return f"""
# <div style='background:#2d1515;border:1px solid #ef4444;border-radius:12px;padding:18px;margin-top:8px;'>
# <p style='color:#fca5a5;margin:0;font-size:14px;'>β οΈ {msg}</p>
# </div>
# """
# # ===============================
# # CSS
# # ===============================
# css = """
# body, .gradio-container {
# background: #0f172a !important;
# font-family: Inter, sans-serif !important;
# }
# .gradio-container {
# max-width: 720px !important;
# margin: auto !important;
# padding: 30px 20px !important;
# }
# textarea {
# background: #1e2d40 !important;
# border: 1px solid #2d4a6b !important;
# border-radius: 12px !important;
# color: #f1f5f9 !important;
# font-size: 15px !important;
# }
# textarea::placeholder { color: #64748b !important; }
# textarea:focus {
# border-color: #3b82f6 !important;
# box-shadow: 0 0 0 3px rgba(59,130,246,0.2) !important;
# }
# label span { color: #94a3b8 !important; font-size: 13px !important; }
# button.primary {
# background: linear-gradient(135deg, #3b82f6, #6366f1) !important;
# border: none !important;
# border-radius: 12px !important;
# color: white !important;
# font-size: 16px !important;
# font-weight: 600 !important;
# }
# button.primary:hover {
# transform: translateY(-2px) !important;
# box-shadow: 0 8px 25px rgba(59,130,246,0.4) !important;
# }
# footer { display: none !important; }
# """
# # ===============================
# # UI
# # ===============================
# with gr.Blocks() as demo:
# gr.HTML("""
# <div style='text-align:center; margin-bottom:24px;'>
# <h1 style='font-size:32px;font-weight:800;color:#f1f5f9;margin:0 0 8px 0;'>
# AI Sentiment Analyzer
# </h1>
# <p style='color:#94a3b8;font-size:15px;margin:0;'>
# Real-Time Twitter Sentiment Analysis using BiLSTM
# </p>
# </div>
# """)
# text_input = gr.Textbox(
# label="Enter Text",
# placeholder="Type or paste any tweet, review, or sentence...",
# lines=4,
# elem_id="text_input",
# )
# gr.HTML("""
# <div style='margin: 8px 0 4px 0;'>
# <p style='color:#64748b; font-size:12px; margin:0 0 8px 0;'>Try a sample β</p>
# <div style='display:flex; flex-wrap:wrap; gap:8px;'>
# <button onclick="fillText('This AI project is absolutely amazing and the results are very accurate')"
# style='background:#1e3a5f; color:#e2e8f0; border:1px solid #2d5a8e;
# border-radius:8px; padding:6px 12px; font-size:12px; cursor:pointer;'>
# π Positive
# </button>
# <button onclick="fillText('I love this product, it works amazingly!')"
# style='background:#1e3a5f; color:#e2e8f0; border:1px solid #2d5a8e;
# border-radius:8px; padding:6px 12px; font-size:12px; cursor:pointer;'>
# π Amazing
# </button>
# <button onclick="fillText('This is the worst experience I have ever had.')"
# style='background:#1e3a5f; color:#e2e8f0; border:1px solid #2d5a8e;
# border-radius:8px; padding:6px 12px; font-size:12px; cursor:pointer;'>
# π€ Negative
# </button>
# <button onclick="fillText('The app keeps crashing, very frustrating.')"
# style='background:#1e3a5f; color:#e2e8f0; border:1px solid #2d5a8e;
# border-radius:8px; padding:6px 12px; font-size:12px; cursor:pointer;'>
# π Frustrating
# </button>
# </div>
# </div>
# <script>
# function fillText(text) {
# const textarea = document.querySelector('#text_input textarea');
# if (textarea) {
# textarea.value = text;
# textarea.dispatchEvent(new Event('input', { bubbles: true }));
# }
# }
# </script>
# """)
# analyze_btn = gr.Button("Analyze Sentiment", variant="primary", size="lg")
# result_out = gr.HTML()
# analyze_btn.click(
# fn=predict_sentiment,
# inputs=text_input,
# outputs=result_out,
# )
# gr.HTML("""
# <div style='text-align:center;margin-top:24px;font-size:12px;color:#475569;'>
# Built with TFLite + Gradio Β·
# <a href='https://github.com/kanha165/Sentiment-Analysis-using-BiLSTM'
# style='color:#3b82f6;text-decoration:none;' target='_blank'>GitHub β</a>
# </div>
# """)
# demo.launch(ssr_mode=False, css=css)
|