mahadewa commited on
Commit
17ea9f2
·
verified ·
1 Parent(s): 0c1043b

Update audio_agent.py

Browse files
Files changed (1) hide show
  1. audio_agent.py +86 -79
audio_agent.py CHANGED
@@ -17,92 +17,99 @@ class AudioAgent(BaseAgent):
17
  def __call__(self, question: str, file_name: str, **kwargs) -> str:
18
  print(f"AudioAgent: Transcribing file: {file_name}")
19
 
20
- search_query = self.extract_search_query(question)
21
-
22
  try:
23
- # Set the model ID based on size
24
- model_id = "openai/whisper-tiny"
25
-
26
- # Load model with optimizations for CPU
27
- model = AutoModelForSpeechSeq2Seq.from_pretrained(
28
- model_id,
29
- torch_dtype=torch.float32, # Use float32 for CPU
30
- low_cpu_mem_usage=True,
31
- use_safetensors=True
32
- )
33
-
34
- # Load processor
35
- processor = AutoProcessor.from_pretrained(model_id)
36
-
37
- # Create pipeline with small batch size for CPU
38
- pipe = pipeline(
39
- "automatic-speech-recognition",
40
- model=model,
41
- tokenizer=processor.tokenizer,
42
- feature_extractor=processor.feature_extractor,
43
- max_new_tokens=128,
44
- chunk_length_s=30,
45
- batch_size=1, # Small batch size for CPU
46
- return_timestamps=True,
47
- device="cpu",
48
- )
49
-
50
- print("Model loaded successfully.")
51
-
52
- print(f"Starting transcription of {file_name}")
53
 
54
- try:
55
- print("Running transcription (this may take some time on CPU)...")
56
-
57
- # Set task and language options
58
- generate_kwargs = {}
59
- generate_kwargs["language"] = "auto"
60
 
61
- # Run the pipeline directly on the file
62
- result = pipe(
63
- file_name,
64
- generate_kwargs=generate_kwargs,
65
- return_timestamps=True
66
- )
67
-
68
- # Process results based on output format
69
-
70
- transcript = result["text"]
71
-
72
- system_prompt = """
73
- You are a research expert tasked with answering factual questions based on a text transcript extracted from an audio file.
74
- Analyze the transcript carefully and extract the information needed to answer the question accurately.
75
- Provide a concise, accurate answer based only on the provided information.
76
- You must provide only the exact answer requested by the user, in the correct type and minimal format, based purely on the provided information.
77
- YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
78
- If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
79
- If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
80
- If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
81
- If you cannot find the answer based on the provided information, reply only with "Unknown".
82
- """
83
-
84
- user_prompt = f"""
85
- Question: {question}
86
-
87
- Transcript:
88
- {transcript}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
- Based on these search results, provide a concise and accurate answer to the question.
91
- """
92
-
93
- final_answer = self.llm_call(system_prompt, user_prompt)
94
-
95
- print(f"Final answer: {final_answer}")
96
 
97
- if final_answer.lower() == "unknown":
98
- final_answer = self.ask_james(question)
 
 
 
 
 
99
 
100
- except Exception as e:
101
- print(f"Transcription failed: {str(e)}")
102
- raise
103
-
104
  except Exception as e:
105
- print(f"Error loading model: {str(e)}")
106
  raise
107
 
108
  return final_answer
 
17
  def __call__(self, question: str, file_name: str, **kwargs) -> str:
18
  print(f"AudioAgent: Transcribing file: {file_name}")
19
 
 
 
20
  try:
21
+ if file_name:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ search_query = self.extract_search_query(question)
24
+
25
+ try:
26
+ # Set the model ID based on size
27
+ model_id = "openai/whisper-tiny"
 
28
 
29
+ # Load model with optimizations for CPU
30
+ model = AutoModelForSpeechSeq2Seq.from_pretrained(
31
+ model_id,
32
+ torch_dtype=torch.float32, # Use float32 for CPU
33
+ low_cpu_mem_usage=True,
34
+ use_safetensors=True
35
+ )
36
+
37
+ # Load processor
38
+ processor = AutoProcessor.from_pretrained(model_id)
39
+
40
+ # Create pipeline with small batch size for CPU
41
+ pipe = pipeline(
42
+ "automatic-speech-recognition",
43
+ model=model,
44
+ tokenizer=processor.tokenizer,
45
+ feature_extractor=processor.feature_extractor,
46
+ max_new_tokens=128,
47
+ chunk_length_s=30,
48
+ batch_size=1, # Small batch size for CPU
49
+ return_timestamps=True,
50
+ device="cpu",
51
+ )
52
+
53
+ print("Model loaded successfully.")
54
+
55
+ print(f"Starting transcription of {file_name}")
56
+
57
+ try:
58
+ print("Running transcription (this may take some time on CPU)...")
59
+
60
+ # Set task and language options
61
+ generate_kwargs = {}
62
+ generate_kwargs["language"] = "auto"
63
+
64
+ # Run the pipeline directly on the file
65
+ result = pipe(
66
+ file_name,
67
+ generate_kwargs=generate_kwargs,
68
+ return_timestamps=True
69
+ )
70
+
71
+ # Process results based on output format
72
+
73
+ transcript = result["text"]
74
+
75
+ system_prompt = """
76
+ You are a research expert tasked with answering factual questions based on a text transcript extracted from an audio file.
77
+ Analyze the transcript carefully and extract the information needed to answer the question accurately.
78
+ Provide a concise, accurate answer based only on the provided information.
79
+ You must provide only the exact answer requested by the user, in the correct type and minimal format, based purely on the provided information.
80
+ YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
81
+ If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise.
82
+ If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise.
83
+ If you are asked for a comma separated list, apply the above rules depending of whether the element to be put in the list is a number or a string.
84
+ If you cannot find the answer based on the provided information, reply only with "Unknown".
85
+ """
86
+
87
+ user_prompt = f"""
88
+ Question: {question}
89
+
90
+ Transcript:
91
+ {transcript}
92
+
93
+ Based on these search results, provide a concise and accurate answer to the question.
94
+ """
95
+
96
+ final_answer = self.llm_call(system_prompt, user_prompt)
97
+
98
+ print(f"Final answer: {final_answer}")
99
 
100
+ if final_answer.lower() == "unknown":
101
+ final_answer = self.ask_james(question)
 
 
 
 
102
 
103
+ except Exception as e:
104
+ print(f"Transcription failed: {str(e)}")
105
+ raise
106
+
107
+ except Exception as e:
108
+ print(f"Error loading model: {str(e)}")
109
+ raise
110
 
 
 
 
 
111
  except Exception as e:
112
+ print(f"Transcription failed: {str(e)}")
113
  raise
114
 
115
  return final_answer