Create audio_agent.py
Browse files- audio_agent.py +111 -0
audio_agent.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Optional, Dict, List, Any
|
| 3 |
+
import requests
|
| 4 |
+
import tempfile
|
| 5 |
+
import json
|
| 6 |
+
import whisper
|
| 7 |
+
from base_agent import BaseAgent
|
| 8 |
+
from transformers import pipeline, AutoModelForSpeechSeq2Seq, AutoProcessor
|
| 9 |
+
|
| 10 |
+
class AudioAgent(BaseAgent):
|
| 11 |
+
"""
|
| 12 |
+
Agent for transcribing audio/mp3 file.
|
| 13 |
+
"""
|
| 14 |
+
def __init__(self, model: str):
|
| 15 |
+
super().__init__(model=model)
|
| 16 |
+
|
| 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 = f"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 |
+
if language:
|
| 60 |
+
generate_kwargs["language"] = "auto"
|
| 61 |
+
|
| 62 |
+
# Run the pipeline directly on the file
|
| 63 |
+
result = pipe(
|
| 64 |
+
file_name,
|
| 65 |
+
generate_kwargs=generate_kwargs,
|
| 66 |
+
return_timestamps=True
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
# Process results based on output format
|
| 70 |
+
|
| 71 |
+
transcript = result["text"]
|
| 72 |
+
|
| 73 |
+
system_prompt = """
|
| 74 |
+
You are a research expert tasked with answering factual questions based on a text transcript extracted from an audio file.
|
| 75 |
+
Analyze the transcript carefully and extract the information needed to answer the question accurately.
|
| 76 |
+
Provide a concise, accurate answer based only on the provided information.
|
| 77 |
+
You must provide only the exact answer requested by the user, in the correct type and minimal format, based purely on the provided information.
|
| 78 |
+
YOUR FINAL ANSWER should be a number OR as few words as possible OR a comma separated list of numbers and/or strings.
|
| 79 |
+
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.
|
| 80 |
+
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.
|
| 81 |
+
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.
|
| 82 |
+
If you cannot find the answer based on the provided information, reply only with "Unknown".
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
user_prompt = f"""
|
| 86 |
+
Question: {question}
|
| 87 |
+
|
| 88 |
+
Transcript:
|
| 89 |
+
{transcript}
|
| 90 |
+
|
| 91 |
+
Based on these search results, provide a concise and accurate answer to the question.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
final_answer = self.llm_call(system_prompt, user_prompt)
|
| 95 |
+
|
| 96 |
+
print(f"Final answer: {final_answer}")
|
| 97 |
+
|
| 98 |
+
if final_answer.lower() == "unknown":
|
| 99 |
+
final_answer = self.ask_james(question)
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
logger.error(f"Transcription failed: {str(e)}")
|
| 103 |
+
raise
|
| 104 |
+
|
| 105 |
+
except Exception as e:
|
| 106 |
+
logger.error(f"Error loading model: {str(e)}")
|
| 107 |
+
raise
|
| 108 |
+
|
| 109 |
+
return final_answer
|
| 110 |
+
|
| 111 |
+
|