kambris commited on
Commit
5ce4f5a
·
verified ·
1 Parent(s): 9a034e8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -23
app.py CHANGED
@@ -1,45 +1,72 @@
1
  import gradio as gr
2
  from bertopic import BERTopic
3
  from sentence_transformers import SentenceTransformer
4
-
5
 
6
  def run_from_textfile(file):
7
  if file is None:
8
  return "Please upload a .txt file.", "", None
9
-
10
- # ---- Handle file input for both HuggingFace and local environments ----
11
- try:
12
- # HuggingFace Spaces: file is NamedString and supports .decode()
13
- text = file.decode("utf-8")
14
- except:
15
- # Local Gradio: file is a TemporaryFile-like object
16
- text = file.read().decode("utf-8")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  # Split the text into documents (one per line)
19
  docs = [line.strip() for line in text.split("\n") if line.strip()]
20
 
21
  if len(docs) < 3:
22
  return "Need at least 3 documents (one per line).", "", None
23
-
24
  # ---- Embedding Model ----
 
25
  embedder = SentenceTransformer("all-MiniLM-L6-v2")
26
-
27
  # ---- Topic Modeling ----
28
  topic_model = BERTopic(embedding_model=embedder)
29
  topics, probs = topic_model.fit_transform(docs)
30
-
31
  # ---- Topic Summary ----
32
- topic_info = topic_model.get_topic_info().to_string()
33
-
 
34
  # ---- Document → Topic Assignments ----
35
  assignments = "\n".join([f"Doc {i+1}: Topic {topics[i]}" for i in range(len(docs))])
36
-
37
  # ---- Visualization ----
38
  fig = topic_model.visualize_barchart(top_n_topics=10)
39
-
40
  return topic_info, assignments, fig
41
 
42
-
43
  # ---- Gradio Interface ----
44
  with gr.Blocks() as demo:
45
  gr.Markdown("# 🧠 Topic Modeling from TXT File (BERTopic)")
@@ -47,15 +74,17 @@ with gr.Blocks() as demo:
47
  "Upload a plain text (.txt) file. Each line should contain **one LLM response**.\n"
48
  "\nExample format:\n```\nResponse 1...\nResponse 2...\nResponse 3...\n```"
49
  )
50
-
51
- file_input = gr.File(label="Upload .txt file")
52
-
 
 
53
  run_button = gr.Button("Run Topic Modeling")
54
-
55
  topic_output = gr.Textbox(label="Topic Overview", lines=12)
56
  assignment_output = gr.Textbox(label="Document → Topic Assignments", lines=12)
57
  fig_output = gr.Plot(label="Topic Visualization")
58
-
59
  run_button.click(
60
  fn=run_from_textfile,
61
  inputs=file_input,
@@ -63,4 +92,4 @@ with gr.Blocks() as demo:
63
  )
64
 
65
  # Launch app
66
- demo.launch()
 
1
  import gradio as gr
2
  from bertopic import BERTopic
3
  from sentence_transformers import SentenceTransformer
4
+ import os # Import os for potential path checks, though the logic below is key
5
 
6
  def run_from_textfile(file):
7
  if file is None:
8
  return "Please upload a .txt file.", "", None
9
+
10
+ # ---- Handle file input: Unify access for NamedString (Spaces) and file object (Local) ----
11
+ text = ""
12
+
13
+ # 1. Check for the .decode() method, which is characteristic of the Gradio NamedString object
14
+ # used in some environments (like HuggingFace Spaces).
15
+ if hasattr(file, 'decode'):
16
+ try:
17
+ # HuggingFace Spaces/NamedString: file supports .decode() directly
18
+ text = file.decode("utf-8")
19
+ except Exception as e:
20
+ return f"Error decoding NamedString: {e}", "", None
21
+
22
+ # 2. If it does not have .decode(), it's likely a standard file object
23
+ # (or a path, though gr.File usually passes an object or path string)
24
+ # The original TemporaryFile-like object in local Gradio will support .read()
25
+ elif hasattr(file, 'read'):
26
+ try:
27
+ # Local Gradio/TemporaryFile-like object: file supports .read()
28
+ text = file.read().decode("utf-8")
29
+ except Exception as e:
30
+ return f"Error reading/decoding file object: {e}", "", None
31
+
32
+ # Optional: Handle the case where Gradio passed a string path instead of an object
33
+ elif isinstance(file, str) and os.path.exists(file):
34
+ try:
35
+ with open(file, 'r', encoding='utf-8') as f:
36
+ text = f.read()
37
+ except Exception as e:
38
+ return f"Error reading file from path: {e}", "", None
39
+
40
+ # Fallback check if text is still empty (e.g., if object type was unexpected)
41
+ if not text:
42
+ return "Could not read the file content. Please check the file type and content.", "", None
43
 
44
  # Split the text into documents (one per line)
45
  docs = [line.strip() for line in text.split("\n") if line.strip()]
46
 
47
  if len(docs) < 3:
48
  return "Need at least 3 documents (one per line).", "", None
49
+
50
  # ---- Embedding Model ----
51
+ # Using 'all-MiniLM-L6-v2' as requested
52
  embedder = SentenceTransformer("all-MiniLM-L6-v2")
53
+
54
  # ---- Topic Modeling ----
55
  topic_model = BERTopic(embedding_model=embedder)
56
  topics, probs = topic_model.fit_transform(docs)
57
+
58
  # ---- Topic Summary ----
59
+ # Convert to string and remove index for clean output
60
+ topic_info = topic_model.get_topic_info().to_string(index=False)
61
+
62
  # ---- Document → Topic Assignments ----
63
  assignments = "\n".join([f"Doc {i+1}: Topic {topics[i]}" for i in range(len(docs))])
64
+
65
  # ---- Visualization ----
66
  fig = topic_model.visualize_barchart(top_n_topics=10)
67
+
68
  return topic_info, assignments, fig
69
 
 
70
  # ---- Gradio Interface ----
71
  with gr.Blocks() as demo:
72
  gr.Markdown("# 🧠 Topic Modeling from TXT File (BERTopic)")
 
74
  "Upload a plain text (.txt) file. Each line should contain **one LLM response**.\n"
75
  "\nExample format:\n```\nResponse 1...\nResponse 2...\nResponse 3...\n```"
76
  )
77
+
78
+ # Ensure file_input is configured to pass a file object or path.
79
+ # The default setting should work with the logic above.
80
+ file_input = gr.File(label="Upload .txt file")
81
+
82
  run_button = gr.Button("Run Topic Modeling")
83
+
84
  topic_output = gr.Textbox(label="Topic Overview", lines=12)
85
  assignment_output = gr.Textbox(label="Document → Topic Assignments", lines=12)
86
  fig_output = gr.Plot(label="Topic Visualization")
87
+
88
  run_button.click(
89
  fn=run_from_textfile,
90
  inputs=file_input,
 
92
  )
93
 
94
  # Launch app
95
+ demo.launch()