Spaces:
Sleeping
Sleeping
Add Gradio app files
Browse files- .gradio/certificate.pem +31 -0
- .gradio/flagged/dataset1.csv +2 -0
- app.py +407 -0
- data/app_reviews_1y_ex3.csv +0 -0
- model/best_model.pkl +3 -0
- model/vectorizer.pkl +3 -0
- requirements.txt +11 -0
.gradio/certificate.pem
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
-----BEGIN CERTIFICATE-----
|
| 2 |
+
MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw
|
| 3 |
+
TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh
|
| 4 |
+
cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4
|
| 5 |
+
WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu
|
| 6 |
+
ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY
|
| 7 |
+
MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc
|
| 8 |
+
h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+
|
| 9 |
+
0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U
|
| 10 |
+
A5/TR5d8mUgjU+g4rk8Kb4Mu0UlX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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import matplotlib.pyplot as plt
|
| 2 |
+
import plotly.express as px
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from google_play_scraper import Sort, reviews, app
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
import io
|
| 8 |
+
import google.generativeai as genai
|
| 9 |
+
import re
|
| 10 |
+
from nltk.corpus import stopwords
|
| 11 |
+
from Sastrawi.Stemmer.StemmerFactory import StemmerFactory
|
| 12 |
+
from Sastrawi.StopWordRemover.StopWordRemoverFactory import StopWordRemoverFactory
|
| 13 |
+
import pickle
|
| 14 |
+
import nltk
|
| 15 |
+
nltk.download('stopwords')
|
| 16 |
+
|
| 17 |
+
# Tujuan file disimpan
|
| 18 |
+
destination_file_1y_ex3 = 'data/app_reviews_1y_ex3.csv'
|
| 19 |
+
model_file = 'model/best_model.pkl'
|
| 20 |
+
vectorizer_file = 'model/vectorizer.pkl'
|
| 21 |
+
|
| 22 |
+
# Global variables to store API key and model name
|
| 23 |
+
api_key = None
|
| 24 |
+
model_name = "gemini-2.0-flash" # Default model name
|
| 25 |
+
|
| 26 |
+
with open(model_file, 'rb') as file:
|
| 27 |
+
best_model = pickle.load(file)
|
| 28 |
+
|
| 29 |
+
with open(vectorizer_file, 'rb') as file:
|
| 30 |
+
vectorizer = pickle.load(file)
|
| 31 |
+
|
| 32 |
+
# Cache stop words
|
| 33 |
+
indonesian_stopwords = stopwords.words('indonesian')
|
| 34 |
+
|
| 35 |
+
# Create stemmer
|
| 36 |
+
factory = StemmerFactory()
|
| 37 |
+
stemmer = factory.create_stemmer()
|
| 38 |
+
|
| 39 |
+
# Create stop word remover
|
| 40 |
+
stopword_factory = StopWordRemoverFactory()
|
| 41 |
+
stopword_remover = stopword_factory.create_stop_word_remover()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def preprocess_text(text):
|
| 45 |
+
# 1. Handle None values
|
| 46 |
+
if text is None:
|
| 47 |
+
return "" # Or any other suitable replacement
|
| 48 |
+
|
| 49 |
+
# Lowercase and remove punctuation & special characters in one step
|
| 50 |
+
text = re.sub(r'[^\w\s\d]+', '', text.lower())
|
| 51 |
+
|
| 52 |
+
# Remove extra whitespaces
|
| 53 |
+
text = re.sub(r'\s+', ' ', text).strip()
|
| 54 |
+
|
| 55 |
+
# Stemming and stop word removal using NLTK and list comprehension
|
| 56 |
+
text = stemmer.stem(text) # Indonesian stemming
|
| 57 |
+
text = stopword_remover.remove(text) # Indonesian stopword removal
|
| 58 |
+
words = text.split()
|
| 59 |
+
words = [word for word in words if word not in indonesian_stopwords] # Remove Indonesian stopwords
|
| 60 |
+
text = " ".join(words)
|
| 61 |
+
|
| 62 |
+
return text
|
| 63 |
+
|
| 64 |
+
def predict_sentiment(text):
|
| 65 |
+
# Preprocess the input text
|
| 66 |
+
processed_text = preprocess_text(text)
|
| 67 |
+
|
| 68 |
+
# Transform the text using the loaded vectorizer
|
| 69 |
+
text_vectorized = vectorizer.transform([processed_text])
|
| 70 |
+
|
| 71 |
+
# Predict the sentiment
|
| 72 |
+
prediction = best_model.predict(text_vectorized)[0]
|
| 73 |
+
return prediction
|
| 74 |
+
|
| 75 |
+
# Fungsi untuk melakukan labeling dengan gemini api
|
| 76 |
+
def label_sentiment_with_gemini(text, api_key, model_name):
|
| 77 |
+
"""Melakukan labeling sentimen menggunakan Gemini."""
|
| 78 |
+
prompt = f"""Klasifikasikan sentimen ulasan berikut menjadi: '1.puas', '2.tidak puas', '3.netral'.
|
| 79 |
+
Perhatikan sarkasme dan sindiran, atau ekspresi negatif/positif halus, serta bahasa yang digunakan.
|
| 80 |
+
**Ulasan:** {text}
|
| 81 |
+
**Tampilkan hanya Sentimen**
|
| 82 |
+
"""
|
| 83 |
+
try:
|
| 84 |
+
genai.configure(api_key=api_key) # Konfigurasi Gemini API di dalam fungsi
|
| 85 |
+
model = genai.GenerativeModel(model_name)
|
| 86 |
+
response = model.generate_content(prompt)
|
| 87 |
+
generated_content = response.text.strip().lower()
|
| 88 |
+
generated_content = re.sub(' ', '', generated_content)
|
| 89 |
+
|
| 90 |
+
if "1.puas" in generated_content:
|
| 91 |
+
return "puas"
|
| 92 |
+
elif "2.tidakpuas" in generated_content:
|
| 93 |
+
return "tidak puas"
|
| 94 |
+
else:
|
| 95 |
+
return "netral"
|
| 96 |
+
except genai.errors.ResourceExhaustedError:
|
| 97 |
+
print("Error: Rate limit exceeded. Please try again later.")
|
| 98 |
+
return "netral" # or another appropriate default value
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"An unexpected error occurred: {e}")
|
| 101 |
+
return "netral" # or another appropriate default value
|
| 102 |
+
|
| 103 |
+
def predict_and_label(text):
|
| 104 |
+
try:
|
| 105 |
+
if not text: # Check if the text input is empty
|
| 106 |
+
raise gr.Error("Please enter a review.") # Raise a Gradio error with a message
|
| 107 |
+
|
| 108 |
+
prediction = predict_sentiment(text)
|
| 109 |
+
# Konversi np.str_ menjadi str
|
| 110 |
+
prediction = prediction.item() # Atau prediction.astype(str)
|
| 111 |
+
|
| 112 |
+
label_gemini = label_sentiment_with_gemini(text, api_key, model_name)
|
| 113 |
+
return prediction, label_gemini
|
| 114 |
+
|
| 115 |
+
except (ValueError, TypeError, AttributeError) as e:
|
| 116 |
+
# Catch specific errors related to data types, empty inputs, and unexpected values
|
| 117 |
+
raise gr.Error(f"Error processing input: {type(e).__name__}. Please check your input.")
|
| 118 |
+
except genai.errors.ResourceExhaustedError:
|
| 119 |
+
# Handle rate limit exceeded error
|
| 120 |
+
raise gr.Error("Error: Rate limit exceeded for Gemini API/You forgot to update API_KEY. Please try again later.")
|
| 121 |
+
except Exception as e:
|
| 122 |
+
# Catch any other unexpected errors
|
| 123 |
+
raise gr.Error(f"An unexpected error occurred: {type(e).__name__}. Please try again later.")
|
| 124 |
+
|
| 125 |
+
def update_api_credentials(new_api_key, new_model_name):
|
| 126 |
+
global api_key, model_name # Access the global variables
|
| 127 |
+
api_key = str(new_api_key)
|
| 128 |
+
model_name = str(new_model_name)
|
| 129 |
+
|
| 130 |
+
#test api and show successfull if connected
|
| 131 |
+
try:
|
| 132 |
+
genai.configure(api_key=api_key) # Konfigurasi Gemini API di dalam fungsi
|
| 133 |
+
model = genai.GenerativeModel(model_name)
|
| 134 |
+
response = model.generate_content("Test API Connection.Just say Yes if successfull")
|
| 135 |
+
generated_content = response.text.strip().lower()
|
| 136 |
+
|
| 137 |
+
except genai.errors.ResourceExhaustedError:
|
| 138 |
+
print("Error: Rate limit exceeded. Please try again later.")
|
| 139 |
+
return "Error: Rate limit exceeded. Please try again later."
|
| 140 |
+
except Exception as e:
|
| 141 |
+
print(f"An unexpected error occurred: {e}")
|
| 142 |
+
return "An unexpected error occurred. Please try again later."
|
| 143 |
+
|
| 144 |
+
print(f"API Key: {api_key}")
|
| 145 |
+
print(f"Model Name: {model_name}")
|
| 146 |
+
return generated_content, " API credentials updated successfully!"
|
| 147 |
+
|
| 148 |
+
def scrape_and_show_data():
|
| 149 |
+
try:
|
| 150 |
+
# List App Packages
|
| 151 |
+
app_packages = [
|
| 152 |
+
'id.dana', #Dana
|
| 153 |
+
'com.shopeepay.id', #Shopeepay
|
| 154 |
+
'com.gojek.gopay', #Gopay
|
| 155 |
+
'ovo.id', #Ovo
|
| 156 |
+
]
|
| 157 |
+
|
| 158 |
+
language = 'id'
|
| 159 |
+
country = 'id'
|
| 160 |
+
|
| 161 |
+
app_reviews = []
|
| 162 |
+
current_date = datetime.now()
|
| 163 |
+
one_year_ago = current_date - timedelta(days=365)
|
| 164 |
+
|
| 165 |
+
for ap in app_packages:
|
| 166 |
+
for score in [1, 2, 3, 4, 5]: # Ambil semua rating (1-5)
|
| 167 |
+
rvs, _ = reviews(
|
| 168 |
+
ap,
|
| 169 |
+
lang=language,
|
| 170 |
+
country=country,
|
| 171 |
+
sort=Sort.NEWEST, # Hanya ambil ulasan terbaru (newest)
|
| 172 |
+
count=10, # Sesuaikan jumlah ulasan yang ingin di-scrape
|
| 173 |
+
filter_score_with=score
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# Filter ulasan untuk satu tahun terakhir
|
| 177 |
+
for r in rvs:
|
| 178 |
+
review_date = datetime.strptime(r['at'].strftime("%Y-%m-%d"), "%Y-%m-%d")
|
| 179 |
+
if review_date >= one_year_ago:
|
| 180 |
+
r['sortOrder'] = 'newest' # Tetapkan sortOrder menjadi 'newest'
|
| 181 |
+
r['appId'] = ap
|
| 182 |
+
app_reviews.append(r)
|
| 183 |
+
|
| 184 |
+
df = pd.DataFrame(app_reviews)
|
| 185 |
+
# Buat label (misal: score 4-5 puas, 3 netral, 1-2 nggak puas)
|
| 186 |
+
def label_sentiment(score):
|
| 187 |
+
if score >= 4:
|
| 188 |
+
return 'puas'
|
| 189 |
+
elif score < 3:
|
| 190 |
+
return 'tidak_puas'
|
| 191 |
+
else:
|
| 192 |
+
return 'netral'
|
| 193 |
+
|
| 194 |
+
df['rating'] = df['score'].apply(label_sentiment)
|
| 195 |
+
|
| 196 |
+
# Load Apps Info
|
| 197 |
+
app_infos = []
|
| 198 |
+
|
| 199 |
+
for ap in app_packages:
|
| 200 |
+
info = app(ap, lang=language, country=country)
|
| 201 |
+
del info['comments']
|
| 202 |
+
app_infos.append(info)
|
| 203 |
+
|
| 204 |
+
app_infos_df = pd.DataFrame(app_infos)
|
| 205 |
+
df = pd.merge(df, app_infos_df[['appId', 'title']], on='appId', how='left')
|
| 206 |
+
df = df.sort_values(by='at', ascending=False).head(10)
|
| 207 |
+
|
| 208 |
+
# predict the data with predict_and_label. The result have 2 list, example is ('puas', 'netral'). Put to dataframe for column predict_model and predict_gemini
|
| 209 |
+
df['predict_model'], df['predict_gemini'] = zip(*df['content'].apply(predict_and_label))
|
| 210 |
+
|
| 211 |
+
# show only column at rename as date, content, rating, and order desc by date
|
| 212 |
+
df = df[['title','at', 'content', 'score', 'rating','predict_model','predict_gemini']].rename(columns={'at': 'date'})
|
| 213 |
+
|
| 214 |
+
return df
|
| 215 |
+
|
| 216 |
+
except Exception as e:
|
| 217 |
+
raise gr.Error(f"Error scraping data: {type(e).__name__}. Please check your app package names and connection.")
|
| 218 |
+
|
| 219 |
+
def scrape_and_download_data(app_packages, language, country, sort, score, start_date, end_date, count):
|
| 220 |
+
try:
|
| 221 |
+
app_reviews = []
|
| 222 |
+
|
| 223 |
+
# Convert app_packages to a list if it's a string
|
| 224 |
+
if isinstance(app_packages, str):
|
| 225 |
+
app_packages = [app_packages]
|
| 226 |
+
|
| 227 |
+
# Convert date strings to datetime objects (if needed)
|
| 228 |
+
if isinstance(start_date, str):
|
| 229 |
+
start_date = datetime.strptime(start_date, "%Y-%m-%d")
|
| 230 |
+
if isinstance(end_date, str):
|
| 231 |
+
end_date = datetime.strptime(end_date, "%Y-%m-%d")
|
| 232 |
+
|
| 233 |
+
# Scrape data based on criteria
|
| 234 |
+
for ap in app_packages:
|
| 235 |
+
for scr in str(score): # Ambil semua rating (1-5)
|
| 236 |
+
rvs, _ = reviews(
|
| 237 |
+
ap,
|
| 238 |
+
lang=str(language), # Convert language to string
|
| 239 |
+
country=str(country), # Convert country to string
|
| 240 |
+
sort=Sort.NEWEST if str(sort) == 'NEWEST' else Sort.MOST_RELEVANT,
|
| 241 |
+
count=int(count),
|
| 242 |
+
filter_score_with=scr,
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
# Filter reviews based on date range and other criteria
|
| 246 |
+
for r in rvs:
|
| 247 |
+
review_date = datetime.strptime(r['at'].strftime("%Y-%m-%d"), "%Y-%m-%d")
|
| 248 |
+
if start_date <= review_date <= end_date: # Date range filter
|
| 249 |
+
r['sortOrder'] = sort
|
| 250 |
+
r['appId'] = ap
|
| 251 |
+
app_reviews.append(r)
|
| 252 |
+
|
| 253 |
+
# Create DataFrame
|
| 254 |
+
df = pd.DataFrame(app_reviews)
|
| 255 |
+
|
| 256 |
+
# Check if DataFrame is empty
|
| 257 |
+
if df.empty:
|
| 258 |
+
# Handle empty DataFrame, e.g., return an empty DataFrame or raise an exception
|
| 259 |
+
print("DataFrame is empty. No reviews found for the specified criteria.")
|
| 260 |
+
return df # or: raise ValueError("No reviews found for the specified criteria.")
|
| 261 |
+
else:
|
| 262 |
+
# Load Apps Info
|
| 263 |
+
app_infos = []
|
| 264 |
+
|
| 265 |
+
for ap in app_packages:
|
| 266 |
+
info = app(ap, lang=language, country=country)
|
| 267 |
+
del info['comments']
|
| 268 |
+
app_infos.append(info)
|
| 269 |
+
|
| 270 |
+
app_infos_df = pd.DataFrame(app_infos)
|
| 271 |
+
df = pd.merge(df, app_infos_df[['appId', 'title']], on='appId', how='left')
|
| 272 |
+
|
| 273 |
+
# Create label if DataFrame is not empty
|
| 274 |
+
def label_sentiment(score):
|
| 275 |
+
if score >= 4:
|
| 276 |
+
return 'puas'
|
| 277 |
+
elif score < 3:
|
| 278 |
+
return 'tidak_puas'
|
| 279 |
+
else:
|
| 280 |
+
return 'netral'
|
| 281 |
+
|
| 282 |
+
df['rating'] = df['score'].apply(label_sentiment)
|
| 283 |
+
|
| 284 |
+
# show only column title, at, sortOrder, reviewId, userName, userImage, content, score, thumbsUpCount, replyContent, repliedAt, rating
|
| 285 |
+
df = df[['title','at', 'sortOrder', 'reviewId', 'userName', 'userImage', 'content', 'score', 'thumbsUpCount', 'replyContent', 'repliedAt', 'rating']].rename(columns={'at': 'date'}) # Rename 'at' to 'date
|
| 286 |
+
df = df.sort_values(by='date', ascending=False)
|
| 287 |
+
|
| 288 |
+
return df
|
| 289 |
+
|
| 290 |
+
except Exception as e:
|
| 291 |
+
raise gr.Error(f"Error scraping or processing data: {type(e).__name__}. Please check your inputs and connection.")
|
| 292 |
+
|
| 293 |
+
# def create_charts():
|
| 294 |
+
# # 1. Rating Distribution Pie Chart
|
| 295 |
+
# df = scrape_and_show_data()
|
| 296 |
+
# rating_counts = df['rating'].value_counts()
|
| 297 |
+
|
| 298 |
+
# # Create the pie chart using Matplotlib
|
| 299 |
+
# fig_pie, ax_pie = plt.subplots()
|
| 300 |
+
# ax_pie.pie(rating_counts, labels=rating_counts.index, autopct='%1.1f%%', startangle=90)
|
| 301 |
+
# ax_pie.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
|
| 302 |
+
# plt.title("Rating Distribution")
|
| 303 |
+
|
| 304 |
+
# # Convert to gradio plot
|
| 305 |
+
# rating_pie_chart = gr.Plot(value=fig_pie) # Using gr.Plot
|
| 306 |
+
|
| 307 |
+
# # 2. Daily Reviews Line Chart
|
| 308 |
+
# daily_reviews = df.groupby('date').size().reset_index(name='total_reviews')
|
| 309 |
+
|
| 310 |
+
# # Create line chart using Plotly
|
| 311 |
+
# fig_line = px.line(daily_reviews, x='date', y='total_reviews', title='Total Reviews per Day')
|
| 312 |
+
# fig_line.update_traces(mode='markers+lines')
|
| 313 |
+
|
| 314 |
+
# # Convert to gradio plot
|
| 315 |
+
# daily_reviews_chart = gr.Plot(value=fig_line) # Using gr.Plot
|
| 316 |
+
|
| 317 |
+
# return rating_pie_chart, daily_reviews_chart # Return both gradio plots
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
with gr.Blocks() as apps:
|
| 321 |
+
with gr.Tabs():
|
| 322 |
+
with gr.TabItem("Prediction Existing Data"):
|
| 323 |
+
# Sentiment Prediction section
|
| 324 |
+
|
| 325 |
+
gr.Interface(
|
| 326 |
+
fn=predict_and_label,
|
| 327 |
+
inputs=[
|
| 328 |
+
gr.Textbox(lines=5, label="Masukkan Ulasan"),
|
| 329 |
+
],
|
| 330 |
+
outputs=[
|
| 331 |
+
gr.Textbox(label="Prediksi Model",info="Prediksi Model Sentiment"),
|
| 332 |
+
gr.Textbox(label="Prediksi Gemini",info="Prediksi Gemini Sentiment"),
|
| 333 |
+
],
|
| 334 |
+
title="Prediksi Sentimen Ulasan Aplikasi Transportasi",
|
| 335 |
+
description="Masukkan ulasan Anda untuk memprediksi sentimen (puas, tidak puas).",
|
| 336 |
+
api_name="prediksi_sentimen"
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
gr.Interface(
|
| 340 |
+
fn=scrape_and_show_data,
|
| 341 |
+
inputs=None,
|
| 342 |
+
outputs=gr.Dataframe(label="Cleaned Reviews DataFrame",wrap=True),
|
| 343 |
+
description="Displaying the Latest the Data:",
|
| 344 |
+
api_name="prediksi_sentimen_latest"
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
# gr.Interface(
|
| 348 |
+
# fn=create_charts,
|
| 349 |
+
# inputs=None,
|
| 350 |
+
# outputs=[
|
| 351 |
+
# gr.Plot(label="Rating Distribution"),
|
| 352 |
+
# gr.Plot(label="Daily Reviews"),
|
| 353 |
+
# ],
|
| 354 |
+
# description="Displaying Charts:",
|
| 355 |
+
# )
|
| 356 |
+
|
| 357 |
+
with gr.TabItem("Download New Data"):
|
| 358 |
+
with gr.Column(): # Place input elements in a column
|
| 359 |
+
app_packages_input = gr.Textbox(label="App Packages (comma-separated)", value="com.gojek.gopay",info="Enter app packages separated by commas")
|
| 360 |
+
language_input = gr.Textbox(label="Language", value="id", info="Enter language code")
|
| 361 |
+
country_input = gr.Textbox(label="Country", value="id", info="Enter country code")
|
| 362 |
+
sort_input = gr.Radio(["NEWEST", "MOST_RELEVANT"], label="Sort Order", value="NEWEST", info="Select sort order")
|
| 363 |
+
scores_input = gr.CheckboxGroup([1, 2, 3, 4, 5], label="Scores", value=[1, 2, 3, 4, 5], info="Select scores")
|
| 364 |
+
start_date_input = gr.Textbox(label="Start Date (YYYY-MM-DD)", value=(datetime.now() - timedelta(days=365)).strftime("%Y-%m-%d"),info="Enter start date (YYYY-MM-DD)")
|
| 365 |
+
end_date_input = gr.Textbox(label="End Date (YYYY-MM-DD)", value=datetime.now().strftime("%Y-%m-%d"),info="Enter end date (YYYY-MM-DD)")
|
| 366 |
+
count = gr.Textbox(label="Count", value="10",info="Enter count")
|
| 367 |
+
|
| 368 |
+
generate_button = gr.Button("Generate Data")
|
| 369 |
+
download_button = gr.DownloadButton(label="Download Data")
|
| 370 |
+
|
| 371 |
+
# Place output elements below the input column
|
| 372 |
+
output_data = gr.Dataframe(label="Scraped Data", wrap=True)
|
| 373 |
+
|
| 374 |
+
generate_button.click(
|
| 375 |
+
fn=scrape_and_download_data,
|
| 376 |
+
inputs=[app_packages_input, language_input, country_input, sort_input, scores_input, start_date_input, end_date_input, count],
|
| 377 |
+
outputs=[output_data],
|
| 378 |
+
api_name="generate_data"
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
download_button.click(
|
| 382 |
+
fn=lambda df: io.StringIO(df.to_csv(index=False)), # Convert DataFrame to CSV in memory
|
| 383 |
+
inputs=output_data,
|
| 384 |
+
outputs=download_button,
|
| 385 |
+
api_name="download_data"
|
| 386 |
+
)
|
| 387 |
+
|
| 388 |
+
with gr.TabItem("API Settings"): # New tab for API settings
|
| 389 |
+
with gr.Row():
|
| 390 |
+
api_key_input = gr.Textbox(label="API Key", value="", info="Enter your API key")
|
| 391 |
+
model_name_input = gr.Textbox(label="Model Name", value="gemini-2.0-flash", info="Enter the model name")
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
update_button = gr.Button("Check and Update API Credentials")
|
| 395 |
+
|
| 396 |
+
update_button.click(
|
| 397 |
+
fn=update_api_credentials,
|
| 398 |
+
inputs=[api_key_input, model_name_input],
|
| 399 |
+
outputs=gr.Textbox(label="Status"),
|
| 400 |
+
api_name="update_api_credentials"
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
# information to get API Key on https://aistudio.google.com/app/apikey
|
| 404 |
+
gr.Markdown("Get API Key on https://aistudio.google.com/app/apikey")
|
| 405 |
+
|
| 406 |
+
|
| 407 |
+
apps.launch(share=True,debug=True, auth=("admin", "admin"))
|
data/app_reviews_1y_ex3.csv
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
model/best_model.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b055a653bcf592c0d1a2b11a45b0200b736b5988ed1020853b3114ffaa03e485
|
| 3 |
+
size 184548
|
model/vectorizer.pkl
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cdd9ff7d4c16e716bee257c28b5b3012dbad7db084897843feea28cbe867d25a
|
| 3 |
+
size 119777
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pandas
|
| 2 |
+
gradio
|
| 3 |
+
google-play-scraper
|
| 4 |
+
pySastrawi
|
| 5 |
+
google-generativeai
|
| 6 |
+
openpyxl
|
| 7 |
+
nltk
|
| 8 |
+
plotly
|
| 9 |
+
matplotlib
|
| 10 |
+
seaborn
|
| 11 |
+
scikit-learn
|