Spaces:
Runtime error
Runtime error
Update app.py
Browse files123445678910111213141516910111213141516171819202122232425262728293031323334353637383940414243444546474823495051522653545556305758593233606162633664656639676869427071721 unmodified line747576505152777879808182548384858658878889901 unmodified line9293946695import gradio as grfrom bertopic import BERTopicfrom sentence_transformers import SentenceTransformer
import os # Import os for potential path checks, though the logic below is key
def 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 object text = file.read().decode("utf-8") # ---- 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() directly text = 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 object elif 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 requested embedder = 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 output topic_info = topic_model.get_topic_info().to_string()
topic_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```" )
file_input = gr.File(label="Upload .txt file")
# 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()demo.launch()app.py+52-23