Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,34 +1,125 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from textblob import TextBlob
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
"""
|
| 14 |
blob = TextBlob(text)
|
| 15 |
sentiment = blob.sentiment
|
| 16 |
|
| 17 |
return {
|
| 18 |
-
"
|
| 19 |
-
"
|
|
|
|
| 20 |
"assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral"
|
| 21 |
}
|
| 22 |
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
demo = gr.Interface(
|
| 25 |
-
fn=
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
)
|
| 31 |
|
| 32 |
# Launch the interface and MCP server
|
| 33 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
| 34 |
demo.launch(mcp_server=True)
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from textblob import TextBlob
|
| 3 |
+
from transformers import AutoModelForSpeechSeq2Seq, AutoProcessor, pipeline
|
| 4 |
+
import torch
|
| 5 |
+
import base64
|
| 6 |
+
import numpy as np
|
| 7 |
+
import ffmpeg
|
| 8 |
|
| 9 |
+
# 1. Set up device and data type for optimized performance
|
| 10 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
| 11 |
+
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
| 12 |
|
| 13 |
+
# 2. Define the model ID for the large Whisper model
|
| 14 |
+
model_id = "openai/whisper-large-v3-turbo"
|
| 15 |
|
| 16 |
+
# 3. Load the model from pretrained weights
|
| 17 |
+
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
| 18 |
+
model_id, torch_dtype=torch_dtype, low_cpu_mem_usage=True, use_safetensors=True
|
| 19 |
+
)
|
| 20 |
+
model.to(device)
|
| 21 |
+
|
| 22 |
+
# 4. Load the processor which includes the feature extractor and tokenizer
|
| 23 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
| 24 |
+
|
| 25 |
+
# 5. Create the ASR pipeline with the loaded components
|
| 26 |
+
pipe = pipeline(
|
| 27 |
+
"automatic-speech-recognition",
|
| 28 |
+
model=model,
|
| 29 |
+
tokenizer=processor.tokenizer,
|
| 30 |
+
feature_extractor=processor.feature_extractor,
|
| 31 |
+
max_new_tokens=128,
|
| 32 |
+
torch_dtype=torch_dtype,
|
| 33 |
+
device=device,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
def sentiment_analysis(text: str) -> dict:
|
| 37 |
+
"""
|
| 38 |
+
Analyze the sentiment of the given text. (This function is unchanged)
|
| 39 |
"""
|
| 40 |
blob = TextBlob(text)
|
| 41 |
sentiment = blob.sentiment
|
| 42 |
|
| 43 |
return {
|
| 44 |
+
"transcript": text,
|
| 45 |
+
"polarity": round(sentiment.polarity, 2),
|
| 46 |
+
"subjectivity": round(sentiment.subjectivity, 2),
|
| 47 |
"assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral"
|
| 48 |
}
|
| 49 |
|
| 50 |
+
def process_base64_audio(base64_data_uri: str) -> dict:
|
| 51 |
+
"""
|
| 52 |
+
Decodes a Base64 audio data URI, processes it in-memory,
|
| 53 |
+
transcribes it using a Hugging Face Whisper pipeline, and then analyzes its sentiment.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
base64_data_uri (str): A string in data URI format (e.g., "data:audio/wav;base64,UklGRi...").
|
| 57 |
+
|
| 58 |
+
Returns:
|
| 59 |
+
dict: The sentiment analysis result or an error message.
|
| 60 |
+
"""
|
| 61 |
+
if not base64_data_uri or "base64," not in base64_data_uri:
|
| 62 |
+
return {"error": "Invalid or empty Base64 data URI provided."}
|
| 63 |
+
|
| 64 |
+
try:
|
| 65 |
+
# Parse the data URI to extract the Base64 encoded data
|
| 66 |
+
_, encoded_data = base64_data_uri.split(',', 1)
|
| 67 |
+
|
| 68 |
+
# Decode the Base64 string into binary audio data
|
| 69 |
+
audio_data = base64.b64decode(encoded_data)
|
| 70 |
+
|
| 71 |
+
# Use ffmpeg to convert the in-memory audio data to a raw PCM buffer.
|
| 72 |
+
# The pipeline expects a 16kHz mono audio stream.
|
| 73 |
+
out, _ = (
|
| 74 |
+
ffmpeg
|
| 75 |
+
.input('pipe:0')
|
| 76 |
+
.output('pipe:1', format='s16le', ac=1, ar=16000)
|
| 77 |
+
.run(input=audio_data, capture_stdout=True, capture_stderr=True)
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
# Convert the raw PCM buffer to a NumPy array of 32-bit floats.
|
| 81 |
+
audio_np = np.frombuffer(out, np.int16).astype(np.float32) / 32768.0
|
| 82 |
+
|
| 83 |
+
# Transcribe the audio from the NumPy array using the HF pipeline
|
| 84 |
+
transcription_result = pipe(audio_np)
|
| 85 |
+
transcript_text = transcription_result["text"]
|
| 86 |
+
|
| 87 |
+
except Exception as e:
|
| 88 |
+
# Capture potential errors from ffmpeg or the model
|
| 89 |
+
return {"error": f"Failed to process audio: {str(e)}"}
|
| 90 |
+
|
| 91 |
+
# Perform sentiment analysis on the transcribed text
|
| 92 |
+
return sentiment_analysis(transcript_text)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# Create the Gradio interface with the Hugging Face theme
|
| 96 |
demo = gr.Interface(
|
| 97 |
+
fn=process_base64_audio,
|
| 98 |
+
# The input remains a Textbox to accept the raw Base64 string from the API client
|
| 99 |
+
inputs=gr.Textbox(lines=5, placeholder="Paste your Base64 encoded audio data URI here...", label="Base64 Audio Input"),
|
| 100 |
+
outputs=gr.JSON(label="Analysis Result"),
|
| 101 |
+
title="🎙️ Audio Sentiment Analysis (Whisper Large v3)",
|
| 102 |
+
description="""
|
| 103 |
+
Analyze the sentiment of spoken words.
|
| 104 |
+
This tool accepts a **Base64 encoded audio data URI**, transcribes the audio in-memory using the `openai/whisper-large-v3` model,
|
| 105 |
+
and performs sentiment analysis on the text with TextBlob.
|
| 106 |
+
""",
|
| 107 |
+
examples=[
|
| 108 |
+
["data:audio/wav;base64,UklGRiQ...<placeholder_for_a_short_positive_clip>"],
|
| 109 |
+
["data:audio/wav;base64,UklGRiQ...<placeholder_for_a_short_negative_clip>"]
|
| 110 |
+
],
|
| 111 |
+
article="""
|
| 112 |
+
### How to get a Base64 Audio URI?
|
| 113 |
+
You can use an online converter or a script (like the provided `test_client.py`) to convert a short audio file (e.g., .wav or .mp3) into a Base64 data URI.
|
| 114 |
+
The format must be `data:audio/[format];base64,[encoded_string]`.
|
| 115 |
+
""",
|
| 116 |
+
theme='huggingface' # This applies the new theme
|
| 117 |
)
|
| 118 |
|
| 119 |
# Launch the interface and MCP server
|
| 120 |
if __name__ == "__main__":
|
| 121 |
+
# You will need to have ffmpeg installed on your system for this to work.
|
| 122 |
+
# You also need to install the required python packages. This model is large and requires significant resources.
|
| 123 |
+
# pip install gradio textblob "transformers[torch]" accelerate safetensors ffmpeg-python numpy
|
| 124 |
demo.launch(mcp_server=True)
|
| 125 |
+
|