hanantonio commited on
Commit
57b215d
·
verified ·
1 Parent(s): a84f008

Upload 21 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ src/best_model.keras filter=lfs diff=lfs merge=lfs -text
37
+ src/Negative[[:space:]]-[[:space:]]Topic[[:space:]]Activities[[:space:]]Over[[:space:]]Time.png filter=lfs diff=lfs merge=lfs -text
38
+ src/Positive[[:space:]]-[[:space:]]Topic[[:space:]]Activities[[:space:]]Over[[:space:]]Time.png filter=lfs diff=lfs merge=lfs -text
Dockerfile CHANGED
@@ -1,20 +1,20 @@
1
- FROM python:3.13.5-slim
2
-
3
- WORKDIR /app
4
-
5
- RUN apt-get update && apt-get install -y \
6
- build-essential \
7
- curl \
8
- git \
9
- && rm -rf /var/lib/apt/lists/*
10
-
11
- COPY requirements.txt ./
12
- COPY src/ ./src/
13
-
14
- RUN pip3 install -r requirements.txt
15
-
16
- EXPOSE 8501
17
-
18
- HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
19
-
20
- ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0"]
 
1
+ FROM python:3.13.5-slim
2
+
3
+ WORKDIR /app
4
+
5
+ RUN apt-get update && apt-get install -y \
6
+ build-essential \
7
+ curl \
8
+ git \
9
+ && rm -rf /var/lib/apt/lists/*
10
+
11
+ COPY requirements.txt ./
12
+ COPY src/ ./src/
13
+
14
+ RUN pip3 install -r requirements.txt
15
+
16
+ EXPOSE 8501
17
+
18
+ HEALTHCHECK CMD curl --fail http://localhost:8501/_stcore/health
19
+
20
+ ENTRYPOINT ["streamlit", "run", "src/streamlit_app.py", "--server.port=8501", "--server.address=0.0.0.0", "--server.enableXsrfProtection=false"]
README.md CHANGED
@@ -1,19 +1,19 @@
1
- ---
2
- title: SQ Sentiment Analysis
3
- emoji: 🚀
4
- colorFrom: red
5
- colorTo: red
6
- sdk: docker
7
- app_port: 8501
8
- tags:
9
- - streamlit
10
- pinned: false
11
- short_description: Streamlit template space
12
- ---
13
-
14
- # Welcome to Streamlit!
15
-
16
- Edit `/src/streamlit_app.py` to customize this app to your heart's desire. :heart:
17
-
18
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
19
- forums](https://discuss.streamlit.io).
 
1
+ ---
2
+ title: acre-system
3
+ emoji: 🚀
4
+ colorFrom: red
5
+ colorTo: red
6
+ sdk: docker
7
+ app_port: 8501
8
+ tags:
9
+ - streamlit
10
+ pinned: false
11
+ short_description: Streamlit template space
12
+ ---
13
+
14
+ # Welcome to Streamlit!
15
+
16
+ Edit `/src/app.py` to customize this app to your heart's desire. :heart:
17
+
18
+ If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
19
+ forums](https://discuss.streamlit.io).
requirements.txt CHANGED
@@ -1,3 +1,17 @@
1
- altair
2
- pandas
3
- streamlit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit==1.44.0
2
+ pandas==2.2.3
3
+ seaborn
4
+ matplotlib
5
+ plotly
6
+ pillow
7
+ numpy
8
+ wordcloud
9
+ fastopic==1.0.1
10
+ topmost==1.0.2
11
+ torchvision==0.21.0
12
+ gensim==4.3.3
13
+ torch===1.11.0
14
+ joblib===1.2.0
15
+ scikit-learn==1.6.1
16
+ tensorflow==2.20.0
17
+ nltk
src/Negative - Top Words Distributions.png ADDED
src/Negative - Topic Activities Over Time.png ADDED

Git LFS Details

  • SHA256: c9021d82de6adf0b4ab744b9b701d86f4d608e0301c8303acc24966245e87782
  • Pointer size: 131 Bytes
  • Size of remote file: 163 kB
src/Negative - Topics Weights.png ADDED
src/Positive - Top Words Distributions.png ADDED
src/Positive - Topic Activities Over Time.png ADDED

Git LFS Details

  • SHA256: 54cf3b7587f84e87206dccbb9ead680bf47e9ca7b8ca422b6e84f51dcce7bed1
  • Pointer size: 131 Bytes
  • Size of remote file: 114 kB
src/Positive - Topics Weights.png ADDED
src/__pycache__/eda.cpython-39.pyc ADDED
Binary file (3.55 kB). View file
 
src/__pycache__/prediction_src.cpython-39.pyc ADDED
Binary file (6.22 kB). View file
 
src/app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # import streamlit as st
2
+ # import eda
3
+ # import prediction_src
4
+
5
+ # ===============================
6
+ # SQ_streamlit_app.py
7
+ # ===============================
8
+
9
+ import streamlit as st
10
+
11
+ # ===============================
12
+ # Streamlit Config
13
+ # ===============================
14
+ st.set_page_config(
15
+ page_title='ACRE - Automated Customer Review Analysis',
16
+ layout='wide',
17
+ initial_sidebar_state='expanded'
18
+ )
19
+ # st.markdown(
20
+ # """
21
+ # **ACRE** (Automated Customer Reviews Analysis) is a system designed to classify customer sentiment towards
22
+ # their flight experience with Singapore Airlines (SQ). It transforms raw customer feedback into structured insights,
23
+ # empowering management to make data-driven decisions and continuously enhance SQ’s reputation for service excellence.
24
+ # """
25
+ # )
26
+
27
+ # Import custom pages (pastikan tidak ada st.* di global scope modul ini)
28
+ import eda
29
+ import prediction_compile
30
+
31
+ # ===============================
32
+ # Sidebar Navigation
33
+ # ===============================
34
+ page = st.sidebar.selectbox(
35
+ 'Select Page:',
36
+ ('Exploratory Data Analysis (EDA)', 'Prediction')
37
+ )
38
+
39
+ # ===============================
40
+ # Page Content
41
+ # ===============================
42
+ # st.title("ACRE - Automated Customer Review Analysis")
43
+
44
+ if page == 'Exploratory Data Analysis (EDA)':
45
+ eda.run()
46
+ else:
47
+ prediction_compile.run()
48
+
49
+ # ===============================
50
+ # Footer
51
+ # ===============================
52
+ st.markdown(
53
+ """
54
+ <div style="text-align: center; color: gray; font-size: 12px; margin-top: 50px;">
55
+ © 2025 Hana Antonio, Muhammad Revi Gilang Pradana, Zhaky B. Triaji. All rights reserved. <br>
56
+ References: Dataset from <a href="https://www.kaggle.com" target="_blank" style="color: gray;">Kaggle</a>
57
+ </div>
58
+ """,
59
+ unsafe_allow_html=True
60
+ )
src/best_lstm_model.h5 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a8f3aa3bdc5dbc925914ff1463382d8f05090cb1e7e9ece6b2a8e1546d7f7630
3
+ size 8057368
src/best_model.keras ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bd4d974bd880724b25a438f7de32d562951740369b972ff6ce80562dc86417ae
3
+ size 8048001
src/eda.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import matplotlib.pyplot as plt
4
+ import seaborn as sns
5
+ import plotly.express as px
6
+ from PIL import Image
7
+
8
+ # =============================================
9
+ # Cache dataset agar tidak reload setiap kali
10
+ # =============================================
11
+ @st.cache_data
12
+ def load_data():
13
+ df = pd.read_csv('./src/singapore_airlines_reviews.csv')
14
+ return df
15
+
16
+ # Load dataset
17
+ df = load_data()
18
+
19
+ # =============================================
20
+ # Main app
21
+ # =============================================
22
+ def run():
23
+ # Judul dan Subjudul
24
+ st.title("ACRE - Automated Customer Review Analysis")
25
+ st.subheader("Exploratory Data Analysis (EDA)")
26
+
27
+ st.markdown(
28
+ """
29
+ This section provides an exploratory data analysis (EDA) of Singapore Airlines (SQ) customer reviews.
30
+ We aim to understand the distribution of ratings, textual review characteristics, and topic modeling results.
31
+ These insights serve as the foundation for building automated models that classify sentiment and uncover key themes
32
+ in customer feedback.
33
+ """
34
+ )
35
+
36
+ # ===============================
37
+ # Dataset Preview
38
+ # ===============================
39
+ st.write("### Dataset Preview")
40
+ st.dataframe(df.head())
41
+
42
+ # ===============================
43
+ # Distribusi Rating
44
+ # ===============================
45
+ st.write("### Distribution of Ratings")
46
+ fig, ax = plt.subplots(figsize=(8, 5))
47
+ sns.countplot(x='rating', data=df, palette='viridis', ax=ax,
48
+ order=sorted(df['rating'].unique()))
49
+ for p in ax.patches:
50
+ height = p.get_height()
51
+ ax.annotate(f'{height:,}', (p.get_x() + p.get_width()/2, height),
52
+ ha='center', va='bottom', fontsize=10, fontweight='bold')
53
+ st.pyplot(fig)
54
+
55
+ st.markdown(
56
+ """
57
+ **Note:** Ratings are explored here only as descriptive information about passenger experiences.
58
+ In the inference page, actual sentiment will be predicted automatically from the review text using NLP techniques.
59
+ """
60
+ )
61
+
62
+ # ===============================
63
+ # Analisis Panjang Teks
64
+ # ===============================
65
+ st.write("### Distribution of Review Length")
66
+ df['text_length'] = df['text'].apply(lambda x: len(str(x).split()))
67
+ fig = px.histogram(df, x='text_length', nbins=50, title='Review Length Distribution')
68
+ st.plotly_chart(fig, use_container_width=True)
69
+
70
+ # ===============================
71
+ # Topic Modeling Results (Images)
72
+ # ===============================
73
+ st.write("## Topic Modeling Results")
74
+
75
+ # 1. Top Words Distributions
76
+ col1, col2 = st.columns(2)
77
+ with col1:
78
+ st.image("./src/Negative - Top Words Distributions.png", caption="Negative - Top Words Distributions")
79
+ with col2:
80
+ st.image("./src/Positive - Top Words Distributions.png", caption="Positive - Top Words Distributions")
81
+ st.write("Lorem ipsum explanation for Top Words Distributions.")
82
+
83
+ # 2. Topic Activities Over Time
84
+ col1, col2 = st.columns(2)
85
+ with col1:
86
+ st.image("./src/Negative - Topic Activities Over Time.png", caption="Negative - Topic Activities Over Time")
87
+ with col2:
88
+ st.image("./src/Positive - Topic Activities Over Time.png", caption="Positive - Topic Activities Over Time")
89
+ st.write("Lorem ipsum explanation for Topic Activities Over Time.")
90
+
91
+ # 3. Topics Hierarchy
92
+ # col1, col2 = st.columns(2)
93
+ # with col1:
94
+ # st.image("./src/Negative - Topics Hierarchy.png", caption="Negative - Topics Hierarchy")
95
+ # with col2:
96
+ # st.image("./src/Positive - Topics Hierarchy.png", caption="Positive - Topics Hierarchy")
97
+ # st.write("Lorem ipsum explanation for Topics Hierarchy.")
98
+
99
+ # 4. Topic Weights
100
+ col1, col2 = st.columns(2)
101
+ with col1:
102
+ st.image("./src/Negative - Topics Weights.png", caption="Negative - Topic Weights")
103
+ with col2:
104
+ st.image("./src/Positive - Topics Weights.png", caption="Positive - Topic Weights")
105
+ st.write("Lorem ipsum explanation for Topics Weights.")
106
+
107
+ # =============================================
108
+ # Run Script
109
+ # =============================================
110
+ if __name__ == '__main__':
111
+ run()
src/fastopic_negative_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fba351cbeb9a08a89a53957b6b6234cf637ebfff4dec49b5ff16174e2f69885f
3
+ size 114269121
src/fastopic_positive_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a06d7de2a2d378f4e8fcb90846607e83fc655b649bbb4590415acab297bd881d
3
+ size 124508274
src/params.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:166628b4f0cd37e23ad24105f70b940c084aef6b368714a92e305576357ded45
3
+ size 43
src/prediction_compile.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================
2
+ # Import Libraries
3
+ # ============================================
4
+ import streamlit as st
5
+ import re
6
+ import pickle
7
+ import joblib
8
+ import nltk
9
+ import os
10
+ import numpy as np
11
+ import pandas as pd
12
+ from tensorflow.keras.preprocessing.sequence import pad_sequences
13
+ from tensorflow import keras
14
+ from nltk.corpus import stopwords
15
+ from nltk.tokenize import word_tokenize
16
+ from nltk.stem import PorterStemmer
17
+ from huggingface_hub import hf_hub_download
18
+
19
+ # ============================================
20
+ # Setup NLTK
21
+ # ============================================
22
+ nltk_data_path = os.path.join("/tmp", "nltk_data")
23
+ os.makedirs(nltk_data_path, exist_ok=True)
24
+ nltk.data.path.append(nltk_data_path)
25
+ nltk.download("stopwords", download_dir=nltk_data_path)
26
+ nltk.download("punkt", download_dir=nltk_data_path)
27
+
28
+ # ============================================
29
+ # Loading Info
30
+ # ============================================
31
+ st.markdown(
32
+ '<p style="color:gray; font-size:14px; font-style:italic;">'
33
+ 'Loading models (≈200 MB) and resources... this may take a while on first run. '
34
+ 'Please be patient and DO NOT refresh the page :)'
35
+ '</p>',
36
+ unsafe_allow_html=True
37
+ )
38
+
39
+ # ============================================
40
+ # Hugging Face Hub Repo
41
+ # ============================================
42
+ repo_id = "BesottenJenny/acre-sentiment-models"
43
+
44
+ # ============================================
45
+ # Cached Loading Functions
46
+ # ============================================
47
+ @st.cache_resource
48
+ def load_sentiment_model():
49
+ path = hf_hub_download(repo_id=repo_id, filename="best_model.keras")
50
+ return keras.models.load_model(path)
51
+
52
+ @st.cache_resource
53
+ def load_tokenizer_params():
54
+ tokenizer_path = hf_hub_download(repo_id=repo_id, filename="tokenizer.pkl")
55
+ params_path = hf_hub_download(repo_id=repo_id, filename="params.pkl")
56
+ with open(tokenizer_path, "rb") as f:
57
+ tokenizer = pickle.load(f)
58
+ with open(params_path, "rb") as f:
59
+ params = pickle.load(f)
60
+ return tokenizer, params
61
+
62
+ @st.cache_resource
63
+ def load_topic_models():
64
+ neg_path = hf_hub_download(repo_id=repo_id, filename="fastopic_negative_model.pkl")
65
+ pos_path = hf_hub_download(repo_id=repo_id, filename="fastopic_positive_model.pkl")
66
+ neg_model = joblib.load(neg_path)
67
+ pos_model = joblib.load(pos_path)
68
+ return neg_model, pos_model
69
+
70
+ # ============================================
71
+ # Load all resources once
72
+ # ============================================
73
+ sentiment_model = load_sentiment_model()
74
+ tokenizer, params = load_tokenizer_params()
75
+ topic_model_neg, topic_model_pos = load_topic_models()
76
+
77
+ max_len = params["max_len"]
78
+
79
+ # ============================================
80
+ # Preprocessing Function (NLTK)
81
+ # ============================================
82
+ negations = {"not", "no", "never"}
83
+ stpwrds_en = set(stopwords.words("english")) - negations
84
+ stemmer = PorterStemmer()
85
+
86
+ replacements = {
87
+ "sia": "sq",
88
+ "flown": "fly",
89
+ "flew": "fly",
90
+ "alway": "always",
91
+ "boarding": "board",
92
+ "told": "tell",
93
+ "said": "say",
94
+ "booked": "book",
95
+ "paid": "pay",
96
+ "well": "good",
97
+ "aircraft": "plane"
98
+ }
99
+
100
+ def text_preprocessing(text):
101
+ text = text.lower()
102
+ text = re.sub(r"\\n", " ", text)
103
+ text = text.strip()
104
+ text = re.sub(r'[^a-z0-9\s]', ' ', text)
105
+ tokens = word_tokenize(text)
106
+ tokens = [replacements.get(word, word) for word in tokens]
107
+ tokens = [word for word in tokens if word not in stpwrds_en]
108
+ tokens = [stemmer.stem(word) for word in tokens]
109
+ if len(tokens) == 0:
110
+ return "emptytext"
111
+ return ' '.join(tokens)
112
+
113
+ # ============================================
114
+ # Streamlit App
115
+ # ============================================
116
+ def run():
117
+ st.title("ACRE - Automated Customer Review Analysis")
118
+ st.subheader("Sentiment & Topic Prediction for SQ Customer Reviews")
119
+ st.markdown(
120
+ """
121
+ This section will help you understand how the **ACRE** system works.
122
+ Simply fill in the form below with either a dummy or real customer review, and the system will:
123
+
124
+ 1. **Preprocess** your review text (cleaning, tokenization, and stemming).
125
+ 2. **Predict sentiment** (Positive or Negative) along with a confidence score.
126
+ 3. **Identify the most relevant topic** associated with the review, based on the predicted sentiment.
127
+
128
+ Use this tool to simulate how Singapore Airlines can transform raw customer feedback into **structured, data-driven insights**.
129
+ """
130
+ )
131
+
132
+ with st.form(key='SQ-sentiment-analysis'):
133
+ date = st.date_input("Review Date")
134
+ platform = st.selectbox('Review Platform', ('Mobile', 'Desktop'), index=0)
135
+ rating = st.number_input('Rating', min_value=0, max_value=5, value=3, step=1)
136
+ st.markdown('---')
137
+ text = st.text_input('Customer Review', value='--customer review--')
138
+ title = st.text_input('Review Title', value='--review title--')
139
+ vote = st.slider('Helpful Vote', min_value=0, max_value=200, value=50, step=1)
140
+ st.markdown('---')
141
+ submitted = st.form_submit_button('Predict')
142
+
143
+ if submitted:
144
+ st.markdown("---")
145
+ st.write("### Input Data")
146
+ data_inf = {
147
+ 'published_date': date,
148
+ 'published_platform': platform,
149
+ 'rating': rating,
150
+ 'type': 'Review',
151
+ 'text': text,
152
+ 'title': title,
153
+ 'helpful_votes': vote
154
+ }
155
+ st.dataframe(pd.DataFrame([data_inf]))
156
+
157
+ # Preprocess
158
+ processed = text_preprocessing(text)
159
+ seq = tokenizer.texts_to_sequences([processed])
160
+ padded = pad_sequences(seq, maxlen=max_len, padding="post", truncating="post")
161
+
162
+ # Sentiment Prediction
163
+ pred_probs = sentiment_model.predict(padded)
164
+ pred_class = np.argmax(pred_probs, axis=1)[0]
165
+ confidence = float(np.max(pred_probs))
166
+
167
+ label_map = {0: "Negative", 1: "Positive"}
168
+ sentiment_label = label_map[pred_class]
169
+
170
+ st.write("### Sentiment Prediction")
171
+ if sentiment_label == "Negative":
172
+ st.markdown(f"<h3 style='color:red;'>Predicted Sentiment: {sentiment_label}</h3>", unsafe_allow_html=True)
173
+ else:
174
+ st.markdown(f"<h3 style='color:green;'>Predicted Sentiment: {sentiment_label}</h3>", unsafe_allow_html=True)
175
+ st.write(f"**Confidence:** {confidence:.2f}")
176
+
177
+ # Topic Prediction
178
+ st.write("### Topic Modeling")
179
+ if sentiment_label == "Negative":
180
+ topics, probs = topic_model_neg.transform([text])
181
+ st.write("**Using Negative Model**")
182
+ st.markdown(f"<p style='color:red;'>Topic ID(s): {topics}</p>", unsafe_allow_html=True)
183
+ else:
184
+ topics, probs = topic_model_pos.transform([text])
185
+ st.write("**Using Positive Model**")
186
+ st.markdown(f"<p style='color:green;'>Topic ID(s): {topics}</p>", unsafe_allow_html=True)
187
+
188
+ st.write(f"**Probabilities:** {probs.tolist()}")
189
+
190
+ # ============================================
191
+ # Run App
192
+ # ============================================
193
+ if __name__ == "__main__":
194
+ run()
src/singapore_airlines_reviews.csv ADDED
The diff for this file is too large to render. See raw diff
 
src/tokenizer.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:814c12639a83d0262d298a91e1aeb404f281dbebd1224b620deea0b36eeb5ad3
3
+ size 453750