ferhatbou/detect_English_language_speaking
0
1import gradio as gr2from video_accent_analyzer import VideoAccentAnalyzer3import plotly.graph_objects as go4import pandas as pd5 6analyzer = VideoAccentAnalyzer()7 8 9def create_plotly_chart(probabilities):10 """Create an interactive Plotly bar chart for accent probabilities"""11 accents = [analyzer.accent_display_names.get(acc, acc.title()) for acc in probabilities.keys()]12 probs = list(probabilities.values())13 14 colors = ['#4CAF50' if p == max(probs) else '#2196F3' if p >= 2015 else '#FFC107' if p >= 10 else '#9E9E9E' for p in probs]16 17 fig = go.Figure(data=[18 go.Bar(19 x=accents,20 y=probs,21 marker_color=colors,22 text=[f'{p:.1f}%' for p in probs],23 textposition='auto',24 )25 ])26 27 fig.update_layout(28 title='Accent Probability Distribution',29 xaxis_title='Accent Type',30 yaxis_title='Probability (%)',31 template='plotly_white',32 yaxis_range=[0, 100],33 )34 35 return fig36 37 38def analyze_video(url=None, video_file=None, duration=30):39 """Analyze video from URL or file with enhanced output"""40 try:41 if not url and not video_file:42 return (43 "### ❌ Error\nPlease provide either a video URL or upload a video file.",44 None45 )46 47 if url:48 result = analyzer.analyze_video_url(url, max_duration=duration)49 else:50 result = analyzer.analyze_local_video(video_file, max_duration=duration)51 52 if 'error' in result:53 return (54 f"### ❌ Error\n{result['error']}",55 None56 )57 58 # Create markdown output59 markdown = f"""60 ### 🎯 Analysis Results61 62 **Primary Classification:**63 - 🗣️ Predicted Accent: {analyzer.accent_display_names.get(result['predicted_accent'])}64 - 📊 Confidence: {result['accent_confidence']:.1f}%65 - 🌍 English Confidence: {result['english_confidence']:.1f}%66 67 **Audio Analysis:**68 - ⏱️ Duration: {result['audio_duration']:.1f} seconds69 - 📊 Quality Score: {result.get('audio_quality_score', 'N/A')}70 - 🎵 Chunks Analyzed: {result.get('chunks_analyzed', 1)}71 72 **Assessment:**73 - {'✅ Strong English Speaker' if result['english_confidence'] >= 70 else '⚠️ Moderate English Confidence' if result['english_confidence'] >= 50 else '❓ Low English Confidence'}74 - {'🎯 High Accent Confidence' if result['accent_confidence'] >= 70 else '🤔 Moderate Accent Confidence' if result['accent_confidence'] >= 50 else '❓ Low Accent Confidence'}75 """76 77 # Create visualization78 fig = create_plotly_chart(result['all_probabilities'])79 80 return markdown, fig81 82 except Exception as e:83 return f"### ❌ Error\nAn unexpected error occurred: {str(e)}", None84 85 86# Create Gradio interface87css = """88 .gradio-container {89 font-family: 'IBM Plex Sans', sans-serif;90 }91 .gr-button {92 background: linear-gradient(45deg, #4CAF50, #2196F3);93 border: none;94 }95 .gr-button:hover {96 background: linear-gradient(45deg, #2196F3, #4CAF50);97 transform: scale(1.02);98 }99 """100 101with gr.Blocks(css=css) as interface:102 gr.Markdown("""103 # 🎧 Video Accent Analyzer104 105 Analyze English accents in videos from various sources:106 - MP4 videos107 - Loom recordings108 - Direct video links109 - Uploaded video files110 111 ### 💡 Tips112 - Keep videos under 2 minutes for best results113 - Ensure clear audio quality114 - Multiple speakers may affect accuracy115 """)116 117 with gr.Row():118 with gr.Column():119 url_input = gr.Textbox(120 label="Video URL",121 placeholder="Enter , Loom, or direct video URL"122 )123 video_input = gr.File(124 label="Or Upload Video",125 file_types=["video"]126 )127 duration = gr.Slider(128 minimum=10,129 maximum=120,130 value=30,131 step=10,132 label="Maximum Duration (seconds)"133 )134 analyze_btn = gr.Button("🔍 Analyze Video", variant="primary")135 136 with gr.Column():137 output_text = gr.Markdown(label="Analysis Results")138 output_plot = gr.Plot(label="Accent Distribution")139 140 analyze_btn.click(141 fn=analyze_video,142 inputs=[url_input, video_input, duration],143 outputs=[output_text, output_plot]144 )145 146 gr.Examples(147 examples=[148 ["https://www.loom.com/share/7b82b3e25ec8409a8e4b5568e95dca5c?sid=e0819070-d2ba-4236-a7a0-878c8739040f", None, 30],149 ],150 inputs=[url_input, video_input, duration],151 outputs=[output_text, output_plot],152 label="Example Videos"153 )154 155 156if __name__ == "__main__":157 interface.launch()158 