Spaces:
Runtime error
Runtime error
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344451 unmodified line4748495051525354555657585960611 unmodified line63646566import gradio as grfrom bertopic import BERTopicfrom sentence_transformers import SentenceTransformerdef run_from_textfile(file):if file is None:return "Please upload a .txt file.", "", None# ---- 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 objecttext = 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 ----embedder = SentenceTransformer("all-MiniLM-L6-v2")# ---- Topic Modeling ----topic_model = BERTopic(embedding_model=embedder)topics, probs = topic_model.fit_transform(docs)# ---- Topic Summary ----topic_info = topic_model.get_topic_info().to_string()# ---- Document → Topic Assignments ----assignments = "\n".join([f"Doc {i+1}: Topic {topics[i]}" for i in range(len(docs))])# ---- 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)")1 unmodified line"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_button = gr.Button("Run Topic Modeling")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_button.click(fn=run_from_textfile,inputs=file_input,1 unmodified line)# Launch appdemo.launch()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071721 unmodified line74757677787980818283848586878889901 unmodified line92939495import gradio as grfrom bertopic import BERTopicfrom sentence_transformers import SentenceTransformerimport os # Import os for potential path checks, though the logic below is keydef run_from_textfile(file):if file is None:return "Please upload a .txt file.", "", None# ---- Handle file input: Unify access for NamedString (Spaces) and file object (Local) ----text = ""# 1. Check for the .decode() method, which is characteristic of the Gradio NamedString object# used in some environments (like HuggingFace Spaces).if hasattr(file, 'decode'):try:# HuggingFace Spaces/NamedString: file supports .decode() directlytext = file.decode("utf-8")except Exception as e:return f"Error decoding NamedString: {e}", "", None# 2. If it does not have .decode(), it's likely a standard file object# (or a path, though gr.File usually passes an object or path string)# The original TemporaryFile-like object in local Gradio will support .read()elif hasattr(file, 'read'):try:# Local Gradio/TemporaryFile-like object: file supports .read()text = file.read().decode("utf-8")except Exception as e:return f"Error reading/decoding file object: {e}", "", None# Optional: Handle the case where Gradio passed a string path instead of an objectelif isinstance(file, str) and os.path.exists(file):try:with open(file, 'r', encoding='utf-8') as f:text = f.read()except Exception as e:return f"Error reading file from path: {e}", "", None# Fallback check if text is still empty (e.g., if object type was unexpected)if not text:return "Could not read the file content. Please check the file type and content.", "", None# 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 ----# Using 'all-MiniLM-L6-v2' as requestedembedder = SentenceTransformer("all-MiniLM-L6-v2")# ---- Topic Modeling ----topic_model = BERTopic(embedding_model=embedder)topics, probs = topic_model.fit_transform(docs)# ---- Topic Summary ----# Convert to string and remove index for clean outputtopic_info = topic_model.get_topic_info().to_string(index=False)# ---- Document → Topic Assignments ----assignments = "\n".join([f"Doc {i+1}: Topic {topics[i]}" for i in range(len(docs))])# ---- 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)")1 unmodified line"Upload a plain text (.txt) file. Each line should contain **one LLM response**.\n""\nExample format:\n```\nResponse 1...\nResponse 2...\nResponse 3...\n```")# Ensure file_input is configured to pass a file object or path.# The default setting should work with the logic above.file_input = gr.File(label="Upload .txt file")run_button = gr.Button("Run Topic Modeling")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_button.click(fn=run_from_textfile,inputs=file_input,1 unmodified line)# Launch appdemo.launch()
app.py+52-23