ferhatbou's picture
Fix import issue
98a96df
import gradio as gr
from video_accent_analyzer import VideoAccentAnalyzer
import plotly.graph_objects as go
import pandas as pd
analyzer = VideoAccentAnalyzer()
def create_plotly_chart(probabilities):
"""Create an interactive Plotly bar chart for accent probabilities"""
accents = [analyzer.accent_display_names.get(acc, acc.title()) for acc in probabilities.keys()]
probs = list(probabilities.values())
colors = ['#4CAF50' if p == max(probs) else '#2196F3' if p >= 20
else '#FFC107' if p >= 10 else '#9E9E9E' for p in probs]
fig = go.Figure(data=[
go.Bar(
x=accents,
y=probs,
marker_color=colors,
text=[f'{p:.1f}%' for p in probs],
textposition='auto',
)
])
fig.update_layout(
title='Accent Probability Distribution',
xaxis_title='Accent Type',
yaxis_title='Probability (%)',
template='plotly_white',
yaxis_range=[0, 100],
)
return fig
def analyze_video(url=None, video_file=None, duration=30):
"""Analyze video from URL or file with enhanced output"""
try:
if not url and not video_file:
return (
"### ❌ Error\nPlease provide either a video URL or upload a video file.",
None
)
if url:
result = analyzer.analyze_video_url(url, max_duration=duration)
else:
result = analyzer.analyze_local_video(video_file, max_duration=duration)
if 'error' in result:
return (
f"### ❌ Error\n{result['error']}",
None
)
# Create markdown output
markdown = f"""
### 🎯 Analysis Results
**Primary Classification:**
- πŸ—£οΈ Predicted Accent: {analyzer.accent_display_names.get(result['predicted_accent'])}
- πŸ“Š Confidence: {result['accent_confidence']:.1f}%
- 🌍 English Confidence: {result['english_confidence']:.1f}%
**Audio Analysis:**
- ⏱️ Duration: {result['audio_duration']:.1f} seconds
- πŸ“Š Quality Score: {result.get('audio_quality_score', 'N/A')}
- 🎡 Chunks Analyzed: {result.get('chunks_analyzed', 1)}
**Assessment:**
- {'βœ… Strong English Speaker' if result['english_confidence'] >= 70 else '⚠️ Moderate English Confidence' if result['english_confidence'] >= 50 else '❓ Low English Confidence'}
- {'🎯 High Accent Confidence' if result['accent_confidence'] >= 70 else 'πŸ€” Moderate Accent Confidence' if result['accent_confidence'] >= 50 else '❓ Low Accent Confidence'}
"""
# Create visualization
fig = create_plotly_chart(result['all_probabilities'])
return markdown, fig
except Exception as e:
return f"### ❌ Error\nAn unexpected error occurred: {str(e)}", None
# Create Gradio interface
css = """
.gradio-container {
font-family: 'IBM Plex Sans', sans-serif;
}
.gr-button {
background: linear-gradient(45deg, #4CAF50, #2196F3);
border: none;
}
.gr-button:hover {
background: linear-gradient(45deg, #2196F3, #4CAF50);
transform: scale(1.02);
}
"""
with gr.Blocks(css=css) as interface:
gr.Markdown("""
# 🎧 Video Accent Analyzer
Analyze English accents in videos from various sources:
- MP4 videos
- Loom recordings
- Direct video links
- Uploaded video files
### πŸ’‘ Tips
- Keep videos under 2 minutes for best results
- Ensure clear audio quality
- Multiple speakers may affect accuracy
""")
with gr.Row():
with gr.Column():
url_input = gr.Textbox(
label="Video URL",
placeholder="Enter , Loom, or direct video URL"
)
video_input = gr.File(
label="Or Upload Video",
file_types=["video"]
)
duration = gr.Slider(
minimum=10,
maximum=120,
value=30,
step=10,
label="Maximum Duration (seconds)"
)
analyze_btn = gr.Button("πŸ” Analyze Video", variant="primary")
with gr.Column():
output_text = gr.Markdown(label="Analysis Results")
output_plot = gr.Plot(label="Accent Distribution")
analyze_btn.click(
fn=analyze_video,
inputs=[url_input, video_input, duration],
outputs=[output_text, output_plot]
)
gr.Examples(
examples=[
["https://www.loom.com/share/7b82b3e25ec8409a8e4b5568e95dca5c?sid=e0819070-d2ba-4236-a7a0-878c8739040f", None, 30],
],
inputs=[url_input, video_input, duration],
outputs=[output_text, output_plot],
label="Example Videos"
)
if __name__ == "__main__":
interface.launch()