AhmadMustafa commited on
Commit
0f97b90
·
1 Parent(s): dfde411

update: code reformating

Browse files
Files changed (3) hide show
  1. tools.py +0 -0
  2. transcript.py +467 -0
  3. utils.py +237 -0
tools.py ADDED
File without changes
transcript.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from dataclasses import dataclass
3
+ from typing import Dict, List, Union
4
+
5
+ import requests
6
+ from bs4 import BeautifulSoup
7
+ from openai import OpenAI
8
+
9
+
10
+ @dataclass
11
+ class TranscriptSegment:
12
+ speaker_id: str
13
+ start_time: float
14
+ end_time: float
15
+ text: str
16
+ speaker_name: str = ""
17
+
18
+
19
+ @dataclass
20
+ class AudioSegment:
21
+ id: int
22
+ transcript: str
23
+ start_time: float
24
+ end_time: float
25
+ speaker_label: str
26
+ original_file: str
27
+ items: List[int]
28
+
29
+
30
+ class TranscriptProcessor:
31
+ def __init__(
32
+ self,
33
+ transcript_file: str = None,
34
+ transcript_data: Union[dict, list] = None,
35
+ call_type: str = "le",
36
+ person_names: list = None,
37
+ ):
38
+ self.transcript_file = transcript_file
39
+ self.transcript_data = transcript_data
40
+ self.formatted_transcript = None
41
+ self.segments = []
42
+ self.speaker_mapping = {}
43
+ self.person_names = person_names
44
+
45
+ if self.transcript_file:
46
+ self._load_transcript()
47
+ elif self.transcript_data:
48
+ if call_type == "rp":
49
+ self.merge_transcripts(transcript_data, person_names)
50
+ else:
51
+ raise ValueError(
52
+ "Either transcript_file or transcript_data must be provided."
53
+ )
54
+
55
+ self._process_transcript()
56
+ self._create_formatted_transcript() # Create initial formatted transcript
57
+ if call_type != "si" and call_type != "rp":
58
+ self.map_speaker_ids_to_names()
59
+
60
+ def _load_transcript(self) -> None:
61
+ """Load the transcript JSON file."""
62
+ with open(self.transcript_file, "r") as f:
63
+ self.transcript_data = json.load(f)
64
+
65
+ def _format_time(self, seconds: float) -> str:
66
+ """Convert seconds to formatted time string (MM:SS)."""
67
+ minutes = int(seconds // 60)
68
+ seconds = int(seconds % 60)
69
+ return f"{minutes:02d}:{seconds:02d}"
70
+
71
+ def _process_transcript(self) -> None:
72
+ results = self.transcript_data["results"]
73
+ current_words = []
74
+ current_speaker = None
75
+ current_start = None
76
+ current_items = []
77
+
78
+ for item in results["items"]:
79
+ if item["type"] == "pronunciation":
80
+ if not self.person_names:
81
+ speaker = (
82
+ item.get("speaker_label", "")
83
+ .replace("spk_", "")
84
+ .replace("spk", "")
85
+ )
86
+ else:
87
+ speaker = item.get("speaker_label", "")
88
+ print("ITEM", item)
89
+
90
+ # Initialize on first pronunciation item
91
+ if current_speaker is None:
92
+ current_speaker = speaker
93
+ current_start = float(item["start_time"])
94
+
95
+ # Check for speaker change
96
+ if speaker != current_speaker:
97
+ if current_items:
98
+ self._create_segment(
99
+ current_speaker,
100
+ current_start,
101
+ float(item["start_time"]),
102
+ current_items,
103
+ )
104
+ current_items = []
105
+ current_words = []
106
+ current_speaker = speaker
107
+ current_start = float(item["start_time"])
108
+
109
+ current_items.append(item)
110
+ current_words.append(item["alternatives"][0]["content"])
111
+ elif item["type"] == "punctuation":
112
+ current_items.append(item)
113
+ # Only check for segment break if we're over 20 words
114
+ if len(current_words) >= 20:
115
+ # Break on this punctuation
116
+ next_item = next(
117
+ (
118
+ it
119
+ for it in results["items"][
120
+ results["items"].index(item) + 1 :
121
+ ]
122
+ if it["type"] == "pronunciation"
123
+ ),
124
+ None,
125
+ )
126
+ if next_item:
127
+ self._create_segment(
128
+ current_speaker,
129
+ current_start,
130
+ float(next_item["start_time"]),
131
+ current_items,
132
+ )
133
+ current_items = []
134
+ current_words = []
135
+ current_start = float(next_item["start_time"])
136
+
137
+ # Don't forget the last segment
138
+ if current_items:
139
+ last_time = max(
140
+ float(item["end_time"])
141
+ for item in current_items
142
+ if item["type"] == "pronunciation"
143
+ )
144
+ self._create_segment(
145
+ current_speaker, current_start, last_time, current_items
146
+ )
147
+
148
+ def _create_segment(
149
+ self, speaker_id: str, start: float, end: float, items: list
150
+ ) -> None:
151
+ segment_content = []
152
+ for item in items:
153
+ if item["type"] == "pronunciation":
154
+ segment_content.append(item["alternatives"][0]["content"])
155
+ elif item["type"] == "punctuation":
156
+ # Append punctuation to the last word without a space
157
+ if segment_content:
158
+ segment_content[-1] += item["alternatives"][0]["content"]
159
+
160
+ if segment_content:
161
+ self.segments.append(
162
+ TranscriptSegment(
163
+ speaker_id=speaker_id,
164
+ start_time=start,
165
+ end_time=end,
166
+ text=" ".join(segment_content),
167
+ )
168
+ )
169
+
170
+ def correct_speaker_mapping_with_agenda(self, url: str) -> None:
171
+ """Fetch agenda from a URL and correct the speaker mapping using OpenAI."""
172
+ try:
173
+ if not url.startswith("http"):
174
+ # add https to the url
175
+ url = "https://" + url
176
+
177
+ response = requests.get(url)
178
+ response.raise_for_status()
179
+ html_content = response.text
180
+
181
+ # Parse the HTML to find the desired description
182
+ soup = BeautifulSoup(html_content, "html.parser")
183
+ description_tag = soup.find(
184
+ "script", {"type": "application/ld+json"}
185
+ ) # Find the ld+json metadata block
186
+ agenda = ""
187
+
188
+ if description_tag:
189
+ # Extract the JSON content
190
+ json_data = json.loads(description_tag.string)
191
+ if "description" in json_data:
192
+ agenda = json_data["description"]
193
+ else:
194
+ print("Agenda description not found in the JSON metadata.")
195
+ else:
196
+ print("No structured data (ld+json) found.")
197
+
198
+ if not agenda:
199
+ print("No agenda found in the structured metadata. Trying meta tags.")
200
+
201
+ # Fallback: Use meta description if ld+json doesn't have it
202
+ meta_description = soup.find("meta", {"name": "description"})
203
+ agenda = meta_description["content"] if meta_description else ""
204
+
205
+ if not agenda:
206
+ print("No agenda found in any description tags.")
207
+ return
208
+
209
+ prompt = (
210
+ f"Given the original speaker mapping {self.speaker_mapping}, agenda:\n{agenda}, and the transcript: {self.formatted_transcript}\n\n"
211
+ "Some speaker names in the mapping might have spelling errors or be incomplete."
212
+ "Remember that the content in agenda is accurate and transcript can have errors so prioritize the spellings and names in the agenda content."
213
+ "If the speaker name and introduction is similar to the agenda, update the speaker name in the mapping."
214
+ "Please correct the names based on the agenda. Return the corrected mapping in JSON format as "
215
+ "{'spk_0': 'Correct Name', 'spk_1': 'Correct Name', ...}."
216
+ "You should only update the name if the name sounds very similar, or there is a good spelling overlap/ The Speaker Introduction matches the description of the Talk from Agends. If the name is totally unrelated, keep the original name."
217
+ "You should always include all the speakers in the mapping from the original mapping, even if you don't update their names. i.e if there are 4 speakers in original mapping, new mapping should have 4 speakers always, ignore all the other spekaers in the agenda. I REPEAT DO NOT ADD OTHER NEW SPEAKERS IN THE MAPPING."
218
+ )
219
+
220
+ client = OpenAI()
221
+
222
+ completion = client.chat.completions.create(
223
+ model="gpt-4o-mini",
224
+ messages=[
225
+ {
226
+ "role": "system",
227
+ "content": "You are a helpful assistant. Who analyzes the given transcript, original speaker mapping and agenda. From the Agenda, you fix the spelling mistakes in the speaker names or update the names if they are similar to the agenda. You should only update the name if the name sounds very similar, or there is a good spelling overlap/ The Speaker Introduction matches the description of the Talk from Agends. If the name is totally unrelated, keep the original name.",
228
+ },
229
+ {"role": "user", "content": prompt},
230
+ ],
231
+ temperature=0,
232
+ )
233
+
234
+ response_text = completion.choices[0].message.content.strip()
235
+ try:
236
+ corrected_mapping = json.loads(response_text)
237
+ except Exception:
238
+ response_text = response_text[
239
+ response_text.find("{") : response_text.rfind("}") + 1
240
+ ]
241
+ try:
242
+ corrected_mapping = json.loads(response_text)
243
+ except json.JSONDecodeError:
244
+ print(
245
+ "Error parsing corrected speaker mapping JSON, keeping the original mapping."
246
+ )
247
+ corrected_mapping = self.speaker_mapping
248
+ # Update the speaker mapping with corrected names
249
+ self.speaker_mapping = corrected_mapping
250
+
251
+ # Update the transcript segments with corrected names
252
+ for segment in self.segments:
253
+ spk_id = f"spk_{segment.speaker_id}"
254
+ segment.speaker_name = self.speaker_mapping.get(spk_id, spk_id)
255
+
256
+ # Recreate the formatted transcript with corrected names
257
+ formatted_segments = []
258
+ for seg in self.segments:
259
+ start_time_str = self._format_time(seg.start_time)
260
+ end_time_str = self._format_time(seg.end_time)
261
+ formatted_segments.append(
262
+ f"time_stamp: {start_time_str}-{end_time_str}\n"
263
+ f"{seg.speaker_name}: {seg.text}\n"
264
+ )
265
+ self.formatted_transcript = "\n".join(formatted_segments)
266
+
267
+ except requests.exceptions.RequestException as e:
268
+ print(f" ching agenda from URL: {str(e)}")
269
+ except Exception as e:
270
+ print(f"Error correcting speaker mapping: {str(e)}")
271
+
272
+ def _create_formatted_transcript(self) -> None:
273
+ """Create formatted transcript with default speaker labels."""
274
+ formatted_segments = []
275
+ for seg in self.segments:
276
+ start_time_str = self._format_time(seg.start_time)
277
+ end_time_str = self._format_time(seg.end_time)
278
+ # Use default speaker label (spk_X) if no mapping exists
279
+ if not self.person_names:
280
+ speaker_label = f"spk_{seg.speaker_id}"
281
+ else:
282
+ speaker_label = f"{seg.speaker_id}"
283
+ formatted_segments.append(
284
+ f"time_stamp: {start_time_str}-{end_time_str}\n"
285
+ f"{speaker_label}: {seg.text}\n"
286
+ )
287
+ self.formatted_transcript = "\n".join(formatted_segments)
288
+
289
+ def map_speaker_ids_to_names(self) -> None:
290
+ """Map speaker IDs to names based on introductions in the transcript."""
291
+ try:
292
+ transcript = self.formatted_transcript
293
+
294
+ prompt = (
295
+ "Given the following transcript where speakers are identified as spk 0, spk 1, spk 2, etc., please map each spk ID to the speaker's name based on their introduction in the transcript. If no name is introduced for a speaker, keep it as spk_id. Return the mapping as a JSON object in the format {'spk_0': 'Speaker Name', 'spk_1': 'Speaker Name', ...}\n\n"
296
+ f"Transcript:\n{transcript}"
297
+ )
298
+
299
+ client = OpenAI()
300
+
301
+ completion = client.chat.completions.create(
302
+ model="gpt-4o",
303
+ messages=[
304
+ {"role": "system", "content": "You are a helpful assistant."},
305
+ {"role": "user", "content": prompt},
306
+ ],
307
+ temperature=0,
308
+ )
309
+
310
+ response_text = completion.choices[0].message.content.strip()
311
+ try:
312
+ self.speaker_mapping = json.loads(response_text)
313
+ except json.JSONDecodeError:
314
+ response_text = response_text[
315
+ response_text.find("{") : response_text.rfind("}") + 1
316
+ ]
317
+ try:
318
+ self.speaker_mapping = json.loads(response_text)
319
+ except json.JSONDecodeError:
320
+ print("Error parsing speaker mapping JSON.")
321
+ self.speaker_mapping = {}
322
+
323
+ # Update segments with speaker names and recreate formatted transcript
324
+ for segment in self.segments:
325
+ spk_id = f"spk_{segment.speaker_id}"
326
+ speaker_name = self.speaker_mapping.get(spk_id, spk_id)
327
+ segment.speaker_name = speaker_name
328
+
329
+ self._create_formatted_transcript_with_names()
330
+
331
+ except Exception as e:
332
+ print(f"Error mapping speaker IDs to names: {str(e)}")
333
+ self.speaker_mapping = {}
334
+
335
+ def _create_formatted_transcript_with_names(self) -> None:
336
+ """Create formatted transcript with mapped speaker names."""
337
+ formatted_segments = []
338
+ for seg in self.segments:
339
+ start_time_str = self._format_time(seg.start_time)
340
+ end_time_str = self._format_time(seg.end_time)
341
+ speaker_name = getattr(seg, "speaker_name", f"spk_{seg.speaker_id}")
342
+ formatted_segments.append(
343
+ f"Start Time: {start_time_str} - End Time: {end_time_str}\n"
344
+ f"{speaker_name}: {seg.text}\n"
345
+ )
346
+ self.formatted_transcript = "\n".join(formatted_segments)
347
+
348
+ def get_transcript(self) -> str:
349
+ """Return the formatted transcript with speaker names."""
350
+ return self.formatted_transcript
351
+
352
+ def get_transcript_data(self) -> Dict:
353
+ """Return the raw transcript data."""
354
+ return self.transcript_data
355
+
356
+ def merge_transcripts(
357
+ self, transcript_files: List[Dict], person_names: List[str]
358
+ ) -> None:
359
+ """
360
+ Merge multiple AWS diarized transcripts while maintaining correct time ordering.
361
+ Each transcript is assumed to have one speaker (spk_0) and person_names list index
362
+ corresponds to transcript file index.
363
+ """
364
+ print(person_names)
365
+ if len(transcript_files) != len(person_names):
366
+ raise ValueError("Number of transcripts must match number of speaker names")
367
+
368
+ # Initialize merged structure
369
+ merged_transcript = {
370
+ "jobName": "merged_transcript",
371
+ "status": "COMPLETED",
372
+ "results": {
373
+ "audio_segments": [],
374
+ "items": [],
375
+ "speaker_labels": {"segments": [], "speakers": len(transcript_files)},
376
+ },
377
+ }
378
+
379
+ # First collect all items with their original data and file index
380
+ all_items = []
381
+ for file_idx, transcript in enumerate(transcript_files):
382
+ items = transcript["results"].get("items", [])
383
+ speaker_name = person_names[file_idx]
384
+
385
+ for item in items:
386
+ # Store original item data along with file index and original ID
387
+ item_data = dict(item)
388
+ # if "speaker_label" in item_data:
389
+ item_data["speaker_label"] = speaker_name
390
+ item_data["file_idx"] = file_idx
391
+ item_data["original_id"] = item["id"]
392
+ item_data["start_time"] = float(item.get("start_time", 0))
393
+ item_data["end_time"] = float(item.get("end_time", 0))
394
+ all_items.append(item_data)
395
+
396
+ # Sort items by start time
397
+ all_items.sort(key=lambda x: (x["start_time"], x["end_time"]))
398
+
399
+ # Create mapping from (file_idx, original_id) to new sequential ID
400
+ item_id_mapping = {}
401
+
402
+ # Assign new sequential IDs and add to merged transcript
403
+ for new_id, item in enumerate(all_items):
404
+ file_idx = item.pop("file_idx")
405
+ original_id = item.pop("original_id")
406
+ item_id_mapping[(file_idx, original_id)] = new_id
407
+
408
+ # Update item ID and convert times back to strings
409
+ item["id"] = new_id
410
+ item["start_time"] = str(item["start_time"])
411
+ item["end_time"] = str(item["end_time"])
412
+
413
+ merged_transcript["results"]["items"].append(item)
414
+
415
+ # Process audio segments
416
+ all_segments = []
417
+ for file_idx, transcript in enumerate(transcript_files):
418
+ file_segments = transcript["results"].get("audio_segments", [])
419
+ speaker_name = person_names[file_idx]
420
+
421
+ for segment in file_segments:
422
+ # Map original item IDs to new sequential IDs
423
+ new_items = [
424
+ item_id_mapping[(file_idx, item_id)]
425
+ for item_id in segment.get("items", [])
426
+ ]
427
+
428
+ all_segments.append(
429
+ AudioSegment(
430
+ id=len(all_segments),
431
+ transcript=segment["transcript"],
432
+ start_time=float(segment["start_time"]),
433
+ end_time=float(segment["end_time"]),
434
+ speaker_label=speaker_name,
435
+ original_file=f"file_{file_idx}",
436
+ items=new_items,
437
+ )
438
+ )
439
+
440
+ # Sort segments by start time
441
+ sorted_segments = sorted(all_segments, key=lambda x: x.start_time)
442
+
443
+ # Convert segments back to dictionary format
444
+ for idx, segment in enumerate(sorted_segments):
445
+ merged_segment = {
446
+ "id": idx,
447
+ "transcript": segment.transcript,
448
+ "start_time": str(segment.start_time),
449
+ "end_time": str(segment.end_time),
450
+ "speaker_label": segment.speaker_label,
451
+ "source_file": segment.original_file,
452
+ "items": sorted(segment.items),
453
+ }
454
+ merged_transcript["results"]["audio_segments"].append(merged_segment)
455
+
456
+ # Add to speaker labels segments
457
+ speaker_segment = {
458
+ "start_time": str(segment.start_time),
459
+ "end_time": str(segment.end_time),
460
+ "speaker_label": segment.speaker_label,
461
+ }
462
+ merged_transcript["results"]["speaker_labels"]["segments"].append(
463
+ speaker_segment
464
+ )
465
+
466
+ # Update the instance transcript data with merged result
467
+ self.transcript_data = merged_transcript
utils.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+
4
+ import requests
5
+
6
+
7
+ def get_transcript_for_url(url: str) -> dict:
8
+ """
9
+ This function fetches the transcript data for a signed URL.
10
+ If the URL results in a direct download, it processes the downloaded content.
11
+
12
+ :param url: Signed URL for the JSON file
13
+ :return: Parsed JSON data as a dictionary
14
+ """
15
+ headers = {
16
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
17
+ }
18
+
19
+ try:
20
+ response = requests.get(url, headers=headers)
21
+ response.raise_for_status()
22
+
23
+ if "application/json" in response.headers.get("Content-Type", ""):
24
+ return response.json() # Parse and return JSON directly
25
+
26
+ # If not JSON, assume it's a file download (e.g., content-disposition header)
27
+ content_disposition = response.headers.get("Content-Disposition", "")
28
+ if "attachment" in content_disposition:
29
+ # Process the content as JSON
30
+ return json.loads(response.content)
31
+
32
+ return json.loads(response.content)
33
+
34
+ except requests.exceptions.HTTPError as http_err:
35
+ print(f"HTTP error occurred: {http_err}")
36
+ except requests.exceptions.RequestException as req_err:
37
+ print(f"Request error occurred: {req_err}")
38
+ except json.JSONDecodeError as json_err:
39
+ print(f"JSON decoding error: {json_err}")
40
+
41
+ return {}
42
+
43
+
44
+ def setup_openai_key() -> None:
45
+ """Set up OpenAI API key from file."""
46
+ try:
47
+ with open("api.key", "r") as f:
48
+ os.environ["OPENAI_API_KEY"] = f.read().strip()
49
+ except FileNotFoundError:
50
+ print("Using ENV variable")
51
+
52
+
53
+ openai_tools = [
54
+ {
55
+ "type": "function",
56
+ "function": {
57
+ "name": "correct_speaker_name_with_url",
58
+ "description": "If a User provides a link to Agenda file, call the correct_speaker_name_with_url function to correct the speaker names based on the url, i.e if a user says 'Here is the Luma link for the event' and provides a link to the event, the function will correct the speaker names based on the event.",
59
+ "parameters": {
60
+ "type": "object",
61
+ "properties": {
62
+ "url": {
63
+ "type": "string",
64
+ "description": "The url to the agenda.",
65
+ },
66
+ },
67
+ "required": ["url"],
68
+ "additionalProperties": False,
69
+ },
70
+ },
71
+ },
72
+ {
73
+ "type": "function",
74
+ "function": {
75
+ "name": "correct_call_type",
76
+ "description": "If the user tells you the correct call type, you have to apologize and call this function with correct call type.",
77
+ "parameters": {
78
+ "type": "object",
79
+ "properties": {
80
+ "call_type": {
81
+ "type": "string",
82
+ "description": "The correct call type. If street interview, call type is 'si'.",
83
+ },
84
+ },
85
+ "required": ["call_type"],
86
+ "additionalProperties": False,
87
+ },
88
+ },
89
+ },
90
+ ]
91
+
92
+
93
+ css = """
94
+ .gradio-container {
95
+
96
+ padding-top: 0px !important;
97
+ padding-left: 0px !important;
98
+ padding-right: 0px !important;
99
+ padding: 0px !important;
100
+ margin: 0px !important;
101
+ }
102
+ #component-0 {
103
+ gap: 0px !important;
104
+ }
105
+
106
+ .icon-button-wrapper{
107
+ display: none !important;
108
+ }
109
+
110
+
111
+ footer {
112
+ display: none !important;
113
+ }
114
+ #chatbot_box{
115
+ flex-grow: 1 !important;
116
+ border-width: 0px !important;
117
+ }
118
+
119
+ #link-frame {
120
+ position: absolute !important;
121
+ width: 1px !important;
122
+ height: 1px !important;
123
+ right: -100px !important;
124
+ bottom: -100px !important;
125
+ display: none !important;
126
+ }
127
+ .html-container {
128
+ display: none !important;
129
+ }
130
+ a {
131
+ text-decoration: none !important;
132
+ }
133
+ #topic {
134
+ color: #999 !important;
135
+ }
136
+ .bubble-wrap {
137
+ padding-top: 0px !important;
138
+ }
139
+ .message-content {
140
+ border: 0px !important;
141
+ margin: 5px !important;
142
+ }
143
+ .message-row {
144
+ border-style: none !important;
145
+ margin: 0px !important;
146
+ width: 100% !important;
147
+ max-width: 100% !important;
148
+ }
149
+ .flex-wrap {
150
+ border-style: none !important;
151
+ }
152
+
153
+ .panel-full-width {
154
+ border-style: none !important;
155
+ border-width: 0px !important;
156
+ }
157
+ ol {
158
+ list-style-position: outside;
159
+ margin-left: 20px;
160
+ }
161
+
162
+ body.waiting * {
163
+ cursor: progress;
164
+ }
165
+ """
166
+ head = f"""
167
+ <script defer src="https://www.gstatic.com/firebasejs/11.1.0/firebase-firestore.js"></script>
168
+ <script type="module">
169
+ // Import the functions you need from the SDKs you need
170
+ import {{ initializeApp }} from "https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js";
171
+ import {{ getDatabase, ref, set }} from "https://www.gstatic.com/firebasejs/11.1.0/firebase-database.js";
172
+ // TODO: Add SDKs for Firebase products that you want to use
173
+ // https://firebase.google.com/docs/web/setup#available-libraries
174
+ console.log("Initializing Firebase");
175
+ // Your web app's Firebase configuration
176
+ // For Firebase JS SDK v7.20.0 and later, measurementId is optional
177
+ const firebaseConfig = {{
178
+ apiKey: "{os.getenv('FIREBASE_API_KEY')}",
179
+ authDomain: "{os.getenv('FIREBASE_AUTH_DOMAIN')}",
180
+ databaseURL: "{os.getenv('FIREBASE_DATABASE_URL')}",
181
+ projectId: "{os.getenv('FIREBASE_PROJECT_ID')}",
182
+ storageBucket: "{os.getenv('FIREBASE_STORAGE_BUCKET')}",
183
+ messagingSenderId: "{os.getenv('FIREBASE_MESSAGING_SENDER_ID')}",
184
+ appId: "{os.getenv('FIREBASE_APP_ID')}",
185
+ measurementId: "{os.getenv('FIREBASE_MEASUREMENT_ID')}"
186
+ }};
187
+
188
+ // Initialize Firebase
189
+ const app = initializeApp(firebaseConfig);
190
+ const realtimeDB = getDatabase(app);
191
+ const rollAccount = "{os.getenv('ROLL_ACCOUNT')}";
192
+ const COLLECTIONS = {{
193
+ COLLAB_EDIT_LINK: "collab_link_handler",
194
+ }};
195
+
196
+ // Event listener for click
197
+ document.addEventListener('click', function (event) {{
198
+ var link = event.target.closest('a');
199
+ event.preventDefault();
200
+ if (link && link.href) {{
201
+
202
+ // Parse the URL to extract 'st' and 'et'
203
+ const url = new URL(link.href);
204
+ const startTime = url.searchParams.get('st');
205
+ const endTime = url.searchParams.get('et');
206
+ const userId = url.searchParams.get('uid') || "";
207
+
208
+ if (startTime || endTime) {{
209
+ let components = url.pathname.split("/");
210
+ let callId = components[2];
211
+ let recordingSessionId = components[3];
212
+
213
+ let data = {{
214
+ startTime: parseInt(startTime, 10),
215
+ endTime: parseInt(endTime, 10),
216
+ }};
217
+
218
+ console.log("Data to save:", data);
219
+
220
+ // Firebase reference
221
+ let reference = ref(
222
+ realtimeDB,
223
+ `${{rollAccount}}/${{COLLECTIONS.COLLAB_EDIT_LINK}}/${{userId}}/${{callId}}/${{recordingSessionId}}`
224
+ );
225
+
226
+ set(reference, data)
227
+ .then(() => {{
228
+ console.log("Data saved successfully:", data);
229
+ }})
230
+ .catch((error) => {{
231
+ console.error("Error saving data:", error);
232
+ }});
233
+ }}
234
+ }}
235
+ }});
236
+ </script>
237
+ """