Spaces:
Runtime error
Runtime error
Update app.py
Browse files1 unmodified line23456789910101112131415161718192021222316242526192728293023313233263435362937383940414243444546383940414243444748495051524953545152555657585559606162636465661 unmodified linefrom bertopic import BERTopicfrom sentence_transformers import SentenceTransformer
def run_from_textfile(file): if file is None: return "Please upload a .txt file.", "", None
# Read text file text = file.read().decode("utf-8") # ---- Handle file input for both HuggingFace and local environments ---- try: # HuggingFace Spaces: file is NamedString and supports .decode() text = file.decode("utf-8") except: # Local Gradio: file is a TemporaryFile-like object text = file.read().decode("utf-8")
# Split the text into documents (one per line) docs = [line.strip() for line in text.split("\n") if line.strip()]
if len(docs) < 3: return "Need at least 3 documents (one per line).", "", None
# Embedding model # ---- Embedding Model ---- embedder = SentenceTransformer("all-MiniLM-L6-v2")
# Topic model # ---- Topic Modeling ---- topic_model = BERTopic(embedding_model=embedder) topics, probs = topic_model.fit_transform(docs)
# Topic info # ---- Topic Summary ---- topic_info = topic_model.get_topic_info().to_string()
# Map each doc to its topic # ---- Document → Topic Assignments ---- assignments = "\n".join([f"Doc {i+1}: Topic {topics[i]}" for i in range(len(docs))])
# Visualization # ---- Visualization ---- fig = topic_model.visualize_barchart(top_n_topics=10)
return topic_info, assignments, fig
# ---- Gradio Interface ----with gr.Blocks() as demo: gr.Markdown("# 🧠 Topic Modeling from TXT File (BERTopic)") gr.Markdown( "Upload a plain text (.txt) file. Each line should contain one LLM response.\n\n" "Example format:\n" "```\n" "Response 1...\n" "Response 2...\n" "Response 3...\n" "```\n" "Upload a plain text (.txt) file. Each line should contain **one LLM response**.\n" "\nExample format:\n```\nResponse 1...\nResponse 2...\nResponse 3...\n```" )
file_input = gr.File(label="Upload .txt file")
run_btn = gr.Button("Run Topic Modeling") run_button = gr.Button("Run Topic Modeling")
topic_output = gr.Textbox(label="Topic Overview", lines=10) assignment_output = gr.Textbox(label="Document → Topic Assignments", lines=10) topic_output = gr.Textbox(label="Topic Overview", lines=12) assignment_output = gr.Textbox(label="Document → Topic Assignments", lines=12) fig_output = gr.Plot(label="Topic Visualization")
run_btn.click( run_button.click( fn=run_from_textfile, inputs=file_input, outputs=[topic_output, assignment_output, fig_output] )
# Launch appdemo.launch()app.py+23-18