|
import json |
|
from typing import Generator, List |
|
|
|
import gradio as gr |
|
from openai import OpenAI |
|
from transcript import TranscriptProcessor |
|
from utils import css, get_transcript_for_url, head, setup_openai_key |
|
from utils import openai_tools as tools |
|
|
|
|
|
def get_initial_analysis( |
|
transcript_processor: TranscriptProcessor, cid, rsid, origin, ct, uid |
|
) -> Generator[str, None, None]: |
|
"""Perform initial analysis of the transcript using OpenAI.""" |
|
try: |
|
transcript = transcript_processor.get_transcript() |
|
speaker_mapping = transcript_processor.speaker_mapping |
|
client = OpenAI() |
|
if "localhost" in origin: |
|
link_start = "http" |
|
else: |
|
link_start = "https" |
|
if ct == "si": |
|
prompt = f"""This is a transcript for a street interview. Call Details are as follows: |
|
User ID UID: {uid} |
|
RSID: {rsid} |
|
Transcript: {transcript} |
|
|
|
Your task is to analyze this street interview transcript and identify the final/best timestamps for each topic or question discussed. Here are the key rules: |
|
The user might repeat the answer to the question sometimes, you need to pick the very last answer intelligently |
|
|
|
1. For any topic/answer that appears multiple times in the transcript (even partially): |
|
- The LAST occurrence is always considered the best version. If the same thing is said multiple times, the last time is the best, all previous times are considered as additional takes. |
|
- This includes cases where parts of an answer are scattered throughout the transcript |
|
- Even slight variations of the same answer should be tracked |
|
- List timestamps for ALL takes, with the final take highlighted as the best answer |
|
|
|
2. Introduction handling: |
|
- Question 1 is ALWAYS the speaker's introduction/self-introduction |
|
- If someone introduces themselves multiple times, use the last introduction as best answer |
|
- Include all variations of how they state their name/background |
|
- List ALL introduction timestamps chronologically |
|
|
|
3. Question sequence: |
|
- After the introduction, list questions in the order they were first asked |
|
- If a question or introduction is revisited later at any point, please use the later timestamp |
|
- Track partial answers to the same question across the transcript |
|
|
|
You need to make sure that any words that are repeated, you need to pick the last of them. |
|
|
|
Return format: |
|
|
|
[Question Title] |
|
Total takes: [X] (Include ONLY if content appears more than once) |
|
- [Take 1. <div id='topic' style="display: inline"> 15s at 12:30 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{750}}&et={{765}}&uid={{uid}}) |
|
- [Take 2. <div id='topic' style="display: inline"> 30s at 14:45 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{885}}&et={{915}}&uid={{uid}}) |
|
... |
|
- [Take X (Best) <div id='topic' style="display: inline"> 1m 10s at 16:20 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{980}}&et={{1050}}&uid={{uid}}) |
|
|
|
URL formatting: |
|
- Convert timestamps to seconds (e.g., 10:13 → 613) |
|
- Format: {link_start}://[origin]/colab/[cid]/[rsid]?st=[start_seconds]&et=[end_seconds]&uid=[unique_id] |
|
- Parameters after RSID must start with ? and subsequent parameters use & |
|
|
|
Example: |
|
1. Introduction |
|
Total takes: 2 |
|
- [Take 1. <div id='topic' style="display: inline"> 22s at 12:30 </div>]({{link_start}}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{750}}&et={{772}}&uid={{uid}}) |
|
- [Take 2. <div id='topic' style="display: inline"> 43s at 14:45 </div>]({{link_start}}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{885}}&et={{928}}&uid={{uid}}) |
|
3 [Take 3. (Best) <div id='topic' style="display: inline"> 58s at 16:20 </div>]({{link_start}}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{980}}&et={{1038}}&uid={{uid}}) |
|
""" |
|
completion = client.chat.completions.create( |
|
model="gpt-4o", |
|
messages=[ |
|
{ |
|
"role": "system", |
|
"content": f"""You are analyzing a transcript for Call ID: {cid}, Session ID: {rsid}, Origin: {origin}, Call Type: {ct}. |
|
CORE REQUIREMENT: |
|
- TIMESTAMPS: A speaker can repeat the answer to a question multiple times. You need to pick the last answer very carefully and choose that as best take. Make sure that that same answer is not repeated again after the best answer. |
|
|
|
YOU SHOULD Prioritize accuracy in timestamp at every cost. Read the Transcript carefully and decide where an answer starts and ends. You will have speaker labels so you need to be very sharp.""", |
|
}, |
|
{"role": "user", "content": prompt}, |
|
], |
|
stream=True, |
|
temperature=0.1, |
|
) |
|
else: |
|
system_prompt = f"""You are a helpful assistant developed by Roll.AI(Leading AI tool for Remote production) who is analyzing the transcript for a RollAI Call. Following are the details: |
|
- Call ID: {cid} |
|
- Session ID: {rsid} |
|
- Origin: {origin} |
|
- Call Type: {ct} |
|
- Speakers: {", ".join(speaker_mapping.values())} |
|
- Diarized Transcript: {transcript} |
|
|
|
|
|
You are tasked with creating social media clips from the transcript, You need to shortlist the atleast two short clips for EACH SPEAKER. There are some requirments: |
|
|
|
CORE REQUIREMENTS: |
|
1. SPEAKER Overlap in the CLIP: When specifying the duration for the script, make sure that in that duration: |
|
- There is only continuous dialogue from that speaker. |
|
- As soon as another speaker starts talking or the topic ends, the clip MUST end. |
|
|
|
2. DURATION RULES: |
|
- Each clip must be between 20 seconds to 120 seconds. |
|
|
|
3. SPEAKER COVERAGE: |
|
- Minimum 2 topics per speaker, aim for 3 if good content exists |
|
|
|
CRITICAL: When analyzing timestamps, you must verify that in the duration specified: |
|
1. No other speaker talks during the selected timeframe |
|
2. The speaker talks continuously for at least 20 seconds |
|
3. The clip ends BEFORE any interruption or speaker change |
|
""" |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
user_prompt = f"""User ID: {uid} |
|
|
|
Your task is to find the starting time, ending time, and the duration for the each topic in the above Short Listed Topics. You need to return the answer in the following format. |
|
Please make sure that in the duration of 1 speaker, there is no segment of any other speaker. The shortlisted duration must be of a single speaker |
|
|
|
Return Format requirements: |
|
SPEAKER FORMAT: |
|
**Speaker Name** |
|
1. [Topic title <div id='topic' style="display: inline"> 22s at 12:30 </div>]({{link_start}}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{750}}&et={{772}}&uid={{uid}}) |
|
2. [Topic title <div id='topic' style="display: inline"> 43s at 14:45 </div>]({{link_start}}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{885}}&et={{928}}&uid={{uid}}) |
|
3. [Topic title <div id='topic' style="display: inline"> 58s at 16:20 </div>]({{link_start}}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{980}}&et={{1038}}&uid={{uid}}) |
|
**Speaker Name** |
|
.... |
|
""" |
|
completion = client.chat.completions.create( |
|
model="gpt-4o", |
|
messages=[ |
|
{"role": "system", "content": system_prompt}, |
|
{"role": "user", "content": user_prompt}, |
|
], |
|
stream=True, |
|
temperature=0.1, |
|
) |
|
|
|
collected_messages = [] |
|
|
|
for chunk in completion: |
|
if chunk.choices[0].delta.content is not None: |
|
chunk_message = chunk.choices[0].delta.content |
|
collected_messages.append(chunk_message) |
|
|
|
yield "".join(collected_messages) |
|
|
|
except Exception as e: |
|
print(f"Error in initial analysis: {str(e)}") |
|
yield "An error occurred during initial analysis. Please check your API key and file path." |
|
|
|
|
|
def chat( |
|
message: str, |
|
chat_history: List, |
|
transcript_processor: TranscriptProcessor, |
|
cid, |
|
rsid, |
|
origin, |
|
ct, |
|
uid, |
|
): |
|
|
|
try: |
|
client = OpenAI() |
|
|
|
if "localhost" in origin: |
|
link_start = "http" |
|
else: |
|
link_start = "https" |
|
speaker_mapping = transcript_processor.speaker_mapping |
|
prompt = f"""You are a helpful assistant analyzing transcripts and generating timestamps and URL. The user will ask you questions regarding the social media clips from the transcript. |
|
Call ID is {cid}, |
|
Session ID is {rsid}, |
|
origin is {origin}, |
|
Call Type is {ct}. |
|
Speakers: {", ".join(speaker_mapping.values())} |
|
Transcript: {transcript_processor.get_transcript()} |
|
|
|
If a user asks timestamps for a specific topic or things, find the start time and end time of that specific topic and return answer in the format: |
|
Answers and URLs should be formated as follows: |
|
[Topic title <div id='topic' style="display: inline"> 22s at 12:30 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{750}}&et={{772}}&uid={{uid}}) |
|
For Example: |
|
If the start time is 10:13 and end time is 10:18, the url will be: |
|
{link_start}://roll.ai/colab/1234aq_12314/51234151?st=613&et=618&uid=82314 |
|
In the URL, make sure that after RSID there is ? and then rest of the fields are added via &. |
|
You can include multiple links here that can related to the user answer. ALWAYS ANSWER FROM THE TRANSCRIPT. |
|
RULE: When selecting timestamps for the answer, always use the **starting time (XX:YY)** as the reference point for your response, with the duration (Z seconds) calculated from this starting time, not the ending time of the segment. |
|
|
|
Example 1: |
|
User: Suggest me some clips that can go viral on Instagram. |
|
Response: |
|
1. [Clip 1 <div id='topic' style="display: inline"> 22s at 12:30 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{750}}&et={{772}}&uid={{uid}}) |
|
User: Give me the URL where each person has introduced themselves. |
|
2. [Clip 2 <div id='topic' style="display: inline"> 10s at 10:00 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{600}}&et={{610}}&uid={{uid}}) |
|
|
|
Example 2: |
|
Provide the exact timestamp where the person begins their introduction, typically starting with phrases like "Hi," "Hello," "I am," or "My name is," and include the full introduction, covering everything they say about themselves, including their name, role, background, current responsibilities, organization, and any additional details they provide about their work or personal interests. |
|
1. [Person Name1 <div id='topic' style="display: inline"> 43s at 14:45 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{885}}&et={{928}}&uid={{uid}}) |
|
2. [Person Name2 <div id='topic' style="display: inline"> 58s at 16:20 </div>]({link_start}://{{origin}}/collab/{{cid}}/{{rsid}}?st={{980}}&et={{1038}}&uid={{uid}}) |
|
.... |
|
|
|
If the user provides a link to the agenda, use the correct_speaker_name_with_url function to correct the speaker names based on the agenda. |
|
If the user provides the correct call type, use the correct_call_type function to correct the call type. Call Type for street interviews is 'si'. |
|
""" |
|
messages = [{"role": "system", "content": prompt}] |
|
|
|
for user_msg, assistant_msg in chat_history: |
|
if user_msg is not None: |
|
messages.append({"role": "user", "content": user_msg}) |
|
if assistant_msg is not None: |
|
messages.append({"role": "assistant", "content": assistant_msg}) |
|
|
|
|
|
messages.append({"role": "user", "content": message}) |
|
|
|
completion = client.chat.completions.create( |
|
model="gpt-4o", |
|
messages=messages, |
|
tools=tools, |
|
stream=True, |
|
temperature=0.3, |
|
) |
|
collected_messages = [] |
|
tool_calls_detected = False |
|
|
|
for chunk in completion: |
|
if chunk.choices[0].delta.tool_calls: |
|
tool_calls_detected = True |
|
|
|
response = client.chat.completions.create( |
|
model="gpt-4o", |
|
messages=messages, |
|
tools=tools, |
|
) |
|
|
|
if response.choices[0].message.tool_calls: |
|
tool_call = response.choices[0].message.tool_calls[0] |
|
if tool_call.function.name == "correct_speaker_name_with_url": |
|
args = eval(tool_call.function.arguments) |
|
url = args.get("url", None) |
|
if url: |
|
transcript_processor.correct_speaker_mapping_with_agenda( |
|
url |
|
) |
|
corrected_speaker_mapping = ( |
|
transcript_processor.speaker_mapping |
|
) |
|
messages.append(response.choices[0].message) |
|
|
|
function_call_result_message = { |
|
"role": "tool", |
|
"content": json.dumps( |
|
{ |
|
"speaker_mapping": f"Corrected Speaker Mapping... {corrected_speaker_mapping}" |
|
} |
|
), |
|
"name": tool_call.function.name, |
|
"tool_call_id": tool_call.id, |
|
} |
|
messages.append(function_call_result_message) |
|
|
|
|
|
final_response = client.chat.completions.create( |
|
model="gpt-4o", |
|
messages=messages, |
|
stream=True, |
|
) |
|
|
|
collected_chunk = "" |
|
for final_chunk in final_response: |
|
if final_chunk.choices[0].delta.content: |
|
collected_chunk += final_chunk.choices[ |
|
0 |
|
].delta.content |
|
yield collected_chunk |
|
return |
|
else: |
|
function_call_result_message = { |
|
"role": "tool", |
|
"content": "No URL Provided", |
|
"name": tool_call.function.name, |
|
"tool_call_id": tool_call.id, |
|
} |
|
|
|
elif tool_call.function.name == "correct_call_type": |
|
args = eval(tool_call.function.arguments) |
|
call_type = args.get("call_type", None) |
|
if call_type: |
|
|
|
for content in get_initial_analysis( |
|
transcript_processor, |
|
call_type, |
|
rsid, |
|
origin, |
|
call_type, |
|
uid, |
|
): |
|
yield content |
|
return |
|
break |
|
|
|
if not tool_calls_detected and chunk.choices[0].delta.content is not None: |
|
chunk_message = chunk.choices[0].delta.content |
|
collected_messages.append(chunk_message) |
|
yield "".join(collected_messages) |
|
|
|
except Exception as e: |
|
print(f"Unexpected error in chat: {str(e)}") |
|
import traceback |
|
|
|
print(f"Traceback: {traceback.format_exc()}") |
|
yield "Sorry, there was an error processing your request." |
|
|
|
|
|
def create_chat_interface(): |
|
"""Create and configure the chat interface.""" |
|
|
|
with gr.Blocks( |
|
fill_height=True, |
|
fill_width=True, |
|
css=css, |
|
head=head, |
|
theme=gr.themes.Default( |
|
font=[gr.themes.GoogleFont("Inconsolata"), "Arial", "sans-serif"] |
|
), |
|
) as demo: |
|
chatbot = gr.Chatbot( |
|
elem_id="chatbot_box", |
|
layout="bubble", |
|
show_label=False, |
|
show_share_button=False, |
|
show_copy_all_button=False, |
|
show_copy_button=False, |
|
) |
|
msg = gr.Textbox(elem_id="chatbot_textbox", show_label=False) |
|
transcript_processor_state = gr.State() |
|
call_id_state = gr.State() |
|
colab_id_state = gr.State() |
|
origin_state = gr.State() |
|
ct_state = gr.State() |
|
turl_state = gr.State() |
|
uid_state = gr.State() |
|
iframe_html = "<iframe id='link-frame'></iframe>" |
|
gr.HTML(value=iframe_html) |
|
|
|
def respond( |
|
message: str, |
|
chat_history: List, |
|
transcript_processor, |
|
cid, |
|
rsid, |
|
origin, |
|
ct, |
|
uid, |
|
): |
|
if not transcript_processor: |
|
bot_message = "Transcript processor not initialized." |
|
chat_history.append((message, bot_message)) |
|
return "", chat_history |
|
|
|
chat_history.append((message, "")) |
|
for chunk in chat( |
|
message, |
|
chat_history[:-1], |
|
transcript_processor, |
|
cid, |
|
rsid, |
|
origin, |
|
ct, |
|
uid, |
|
): |
|
chat_history[-1] = (message, chunk) |
|
yield "", chat_history |
|
|
|
msg.submit( |
|
respond, |
|
[ |
|
msg, |
|
chatbot, |
|
transcript_processor_state, |
|
call_id_state, |
|
colab_id_state, |
|
origin_state, |
|
ct_state, |
|
uid_state, |
|
], |
|
[msg, chatbot], |
|
) |
|
|
|
|
|
def on_app_load(request: gr.Request): |
|
turls = None |
|
cid = request.query_params.get("cid", None) |
|
rsid = request.query_params.get("rsid", None) |
|
origin = request.query_params.get("origin", None) |
|
ct = request.query_params.get("ct", None) |
|
turl = request.query_params.get("turl", None) |
|
uid = request.query_params.get("uid", None) |
|
pnames = request.query_params.get("pnames", None) |
|
|
|
required_params = ["cid", "rsid", "origin", "ct", "turl", "uid"] |
|
missing_params = [ |
|
param |
|
for param in required_params |
|
if request.query_params.get(param) is None |
|
] |
|
print("Missing Params", missing_params) |
|
|
|
if missing_params: |
|
error_message = ( |
|
f"Missing required parameters: {', '.join(missing_params)}" |
|
) |
|
chatbot_value = [(None, error_message)] |
|
return [chatbot_value, None, None, None, None, None, None, None] |
|
|
|
if ct == "rp": |
|
|
|
turls = turl.split(",") |
|
pnames = [pname.replace("_", " ") for pname in pnames.split(",")] |
|
print(pnames) |
|
|
|
|
|
|
|
if turls: |
|
transcript_data = [] |
|
for turl in turls: |
|
print("Getting Transcript for URL") |
|
transcript_data.append(get_transcript_for_url(turl)) |
|
print("Now creating Processor") |
|
transcript_processor = TranscriptProcessor( |
|
transcript_data=transcript_data, |
|
call_type=ct, |
|
person_names=pnames, |
|
) |
|
|
|
else: |
|
transcript_data = get_transcript_for_url(turl) |
|
transcript_processor = TranscriptProcessor( |
|
transcript_data=transcript_data, call_type=ct |
|
) |
|
|
|
|
|
chatbot_value = [(None, "")] |
|
|
|
|
|
return [ |
|
chatbot_value, |
|
transcript_processor, |
|
cid, |
|
rsid, |
|
origin, |
|
ct, |
|
turl, |
|
uid, |
|
] |
|
|
|
|
|
|
|
|
|
|
|
|
|
def display_processing_message(chatbot_value): |
|
"""Display the processing message while maintaining state.""" |
|
|
|
new_chatbot_value = [ |
|
(None, "Video is being processed. Please wait for the results...") |
|
] |
|
|
|
|
|
return new_chatbot_value |
|
|
|
def stream_initial_analysis( |
|
chatbot_value, transcript_processor, cid, rsid, origin, ct, uid |
|
): |
|
if not transcript_processor: |
|
return chatbot_value |
|
|
|
try: |
|
for chunk in get_initial_analysis( |
|
transcript_processor, cid, rsid, origin, ct, uid |
|
): |
|
|
|
chatbot_value[0] = (None, chunk) |
|
yield chatbot_value |
|
except Exception as e: |
|
chatbot_value[0] = (None, f"Error during analysis: {str(e)}") |
|
yield chatbot_value |
|
|
|
demo.load( |
|
on_app_load, |
|
inputs=None, |
|
outputs=[ |
|
chatbot, |
|
transcript_processor_state, |
|
call_id_state, |
|
colab_id_state, |
|
origin_state, |
|
ct_state, |
|
turl_state, |
|
uid_state, |
|
], |
|
).then( |
|
display_processing_message, |
|
inputs=[chatbot], |
|
outputs=[chatbot], |
|
).then( |
|
stream_initial_analysis, |
|
inputs=[ |
|
chatbot, |
|
transcript_processor_state, |
|
call_id_state, |
|
colab_id_state, |
|
origin_state, |
|
ct_state, |
|
uid_state, |
|
], |
|
outputs=[chatbot], |
|
) |
|
return demo |
|
|
|
|
|
def main(): |
|
"""Main function to run the application.""" |
|
try: |
|
setup_openai_key() |
|
demo = create_chat_interface() |
|
demo.launch(share=True) |
|
except Exception as e: |
|
print(f"Error starting application: {str(e)}") |
|
raise |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |
|
|