Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
CHANGED
|
@@ -3,14 +3,24 @@ from sklearn.feature_extraction.text import TfidfVectorizer
|
|
| 3 |
from sklearn.cluster import KMeans
|
| 4 |
import gradio as gr
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
vectorizer = TfidfVectorizer(stop_words='english', ngram_range=(1, 2), max_df=0.9)
|
| 10 |
X = vectorizer.fit_transform(titles)
|
|
|
|
| 11 |
model = KMeans(n_clusters=n_clusters, random_state=42)
|
| 12 |
df['topic'] = model.fit_predict(X)
|
| 13 |
|
|
|
|
| 14 |
output = ""
|
| 15 |
for i in range(n_clusters):
|
| 16 |
output += f"\n### Topic {i}\n"
|
|
@@ -18,12 +28,13 @@ def topic_modeling(file, n_clusters):
|
|
| 18 |
output += "\n".join(f"- {t}" for t in top_titles) + "\n"
|
| 19 |
return output
|
| 20 |
|
|
|
|
| 21 |
iface = gr.Interface(
|
| 22 |
fn=topic_modeling,
|
| 23 |
-
inputs=[gr.
|
| 24 |
outputs="markdown",
|
| 25 |
title="Topic Modeling App (TF-IDF + KMeans)",
|
| 26 |
-
description="
|
| 27 |
)
|
| 28 |
|
| 29 |
if __name__ == "__main__":
|
|
|
|
| 3 |
from sklearn.cluster import KMeans
|
| 4 |
import gradio as gr
|
| 5 |
|
| 6 |
+
# Adjust the file path to where titles.csv is located in your environment
|
| 7 |
+
CSV_FILE_PATH = 'titles.csv' # Update this with the correct path to your CSV file
|
| 8 |
+
|
| 9 |
+
def topic_modeling(n_clusters):
|
| 10 |
+
# Read the CSV file directly from the specified file path
|
| 11 |
+
df = pd.read_csv(CSV_FILE_PATH)
|
| 12 |
+
|
| 13 |
+
if 'title' not in df.columns:
|
| 14 |
+
return "Error: CSV does not contain a 'title' column"
|
| 15 |
+
|
| 16 |
+
titles = df['title'].astype(str).tolist() # Convert the 'title' column to a list of strings
|
| 17 |
vectorizer = TfidfVectorizer(stop_words='english', ngram_range=(1, 2), max_df=0.9)
|
| 18 |
X = vectorizer.fit_transform(titles)
|
| 19 |
+
|
| 20 |
model = KMeans(n_clusters=n_clusters, random_state=42)
|
| 21 |
df['topic'] = model.fit_predict(X)
|
| 22 |
|
| 23 |
+
# Prepare the output to display the top titles for each topic
|
| 24 |
output = ""
|
| 25 |
for i in range(n_clusters):
|
| 26 |
output += f"\n### Topic {i}\n"
|
|
|
|
| 28 |
output += "\n".join(f"- {t}" for t in top_titles) + "\n"
|
| 29 |
return output
|
| 30 |
|
| 31 |
+
# Define the Gradio interface (no file input, just a slider for n_clusters)
|
| 32 |
iface = gr.Interface(
|
| 33 |
fn=topic_modeling,
|
| 34 |
+
inputs=[gr.Slider(2, 10, step=1, value=5, label="Number of Topics")],
|
| 35 |
outputs="markdown",
|
| 36 |
title="Topic Modeling App (TF-IDF + KMeans)",
|
| 37 |
+
description="This app clusters titles from a CSV file into topics using TF-IDF and KMeans. No file upload needed."
|
| 38 |
)
|
| 39 |
|
| 40 |
if __name__ == "__main__":
|