MurderousCoder commited on
Commit
4f93fcb
·
verified ·
1 Parent(s): 5bbd65a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -115
app.py CHANGED
@@ -1,138 +1,64 @@
1
  import streamlit as st
2
- import pandas as pd
3
- import numpy as np
4
- import yt_dlp
5
  import os
6
  from pathlib import Path
7
- import json
8
 
9
- def save_cookies(cookie_string):
10
  """
11
- Save cookies to a file in Netscape format
12
  """
13
  try:
14
- cookie_file = "youtube.txt"
15
- with open(cookie_file, "w") as f:
16
- f.write(cookie_string)
17
- return cookie_file
18
- except Exception as e:
19
- st.error(f"Error saving cookies: {str(e)}")
20
- return None
21
-
22
- def download_youtube_music(url, cookie_string=None):
23
- """
24
- Download music from YouTube URL using provided cookies
25
- """
26
- try:
27
- # Create downloads directory if it doesn't exist
28
- download_dir = Path("downloads")
29
- download_dir.mkdir(exist_ok=True)
30
-
31
- # Base options
32
- ydl_opts = {
33
- 'format': 'bestaudio/best',
34
- 'postprocessors': [{
35
- 'key': 'FFmpegExtractAudio',
36
- 'preferredcodec': 'mp3',
37
- 'preferredquality': '320',
38
- }],
39
- 'outtmpl': str(download_dir / '%(title)s.%(ext)s'),
40
- 'verbose': True,
41
- 'progress_hooks': [lambda d: download_progress_hook(d)],
42
- }
43
-
44
- # Add cookies if provided
45
- if cookie_string:
46
- cookie_file = save_cookies(cookie_string)
47
- if cookie_file:
48
- ydl_opts['cookiefile'] = cookie_file
49
-
50
- # Show download starting message
51
- status = st.empty()
52
- status.info('Starting download...')
53
 
54
- # Download the audio
55
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
56
- info = ydl.extract_info(url, download=True)
57
- filename = ydl.prepare_filename(info).replace('.webm', '.mp3').replace('.m4a', '.mp3')
58
-
59
- # Show success message and download button
60
- status.success('Download completed!')
61
 
62
- # Create download button for the file
63
- with open(filename, 'rb') as file:
64
- st.download_button(
65
- label="Download MP3",
66
- data=file,
67
- file_name=os.path.basename(filename),
68
- mime='audio/mpeg'
69
- )
70
-
71
- # Clean up cookie file
72
- if cookie_string and os.path.exists("youtube.txt"):
73
- os.remove("youtube.txt")
74
 
 
75
  except Exception as e:
76
- st.error(f'An error occurred: {str(e)}')
77
- if "HTTP Error 429" in str(e):
78
- st.error("Too many requests. Please wait a few minutes and try again.")
79
 
80
- def download_progress_hook(d):
81
- """
82
- Display download progress in Streamlit
83
- """
84
- if d['status'] == 'downloading':
85
- try:
86
- progress = float(d['_percent_str'].replace('%',''))
87
- progress_bar = st.progress(0)
88
- progress_bar.progress(progress/100)
89
- except:
90
- pass
91
-
92
  def main():
93
  st.set_page_config(page_title="What's That Tongue?", layout="centered")
94
-
95
  st.title("What's That Tongue?")
96
 
97
- # Create a container for the input selection
98
- input_option = st.radio(
99
- "Select Input Method:",
100
- ("URL Input", "File Upload"),
101
- horizontal=True
102
  )
103
 
104
- # Display input fields based on the selected option
105
- if input_option == "URL Input":
106
- with st.expander("YouTube Cookie Settings (Required)"):
107
- st.markdown("""
108
- To get your YouTube cookies:
109
- 1. Go to YouTube and make sure you're logged in
110
- 2. Open Developer Tools (F12 or right-click > Inspect)
111
- 3. Go to Network tab
112
- 4. Visit any YouTube page
113
- 5. Find a request to youtube.com
114
- 6. In the request headers, find the 'cookie' header
115
- 7. Copy the entire cookie value
116
- """)
117
- cookie_string = st.text_area(
118
- "Paste your YouTube cookies here",
119
- help="Paste the entire cookie string from YouTube's request headers"
120
- )
121
 
122
- url = st.text_input("Enter URL", placeholder="Enter URL here...")
123
- if url and cookie_string:
124
- if not url.startswith(('http://', 'https://')):
125
- st.warning('Please enter a valid URL starting with http:// or https://')
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  else:
127
- st.write(f"You entered: {url}")
128
- download_youtube_music(url, cookie_string)
129
- elif url and not cookie_string:
130
- st.warning("Please provide YouTube cookies to download the video")
131
-
132
- elif input_option == "File Upload":
133
- uploaded_file = st.file_uploader("Upload a File", type=["txt", "mp3", "wav"])
134
- if uploaded_file:
135
- st.write(f"File uploaded: {uploaded_file.name}")
136
 
137
  if __name__ == "__main__":
138
  main()
 
1
  import streamlit as st
 
 
 
2
  import os
3
  from pathlib import Path
 
4
 
5
+ def save_uploaded_file(uploaded_file):
6
  """
7
+ Save the uploaded file to the uploads directory
8
  """
9
  try:
10
+ # Create uploads directory if it doesn't exist
11
+ upload_dir = Path("uploads")
12
+ upload_dir.mkdir(exist_ok=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ # Create file path
15
+ file_path = upload_dir / uploaded_file.name
 
 
 
 
 
16
 
17
+ # Save the file
18
+ with open(file_path, "wb") as f:
19
+ f.write(uploaded_file.getbuffer())
 
 
 
 
 
 
 
 
 
20
 
21
+ return True, file_path
22
  except Exception as e:
23
+ return False, str(e)
 
 
24
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  def main():
26
  st.set_page_config(page_title="What's That Tongue?", layout="centered")
 
27
  st.title("What's That Tongue?")
28
 
29
+ # Create a container for file upload
30
+ uploaded_file = st.file_uploader(
31
+ "Upload your audio file",
32
+ type=["mp3", "wav", "txt"],
33
+ help="Supported formats: MP3, WAV, TXT"
34
  )
35
 
36
+ if uploaded_file is not None:
37
+ # Show file details
38
+ st.write("File Details:")
39
+ st.write(f"- Name: {uploaded_file.name}")
40
+ st.write(f"- Size: {uploaded_file.size / 1024:.2f} KB")
41
+ st.write(f"- Type: {uploaded_file.type}")
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ # Create upload button
44
+ if st.button("Start Upload", type="primary"):
45
+ # Show progress
46
+ progress_text = "Upload in progress. Please wait..."
47
+ progress_bar = st.progress(0)
48
+
49
+ # Process upload
50
+ with st.spinner(progress_text):
51
+ success, result = save_uploaded_file(uploaded_file)
52
+ progress_bar.progress(100)
53
+
54
+ # Show result
55
+ if success:
56
+ st.success(f"File successfully uploaded to: {result}")
57
+ # Optional: Show a preview or additional options
58
+ if uploaded_file.type.startswith('audio/'):
59
+ st.audio(result)
60
  else:
61
+ st.error(f"Error uploading file: {result}")
 
 
 
 
 
 
 
 
62
 
63
  if __name__ == "__main__":
64
  main()