Spaces:
Running
Running
Upload 5 files
Browse files
src/app/__pycache__/main_agent.cpython-310.pyc
ADDED
Binary file (1.91 kB). View file
|
|
src/app/main_agent.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# from langchain_core.messages import HumanMessage, AIMessage
|
2 |
+
# from langgraph.graph import MessageGraph
|
3 |
+
# from langchain_core.runnables import RunnableLambda
|
4 |
+
# from langchain_core.messages import BaseMessage
|
5 |
+
# from langchain.tools import Tool
|
6 |
+
# from langchain_core.runnables import RunnableLambda, Runnable
|
7 |
+
# import re
|
8 |
+
|
9 |
+
# def create_agent(accent_tool_obj) -> 'Runnable':
|
10 |
+
# accent_tool = Tool(
|
11 |
+
# name="AccentAnalyzer",
|
12 |
+
# func=accent_tool_obj.analyze,
|
13 |
+
# description="Analyze a public MP4 video URL and determine the English accent with transcription."
|
14 |
+
# )
|
15 |
+
|
16 |
+
# def analyze_node(messages: list[BaseMessage]) -> AIMessage:
|
17 |
+
# last_input = messages[-1].content
|
18 |
+
# match = re.search(r'https?://\S+', last_input)
|
19 |
+
# if match:
|
20 |
+
# url = match.group()
|
21 |
+
# result = accent_tool.func(url)
|
22 |
+
# else:
|
23 |
+
# result = "No valid video URL found in your message."
|
24 |
+
# return AIMessage(content=result)
|
25 |
+
|
26 |
+
# graph = MessageGraph()
|
27 |
+
# graph.add_node("analyze_accent", RunnableLambda(analyze_node))
|
28 |
+
# graph.set_entry_point("analyze_accent")
|
29 |
+
# graph.set_finish_point("analyze_accent")
|
30 |
+
|
31 |
+
# return graph.compile()
|
32 |
+
# --------------------------------------
|
33 |
+
|
34 |
+
from langchain_core.messages import BaseMessage, AIMessage
|
35 |
+
from langchain_core.runnables import RunnableLambda, Runnable
|
36 |
+
from langchain_community.llms import Ollama
|
37 |
+
from langchain.tools import Tool
|
38 |
+
from langgraph.graph import MessageGraph
|
39 |
+
import re
|
40 |
+
|
41 |
+
llm = Ollama(model="gemma3", temperature=0.0) # llama3.1
|
42 |
+
|
43 |
+
def create_agent(accent_tool_obj) -> tuple[Runnable, Runnable]:
|
44 |
+
accent_tool = Tool(
|
45 |
+
name="AccentAnalyzer",
|
46 |
+
func=accent_tool_obj.analyze,
|
47 |
+
description="Analyze a public MP4 video URL and determine the English accent with transcription."
|
48 |
+
)
|
49 |
+
|
50 |
+
def analyze_node(messages: list[BaseMessage]) -> AIMessage:
|
51 |
+
last_input = messages[-1].content
|
52 |
+
match = re.search(r'https?://\S+', last_input)
|
53 |
+
if match:
|
54 |
+
url = match.group()
|
55 |
+
result = accent_tool.func(url)
|
56 |
+
else:
|
57 |
+
result = "No valid video URL found in your message."
|
58 |
+
return AIMessage(content=result)
|
59 |
+
|
60 |
+
graph = MessageGraph()
|
61 |
+
graph.add_node("analyze_accent", RunnableLambda(analyze_node))
|
62 |
+
graph.set_entry_point("analyze_accent")
|
63 |
+
graph.set_finish_point("analyze_accent")
|
64 |
+
analysis_agent = graph.compile()
|
65 |
+
|
66 |
+
# Follow-up agent that uses transcript and responds to questions
|
67 |
+
def follow_up_node(messages: list[BaseMessage]) -> AIMessage:
|
68 |
+
user_question = messages[-1].content
|
69 |
+
transcript = accent_tool_obj.last_transcript or ""
|
70 |
+
prompt = f"""You are given this transcript of a video:
|
71 |
+
|
72 |
+
\"\"\"{transcript}\"\"\"
|
73 |
+
|
74 |
+
Now respond to the user's follow-up question: {user_question}
|
75 |
+
"""
|
76 |
+
response = llm.invoke(prompt)
|
77 |
+
return AIMessage(content=response)
|
78 |
+
|
79 |
+
follow_up_agent = RunnableLambda(follow_up_node)
|
80 |
+
|
81 |
+
return analysis_agent, follow_up_agent
|
src/custom_interface.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from speechbrain.pretrained import Pretrained
|
3 |
+
|
4 |
+
|
5 |
+
class CustomEncoderWav2vec2Classifier(Pretrained):
|
6 |
+
"""A ready-to-use class for utterance-level classification (e.g, speaker-id,
|
7 |
+
language-id, emotion recognition, keyword spotting, etc).
|
8 |
+
|
9 |
+
The class assumes that an self-supervised encoder like wav2vec2/hubert and a classifier model
|
10 |
+
are defined in the yaml file. If you want to
|
11 |
+
convert the predicted index into a corresponding text label, please
|
12 |
+
provide the path of the label_encoder in a variable called 'lab_encoder_file'
|
13 |
+
within the yaml.
|
14 |
+
|
15 |
+
The class can be used either to run only the encoder (encode_batch()) to
|
16 |
+
extract embeddings or to run a classification step (classify_batch()).
|
17 |
+
```
|
18 |
+
|
19 |
+
Example
|
20 |
+
-------
|
21 |
+
>>> import torchaudio
|
22 |
+
>>> from speechbrain.pretrained import EncoderClassifier
|
23 |
+
>>> # Model is downloaded from the speechbrain HuggingFace repo
|
24 |
+
>>> tmpdir = getfixture("tmpdir")
|
25 |
+
>>> classifier = EncoderClassifier.from_hparams(
|
26 |
+
... source="speechbrain/spkrec-ecapa-voxceleb",
|
27 |
+
... savedir=tmpdir,
|
28 |
+
... )
|
29 |
+
|
30 |
+
>>> # Compute embeddings
|
31 |
+
>>> signal, fs = torchaudio.load("samples/audio_samples/example1.wav")
|
32 |
+
>>> embeddings = classifier.encode_batch(signal)
|
33 |
+
|
34 |
+
>>> # Classification
|
35 |
+
>>> prediction = classifier .classify_batch(signal)
|
36 |
+
"""
|
37 |
+
|
38 |
+
def __init__(self, *args, **kwargs):
|
39 |
+
super().__init__(*args, **kwargs)
|
40 |
+
|
41 |
+
def encode_batch(self, wavs, wav_lens=None, normalize=False):
|
42 |
+
"""Encodes the input audio into a single vector embedding.
|
43 |
+
|
44 |
+
The waveforms should already be in the model's desired format.
|
45 |
+
You can call:
|
46 |
+
``normalized = <this>.normalizer(signal, sample_rate)``
|
47 |
+
to get a correctly converted signal in most cases.
|
48 |
+
|
49 |
+
Arguments
|
50 |
+
---------
|
51 |
+
wavs : torch.tensor
|
52 |
+
Batch of waveforms [batch, time, channels] or [batch, time]
|
53 |
+
depending on the model. Make sure the sample rate is fs=16000 Hz.
|
54 |
+
wav_lens : torch.tensor
|
55 |
+
Lengths of the waveforms relative to the longest one in the
|
56 |
+
batch, tensor of shape [batch]. The longest one should have
|
57 |
+
relative length 1.0 and others len(waveform) / max_length.
|
58 |
+
Used for ignoring padding.
|
59 |
+
normalize : bool
|
60 |
+
If True, it normalizes the embeddings with the statistics
|
61 |
+
contained in mean_var_norm_emb.
|
62 |
+
|
63 |
+
Returns
|
64 |
+
-------
|
65 |
+
torch.tensor
|
66 |
+
The encoded batch
|
67 |
+
"""
|
68 |
+
# Manage single waveforms in input
|
69 |
+
if len(wavs.shape) == 1:
|
70 |
+
wavs = wavs.unsqueeze(0)
|
71 |
+
|
72 |
+
# Assign full length if wav_lens is not assigned
|
73 |
+
if wav_lens is None:
|
74 |
+
wav_lens = torch.ones(wavs.shape[0], device=self.device)
|
75 |
+
|
76 |
+
# Storing waveform in the specified device
|
77 |
+
wavs, wav_lens = wavs.to(self.device), wav_lens.to(self.device)
|
78 |
+
wavs = wavs.float()
|
79 |
+
|
80 |
+
# Computing features and embeddings
|
81 |
+
outputs = self.mods.wav2vec2(wavs)
|
82 |
+
|
83 |
+
# last dim will be used for AdaptativeAVG pool
|
84 |
+
outputs = self.mods.avg_pool(outputs, wav_lens)
|
85 |
+
outputs = outputs.view(outputs.shape[0], -1)
|
86 |
+
return outputs
|
87 |
+
|
88 |
+
def classify_batch(self, wavs, wav_lens=None):
|
89 |
+
"""Performs classification on the top of the encoded features.
|
90 |
+
|
91 |
+
It returns the posterior probabilities, the index and, if the label
|
92 |
+
encoder is specified it also the text label.
|
93 |
+
|
94 |
+
Arguments
|
95 |
+
---------
|
96 |
+
wavs : torch.tensor
|
97 |
+
Batch of waveforms [batch, time, channels] or [batch, time]
|
98 |
+
depending on the model. Make sure the sample rate is fs=16000 Hz.
|
99 |
+
wav_lens : torch.tensor
|
100 |
+
Lengths of the waveforms relative to the longest one in the
|
101 |
+
batch, tensor of shape [batch]. The longest one should have
|
102 |
+
relative length 1.0 and others len(waveform) / max_length.
|
103 |
+
Used for ignoring padding.
|
104 |
+
|
105 |
+
Returns
|
106 |
+
-------
|
107 |
+
out_prob
|
108 |
+
The log posterior probabilities of each class ([batch, N_class])
|
109 |
+
score:
|
110 |
+
It is the value of the log-posterior for the best class ([batch,])
|
111 |
+
index
|
112 |
+
The indexes of the best class ([batch,])
|
113 |
+
text_lab:
|
114 |
+
List with the text labels corresponding to the indexes.
|
115 |
+
(label encoder should be provided).
|
116 |
+
"""
|
117 |
+
outputs = self.encode_batch(wavs, wav_lens)
|
118 |
+
outputs = self.mods.output_mlp(outputs)
|
119 |
+
out_prob = self.hparams.softmax(outputs)
|
120 |
+
score, index = torch.max(out_prob, dim=-1)
|
121 |
+
text_lab = self.hparams.label_encoder.decode_torch(index)
|
122 |
+
return out_prob, score, index, text_lab
|
123 |
+
|
124 |
+
def classify_file(self, path):
|
125 |
+
"""Classifies the given audiofile into the given set of labels.
|
126 |
+
|
127 |
+
Arguments
|
128 |
+
---------
|
129 |
+
path : str
|
130 |
+
Path to audio file to classify.
|
131 |
+
|
132 |
+
Returns
|
133 |
+
-------
|
134 |
+
out_prob
|
135 |
+
The log posterior probabilities of each class ([batch, N_class])
|
136 |
+
score:
|
137 |
+
It is the value of the log-posterior for the best class ([batch,])
|
138 |
+
index
|
139 |
+
The indexes of the best class ([batch,])
|
140 |
+
text_lab:
|
141 |
+
List with the text labels corresponding to the indexes.
|
142 |
+
(label encoder should be provided).
|
143 |
+
"""
|
144 |
+
waveform = self.load_audio(path)
|
145 |
+
# Fake a batch:
|
146 |
+
batch = waveform.unsqueeze(0)
|
147 |
+
rel_length = torch.tensor([1.0])
|
148 |
+
outputs = self.encode_batch(batch, rel_length)
|
149 |
+
outputs = self.mods.output_mlp(outputs).squeeze(1)
|
150 |
+
out_prob = self.hparams.softmax(outputs)
|
151 |
+
score, index = torch.max(out_prob, dim=-1)
|
152 |
+
text_lab = self.hparams.label_encoder.decode_torch(index)
|
153 |
+
return out_prob, score, index, text_lab
|
154 |
+
|
155 |
+
def forward(self, wavs, wav_lens=None, normalize=False):
|
156 |
+
return self.encode_batch(
|
157 |
+
wavs=wavs, wav_lens=wav_lens, normalize=normalize
|
158 |
+
)
|
src/tools/__pycache__/accent_tool.cpython-310.pyc
ADDED
Binary file (2.25 kB). View file
|
|
src/tools/accent_tool.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os, requests, shutil
|
2 |
+
from pydub import AudioSegment
|
3 |
+
import whisper
|
4 |
+
from speechbrain.pretrained.interfaces import foreign_class
|
5 |
+
|
6 |
+
class AccentAnalyzerTool:
|
7 |
+
def __init__(self):
|
8 |
+
self.whisper_model = whisper.load_model("medium")
|
9 |
+
self.accent_model = foreign_class(
|
10 |
+
source="Jzuluaga/accent-id-commonaccent_xlsr-en-english",
|
11 |
+
pymodule_file="custom_interface.py",
|
12 |
+
classname="CustomEncoderWav2vec2Classifier"
|
13 |
+
)
|
14 |
+
self.last_transcript = None
|
15 |
+
|
16 |
+
def log(self, msg):
|
17 |
+
print(f"[AccentAnalyzerTool] {msg}")
|
18 |
+
|
19 |
+
def analyze(self, url: str) -> str:
|
20 |
+
try:
|
21 |
+
self.log("Downloading video...")
|
22 |
+
tmp_dir = "tmp"
|
23 |
+
os.makedirs(tmp_dir, exist_ok=True)
|
24 |
+
video_path = os.path.join(tmp_dir, "video.mp4")
|
25 |
+
r = requests.get(url)
|
26 |
+
with open(video_path, "wb") as f:
|
27 |
+
f.write(r.content)
|
28 |
+
|
29 |
+
self.log("Extracting audio...")
|
30 |
+
audio_path = os.path.join(tmp_dir, "audio.wav")
|
31 |
+
AudioSegment.from_file(video_path).export(audio_path, format="wav")
|
32 |
+
|
33 |
+
self.log("Classifying accent...")
|
34 |
+
_, score, _, label = self.accent_model.classify_file(audio_path)
|
35 |
+
accent = label[0].upper() if label[0] == 'us' else label[0].capitalize()
|
36 |
+
confidence = round(float(score) * 100, 2)
|
37 |
+
|
38 |
+
self.log("Transcribing...")
|
39 |
+
transcript = self.whisper_model.transcribe(audio_path)["text"]
|
40 |
+
self.last_transcript = transcript
|
41 |
+
|
42 |
+
summary = (
|
43 |
+
f"The speaker has a **{accent} English accent** "
|
44 |
+
f"with **{confidence}% confidence**.\n\n"
|
45 |
+
f"**Transcript of the audio:**\n\n *{transcript.strip(' ')}*"
|
46 |
+
)
|
47 |
+
|
48 |
+
shutil.rmtree(tmp_dir, ignore_errors=True)
|
49 |
+
return summary
|
50 |
+
|
51 |
+
except Exception as e:
|
52 |
+
return f"Error analyzing accent: {str(e)}"
|