kanha1111's picture
Upload folder using huggingface_hub
1976483 verified
Raw History Blame Contribute Delete
10 kB
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>&nbsp;{text}
# </p>
# <p style='margin:8px 0;color:#cbd5e1;font-size:14px;line-height:1.8;'>
# <b style='color:#f1f5f9;'>Cleaned Text:</b>&nbsp;{cleaned}
# </p>
# <p style='margin:8px 0;color:#cbd5e1;font-size:14px;line-height:1.8;'>
# <b style='color:#f1f5f9;'>Sentiment:</b>&nbsp;
# <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>&nbsp;
# <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 &nbsp;Β·&nbsp;
# <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)