mguven61 commited on
Commit
3ed5ff4
·
verified ·
1 Parent(s): a3641a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -106
app.py CHANGED
@@ -1,128 +1,49 @@
1
- import gradio as gr
2
- from detect import SimpleOfflineAccentClassifier
3
  import yt_dlp
4
  import os
5
- import tempfile
6
- import logging
7
 
8
- # Logging ayarları
9
- logging.basicConfig(level=logging.DEBUG)
10
- logger = logging.getLogger(__name__)
11
 
12
- def download_youtube_audio(url):
 
 
 
 
 
13
  try:
14
- logger.debug(f"Downloading from URL: {url}")
15
-
16
- # Geçici dosya yolu oluştur
17
- temp_dir = tempfile.gettempdir()
18
- temp_file = os.path.join(temp_dir, 'temp_audio.wav')
19
 
20
- # Basit yt-dlp ayarları
21
  ydl_opts = {
22
  'format': 'bestaudio/best',
23
- 'outtmpl': temp_file.replace('.wav', ''),
24
- 'quiet': True,
25
- 'no_warnings': True,
26
- 'extract_flat': True,
27
- 'noplaylist': True,
28
- 'ignoreerrors': True,
29
  'postprocessors': [{
30
  'key': 'FFmpegExtractAudio',
31
  'preferredcodec': 'wav',
32
- }]
 
 
 
33
  }
34
 
35
- # İndirme işlemi
36
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
37
- logger.debug("Starting download...")
38
- info = ydl.extract_info(url, download=True)
39
- logger.debug(f"Download info: {info}")
40
-
41
- # Dosya adını düzelt
42
- if os.path.exists(temp_file.replace('.wav', '.webm')):
43
- os.rename(temp_file.replace('.wav', '.webm'), temp_file)
44
- elif os.path.exists(temp_file.replace('.wav', '.m4a')):
45
- os.rename(temp_file.replace('.wav', '.m4a'), temp_file)
46
-
47
- logger.debug(f"Download complete. File saved to: {temp_file}")
48
 
49
- if os.path.exists(temp_file):
50
- return temp_file
51
- else:
52
- logger.error("Downloaded file not found")
53
- return None
54
-
55
- except Exception as e:
56
- logger.exception(f"Download error: {str(e)}")
57
- return None
58
-
59
- def analyze_audio(audio_file, youtube_url):
60
- try:
61
- if youtube_url:
62
- logger.debug(f"Processing YouTube URL: {youtube_url}")
63
- audio_file = download_youtube_audio(youtube_url)
64
- if not audio_file:
65
- return "Failed to download YouTube audio. Please check the URL and try again."
66
-
67
- if not audio_file:
68
- return "Please upload an audio file or provide a YouTube URL."
69
 
70
- logger.debug(f"Processing audio file: {audio_file}")
71
- classifier = SimpleOfflineAccentClassifier()
72
- result = classifier.predict_accent(audio_file)
73
 
74
  if result is None:
75
- return "Audio file processing failed."
76
-
77
- output = f"Predicted Accent: {result['accent']}\n"
78
- output += f"Confidence Score: {result['confidence']:.2%}\n\n"
79
- output += "All Probabilities:\n"
80
-
81
- sorted_probs = sorted(
82
- result['all_probabilities'].items(),
83
- key=lambda x: x[1],
84
- reverse=True
85
- )
86
 
87
- for accent, prob in sorted_probs:
88
- bar = "█" * int(prob * 20)
89
- output += f"- {accent}: {prob:.2%} {bar}\n"
90
-
91
- return output
92
 
93
  except Exception as e:
94
- logger.exception(f"Analysis error: {str(e)}")
95
- return f"Error occurred: {str(e)}"
96
-
97
- # Create Gradio interface
98
- with gr.Blocks() as interface:
99
- gr.Markdown("# AI Accent Classifier")
100
-
101
- with gr.Row():
102
- with gr.Column():
103
- audio_input = gr.Audio(
104
- label="Upload Audio File",
105
- type="filepath"
106
- )
107
-
108
- youtube_url = gr.Textbox(
109
- label="Or enter YouTube URL",
110
- placeholder="https://www.youtube.com/watch?v=..."
111
- )
112
-
113
- classify_btn = gr.Button("Analyze Accent")
114
-
115
- with gr.Column():
116
- output_text = gr.Markdown(
117
- label="Analysis Results",
118
- value="Analysis results will appear here..."
119
- )
120
-
121
- classify_btn.click(
122
- fn=analyze_audio,
123
- inputs=[audio_input, youtube_url],
124
- outputs=output_text
125
- )
126
 
127
- # Launch the interface
128
- interface.launch(debug=True)
 
1
+ from flask import Flask, render_template, request, jsonify
 
2
  import yt_dlp
3
  import os
4
+ from detect import SimpleOfflineAccentClassifier
 
5
 
6
+ app = Flask(__name__)
7
+ classifier = SimpleOfflineAccentClassifier()
 
8
 
9
+ @app.route('/')
10
+ def home():
11
+ return render_template('index.html')
12
+
13
+ @app.route('/analyze', methods=['POST'])
14
+ def analyze():
15
  try:
16
+ video_url = request.form['url']
 
 
 
 
17
 
18
+ # YouTube'dan ses indir
19
  ydl_opts = {
20
  'format': 'bestaudio/best',
 
 
 
 
 
 
21
  'postprocessors': [{
22
  'key': 'FFmpegExtractAudio',
23
  'preferredcodec': 'wav',
24
+ }],
25
+ 'outtmpl': 'temp_audio',
26
+ 'quiet': True,
27
+ 'no_warnings': True
28
  }
29
 
 
30
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
31
+ ydl.download([video_url])
 
 
 
 
 
 
 
 
 
 
32
 
33
+ # Ses dosyasını analiz et
34
+ result = classifier.predict_accent('temp_audio.wav')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
 
36
+ # Geçici dosyayı temizle
37
+ if os.path.exists('temp_audio.wav'):
38
+ os.remove('temp_audio.wav')
39
 
40
  if result is None:
41
+ return jsonify({'error': 'voice analyze failed.'})
 
 
 
 
 
 
 
 
 
 
42
 
43
+ return jsonify(result)
 
 
 
 
44
 
45
  except Exception as e:
46
+ return jsonify({'error': str(e)})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
+ if __name__ == '__main__':
49
+ app.run(debug=True, port=5000)