Spaces:
Sleeping

clementBE commited on
Commit
77369f4
Β·
verified Β·
1 Parent(s): 46e8e70

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +171 -112
app.py CHANGED
@@ -7,9 +7,9 @@ try:
7
  except ImportError:
8
  docx = None
9
 
10
- # ============================
11
- # CONFIGURATION
12
- # ============================
13
 
14
  DEFAULT_CODES = [
15
  "Theme: Communication Barrier",
@@ -26,172 +26,231 @@ METADATA_FIELDS = {
26
  "age": "Participant Age",
27
  }
28
 
29
- # ============================
30
- # FILE READERS
31
- # ============================
32
 
33
- def read_docx(file_path):
34
  if not docx:
35
- return "Error: python-docx is not installed."
36
 
37
- document = docx.Document(file_path)
38
- return "\n".join([p.text for p in document.paragraphs])
39
 
40
 
41
- def read_vtt(file_path):
42
- with open(file_path, "r", encoding="utf-8") as f:
43
- content = f.read()
44
 
45
- lines = [l.strip() for l in content.split("\n")]
46
- transcript = [
47
- l for l in lines
48
- if l and not l.startswith("WEBVTT") and "-->" not in l and not l.isdigit()
 
 
 
49
  ]
50
- return " ".join(transcript)
51
 
52
 
53
- def get_initial_df():
54
- cols = ["File ID", "Code", "Coded Segment", "Context (100 chars)"] + list(METADATA_FIELDS.keys())
55
- return pd.DataFrame(columns=cols)
 
 
56
 
57
- # ============================
58
  # FILE PROCESSING
59
- # ============================
60
 
61
  def process_file(file_obj):
62
  if file_obj is None:
63
- return "", "No file uploaded.", "", get_initial_df()
64
 
65
- file_path = file_obj.name
66
- filename = os.path.basename(file_path)
67
 
68
- if filename.lower().endswith(".docx"):
69
- text = read_docx(file_path)
70
- elif filename.lower().endswith(".vtt"):
71
- text = read_vtt(file_path)
72
  else:
73
- with open(file_path, "r", encoding="utf-8") as f:
74
  text = f.read()
75
 
76
- return text, f"Loaded: {filename}", filename, get_initial_df()
77
-
78
- # ============================
79
- # CODING
80
- # ============================
81
-
82
- def apply_code(coded_df, file_id, full_text, segment_text, selected_code, *metadata_values):
83
- if not segment_text or not selected_code:
84
- return coded_df, "Please enter a segment and select a code."
85
-
86
- meta_dict = dict(zip(METADATA_FIELDS.keys(), metadata_values))
87
 
88
- # Extract simple context
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  context = "Context unavailable"
90
  try:
91
- norm_full = " ".join(full_text.split())
92
- norm_seg = " ".join(segment_text.split())
93
- idx = norm_full.index(norm_seg)
94
- context = "..." + norm_full[max(0, idx - 100):idx]
95
  except:
96
  pass
97
 
98
  new_row = {
99
  "File ID": file_id,
100
- "Code": selected_code,
101
- "Coded Segment": segment_text,
102
  "Context (100 chars)": context,
103
- **meta_dict
104
  }
105
 
106
- new_df = pd.concat([coded_df, pd.DataFrame([new_row])], ignore_index=True)
107
- return new_df, "Code applied!"
 
 
 
 
108
 
109
- # ============================
110
- # EXCEL EXPORT
111
- # ============================
112
 
113
- def generate_excel(coded_df):
114
- if coded_df.empty:
115
- return None, "No coded segments yet."
116
 
117
- out_path = "qualitative_codes.xlsx"
118
- coded_df.to_excel(out_path, index=False)
119
- return out_path, "Excel ready for download."
120
 
121
- # ============================
122
- # GRADIO UI
123
- # ============================
124
 
125
- with gr.Blocks(title="Qualitative Coding Interface") as demo:
126
-
127
- gr.Markdown("# πŸ“‘ Qualitative Coding Interface")
128
- gr.Markdown("Load transcripts β†’ add metadata β†’ code text segments β†’ export Excel.")
129
 
130
- # Hidden states
131
- current_file_id = gr.State("")
132
- full_text_state = gr.State("")
133
- coded_state = gr.State(get_initial_df())
134
 
135
- # ---- FILE UPLOAD ----
136
  with gr.Row():
137
- file_input = gr.File(label="Upload (.docx, .vtt, .txt)", file_types=[".docx", ".vtt", ".txt"])
138
  status = gr.Textbox(label="Status", value="Ready")
139
 
140
- file_input.change(
141
  fn=process_file,
142
- inputs=file_input,
143
- outputs=[full_text_state, status, current_file_id, coded_state]
 
 
 
 
 
 
 
 
 
144
  )
145
 
146
- # ---- METADATA ----
147
- gr.Markdown("## πŸ“ Interview Metadata")
 
148
  metadata_inputs = []
149
  with gr.Row():
150
- for key, lbl in METADATA_FIELDS.items():
151
- box = gr.Textbox(label=lbl)
152
- metadata_inputs.append(box)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
- # ---- TRANSCRIPT VIEW ----
155
- gr.Markdown("## πŸ“– Transcript")
156
- transcript_box = gr.Textbox(label="Transcript (read-only)", lines=15, interactive=False)
157
- full_text_state.change(lambda x: x, inputs=full_text_state, outputs=transcript_box)
158
 
159
- # ---- CODING ----
160
- gr.Markdown("## 🏷️ Apply Code")
161
  with gr.Row():
162
- segment_input = gr.Textbox(label="Paste segment", lines=3)
163
- code_choice = gr.Dropdown(label="Select Code", choices=DEFAULT_CODES)
 
 
 
 
164
 
165
- code_btn = gr.Button("Apply Code")
166
 
167
  code_btn.click(
168
- fn=apply_code,
169
- inputs=[coded_state, current_file_id, full_text_state, segment_input, code_choice] + metadata_inputs,
170
- outputs=[coded_state, status]
171
  )
172
 
173
- # ---- DISPLAY CODED DATA ----
174
- gr.Markdown("## πŸ“Š Coded Data")
175
- data_table = gr.Dataframe(interactive=False)
176
- coded_state.change(lambda x: x, inputs=coded_state, outputs=data_table)
177
 
178
- # ---- DOWNLOAD ----
179
- download_btn = gr.Button("Download XLSX")
180
- download_file = gr.File(label="Download", visible=False)
181
-
182
- def show_file(file):
183
- return gr.update(visible=file is not None)
184
 
185
- download_btn.click(
186
- generate_excel,
187
- inputs=coded_state,
188
- outputs=[download_file, status]
189
  ).then(
190
- show_file,
191
- inputs=download_file,
192
- outputs=download_file
193
  )
194
 
195
- # Launch
196
  if __name__ == "__main__":
197
  demo.launch()
 
7
  except ImportError:
8
  docx = None
9
 
10
+ # ====================================================
11
+ # CONFIG
12
+ # ====================================================
13
 
14
  DEFAULT_CODES = [
15
  "Theme: Communication Barrier",
 
26
  "age": "Participant Age",
27
  }
28
 
29
+ # ====================================================
30
+ # READERS
31
+ # ====================================================
32
 
33
+ def read_docx(path):
34
  if not docx:
35
+ return "Error: python-docx not installed."
36
 
37
+ d = docx.Document(path)
38
+ return "\n".join([p.text for p in d.paragraphs])
39
 
40
 
41
+ def read_vtt(path):
42
+ with open(path, "r", encoding="utf-8") as f:
43
+ lines = f.read().split("\n")
44
 
45
+ cleaned = [
46
+ l.strip()
47
+ for l in lines
48
+ if l.strip()
49
+ and "WEBVTT" not in l
50
+ and "-->" not in l
51
+ and not l.strip().isdigit()
52
  ]
53
+ return " ".join(cleaned)
54
 
55
 
56
+ def get_empty_df():
57
+ return pd.DataFrame(
58
+ columns=["File ID", "Code", "Coded Segment", "Context (100 chars)"]
59
+ + list(METADATA_FIELDS.keys())
60
+ )
61
 
62
+ # ====================================================
63
  # FILE PROCESSING
64
+ # ====================================================
65
 
66
  def process_file(file_obj):
67
  if file_obj is None:
68
+ return "", "", "No file uploaded.", get_empty_df()
69
 
70
+ path = file_obj.name
71
+ name = os.path.basename(path)
72
 
73
+ if name.lower().endswith(".docx"):
74
+ text = read_docx(path)
75
+ elif name.lower().endswith(".vtt"):
76
+ text = read_vtt(path)
77
  else:
78
+ with open(path, "r", encoding="utf-8") as f:
79
  text = f.read()
80
 
81
+ # convert to HTML with selectable div
82
+ html_text = (
83
+ "<div id='transcript' "
84
+ "style='white-space: pre-wrap; font-size: 16px; line-height: 1.5;'>"
85
+ + text.replace("\n", "<br>")
86
+ + "</div>"
87
+ )
 
 
 
 
88
 
89
+ # JS for capturing highlighted text
90
+ js = """
91
+ <script>
92
+ document.addEventListener("mouseup", function () {
93
+ let selection = window.getSelection().toString();
94
+ if (selection.length > 0) {
95
+
96
+ // Find Gradio textbox for segment input
97
+ let tb = document.querySelector(
98
+ 'textarea[placeholder="Paste segment here"]'
99
+ );
100
+ if (tb) {
101
+ tb.value = selection;
102
+ tb.dispatchEvent(new Event("input", { bubbles: true }));
103
+ }
104
+ }
105
+ });
106
+ </script>
107
+ """
108
+
109
+ return html_text + js, text, name, get_empty_df()
110
+
111
+ # ====================================================
112
+ # APPLY CODE
113
+ # ====================================================
114
+
115
+ def apply_code(df, file_id, full_text, segment, code, *metadata_values):
116
+ if not file_id:
117
+ return df, "Upload a file first."
118
+ if not segment:
119
+ return df, "Select or paste a text segment."
120
+ if not code:
121
+ return df, "Choose a code."
122
+
123
+ meta = dict(zip(METADATA_FIELDS.keys(), metadata_values))
124
+
125
+ # Extract context window
126
  context = "Context unavailable"
127
  try:
128
+ n_full = " ".join(full_text.split())
129
+ n_seg = " ".join(segment.split())
130
+ idx = n_full.index(n_seg)
131
+ context = "..." + n_full[max(0, idx - 100):idx]
132
  except:
133
  pass
134
 
135
  new_row = {
136
  "File ID": file_id,
137
+ "Code": code,
138
+ "Coded Segment": segment,
139
  "Context (100 chars)": context,
140
+ **meta,
141
  }
142
 
143
+ out = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
144
+ return out, "Code applied!"
145
+
146
+ # ====================================================
147
+ # EXPORT
148
+ # ====================================================
149
 
150
+ def export_excel(df):
151
+ if df.empty:
152
+ return None, "Nothing to export."
153
 
154
+ out = "qualitative_codes.xlsx"
155
+ df.to_excel(out, index=False)
156
+ return out, "Excel ready."
157
 
158
+ # ====================================================
159
+ # UI
160
+ # ====================================================
161
 
162
+ with gr.Blocks(title="Qualitative Coding Tool") as demo:
 
 
163
 
164
+ gr.Markdown("# πŸ“‘ Qualitative Coding Tool")
165
+ gr.Markdown("Highlight text directly in the transcript to auto-fill the coding box.")
 
 
166
 
167
+ # state
168
+ file_id = gr.State("")
169
+ full_text = gr.State("")
170
+ coded_df_state = gr.State(get_empty_df())
171
 
172
+ # -------------------------------- FILE UPLOAD --------------------------------
173
  with gr.Row():
174
+ upload = gr.File(label="Upload transcript (.docx, .vtt, .txt)", file_types=[".docx", ".vtt", ".txt"])
175
  status = gr.Textbox(label="Status", value="Ready")
176
 
177
+ upload.change(
178
  fn=process_file,
179
+ inputs=upload,
180
+ outputs=[ # MUST MATCH RETURN ORDER
181
+ gr.HTML(), # transcript HTML
182
+ full_text, # raw text
183
+ file_id, # filename
184
+ coded_df_state, # empty df
185
+ ]
186
+ ).then(
187
+ lambda x: f"Loaded: {x}",
188
+ inputs=file_id,
189
+ outputs=status
190
  )
191
 
192
+ # -------------------------------- METADATA --------------------------------
193
+ gr.Markdown("## πŸ“ Metadata")
194
+
195
  metadata_inputs = []
196
  with gr.Row():
197
+ for k, lbl in METADATA_FIELDS.items():
198
+ metadata_inputs.append(gr.Textbox(label=lbl))
199
+
200
+ # -------------------------------- TRANSCRIPT --------------------------------
201
+ gr.Markdown("## πŸ“– Transcript (highlight text to code)")
202
+ transcript_html = gr.HTML()
203
+
204
+ # full_text pushes new transcript content
205
+ full_text.change(
206
+ lambda t: (
207
+ "<div id='transcript' style='white-space: pre-wrap; font-size: 16px;'>"
208
+ + t.replace("\n", "<br>")
209
+ + "</div>"
210
+ ),
211
+ inputs=full_text,
212
+ outputs=transcript_html
213
+ )
214
 
215
+ # -------------------------------- CODING --------------------------------
216
+ gr.Markdown("## 🏷️ Coding")
 
 
217
 
 
 
218
  with gr.Row():
219
+ segment_box = gr.Textbox(
220
+ label="Segment to Code",
221
+ placeholder="Paste segment here",
222
+ lines=3
223
+ )
224
+ code_dropdown = gr.Dropdown(label="Code", choices=DEFAULT_CODES)
225
 
226
+ code_btn = gr.Button("Apply Code", variant="primary")
227
 
228
  code_btn.click(
229
+ apply_code,
230
+ inputs=[coded_df_state, file_id, full_text, segment_box, code_dropdown] + metadata_inputs,
231
+ outputs=[coded_df_state, status]
232
  )
233
 
234
+ # -------------------------------- TABLE --------------------------------
235
+ gr.Markdown("## πŸ“Š Coded Segments")
236
+ table = gr.Dataframe(interactive=False)
237
+ coded_df_state.change(lambda x: x, inputs=coded_df_state, outputs=table)
238
 
239
+ # -------------------------------- EXPORT --------------------------------
240
+ with gr.Row():
241
+ export_btn = gr.Button("Export XLSX")
242
+ export_file = gr.File(visible=False)
 
 
243
 
244
+ export_btn.click(
245
+ export_excel,
246
+ inputs=coded_df_state,
247
+ outputs=[export_file, status]
248
  ).then(
249
+ lambda f: gr.update(visible=f is not None),
250
+ inputs=export_file,
251
+ outputs=export_file
252
  )
253
 
254
+ # LAUNCH FOR HF SPACES
255
  if __name__ == "__main__":
256
  demo.launch()