developer28 commited on
Commit
3d3b497
Β·
verified Β·
1 Parent(s): 633443e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -32
app.py CHANGED
@@ -1,5 +1,3 @@
1
- # βœ… Stock Recommendation Extractor from YouTube Audio (with full error reporting)
2
-
3
  import os
4
  import gradio as gr
5
  import tempfile
@@ -15,8 +13,7 @@ try:
15
  except:
16
  WHISPER_AVAILABLE = False
17
 
18
- # βœ… Download audio using working logic
19
-
20
  def download_audio(url, cookies_path=None):
21
  try:
22
  temp_dir = tempfile.mkdtemp()
@@ -54,7 +51,6 @@ def download_audio(url, cookies_path=None):
54
  return None, f"❌ Download error: {str(e)}"
55
 
56
  # βœ… Transcribe audio using Whisper
57
-
58
  def transcribe_audio(path):
59
  if not WHISPER_AVAILABLE:
60
  return "❌ Whisper not available. Please install openai-whisper."
@@ -66,8 +62,7 @@ def transcribe_audio(path):
66
  traceback.print_exc()
67
  return f"❌ Transcription failed: {str(e)}"
68
 
69
- # βœ… Extract stock-related information from transcript
70
-
71
  def extract_stock_info(text):
72
  try:
73
  companies = re.findall(r'\b[A-Z][a-z]+(?: [A-Z][a-z]+)*\b', text)
@@ -85,7 +80,6 @@ def extract_stock_info(text):
85
  if actions:
86
  result += f"πŸ“Š Actions: {', '.join(set(actions[:10]))}\n"
87
 
88
- # Highlight potential recommendations
89
  recommendations = []
90
  for line in text.split("."):
91
  if any(word in line.lower() for word in ['buy', 'sell', 'target', 'hold']):
@@ -105,30 +99,23 @@ def extract_stock_info(text):
105
  return f"❌ Stock info extraction failed: {str(e)}"
106
 
107
  # βœ… Save uploaded cookies.txt
108
-
109
  def save_cookies(file):
110
  if file is None:
111
  return None
112
 
113
  temp_path = tempfile.mktemp(suffix=".txt")
114
-
115
  try:
116
- # Handle both file-like object and NamedString
117
- if hasattr(file, "read"): # File-like
118
  with open(temp_path, "wb") as f:
119
  f.write(file.read())
120
- else: # NamedString (str path)
121
  shutil.copy(file, temp_path)
122
-
123
  return temp_path
124
-
125
  except Exception as e:
126
  print(f"❌ Failed to handle cookies.txt: {e}")
127
  return None
128
 
129
-
130
- # βœ… Full pipeline with error traceback
131
-
132
  def run_pipeline(url, cookies_file):
133
  try:
134
  if not WHISPER_AVAILABLE:
@@ -153,23 +140,52 @@ def run_pipeline(url, cookies_file):
153
  print(tb)
154
  return f"❌ Unhandled Error:\n{tb}", ""
155
 
156
- # βœ… Gradio Interface
157
- with gr.Blocks(title="Stock Insights from YouTube Audio") as demo:
158
- gr.Markdown("""
159
- # 🎧 Extract Stock Recommendations from YouTube Audio
160
- This app downloads the audio from a YouTube video, transcribes it with Whisper,
161
- and extracts stock trading recommendations, sentiments, and symbols.
162
- """)
 
 
 
 
 
 
 
 
 
 
 
163
 
164
- with gr.Row():
165
- url_input = gr.Textbox(label="πŸŽ₯ YouTube Video URL")
166
- cookie_input = gr.File(label="cookies.txt (optional)", file_types=[".txt"])
 
167
 
168
- run_btn = gr.Button("πŸš€ Extract Stock Info")
169
- status_output = gr.Textbox(label="Status")
170
- result_output = gr.Textbox(label="Stock Info", lines=12)
 
 
 
171
 
172
- run_btn.click(fn=run_pipeline, inputs=[url_input, cookie_input], outputs=[status_output, result_output])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
  if __name__ == "__main__":
175
  demo.launch(debug=True)
 
 
 
1
  import os
2
  import gradio as gr
3
  import tempfile
 
13
  except:
14
  WHISPER_AVAILABLE = False
15
 
16
+ # βœ… Download audio from YouTube
 
17
  def download_audio(url, cookies_path=None):
18
  try:
19
  temp_dir = tempfile.mkdtemp()
 
51
  return None, f"❌ Download error: {str(e)}"
52
 
53
  # βœ… Transcribe audio using Whisper
 
54
  def transcribe_audio(path):
55
  if not WHISPER_AVAILABLE:
56
  return "❌ Whisper not available. Please install openai-whisper."
 
62
  traceback.print_exc()
63
  return f"❌ Transcription failed: {str(e)}"
64
 
65
+ # βœ… Extract stock-related information
 
66
  def extract_stock_info(text):
67
  try:
68
  companies = re.findall(r'\b[A-Z][a-z]+(?: [A-Z][a-z]+)*\b', text)
 
80
  if actions:
81
  result += f"πŸ“Š Actions: {', '.join(set(actions[:10]))}\n"
82
 
 
83
  recommendations = []
84
  for line in text.split("."):
85
  if any(word in line.lower() for word in ['buy', 'sell', 'target', 'hold']):
 
99
  return f"❌ Stock info extraction failed: {str(e)}"
100
 
101
  # βœ… Save uploaded cookies.txt
 
102
  def save_cookies(file):
103
  if file is None:
104
  return None
105
 
106
  temp_path = tempfile.mktemp(suffix=".txt")
 
107
  try:
108
+ if hasattr(file, "read"):
 
109
  with open(temp_path, "wb") as f:
110
  f.write(file.read())
111
+ else:
112
  shutil.copy(file, temp_path)
 
113
  return temp_path
 
114
  except Exception as e:
115
  print(f"❌ Failed to handle cookies.txt: {e}")
116
  return None
117
 
118
+ # βœ… YouTube pipeline
 
 
119
  def run_pipeline(url, cookies_file):
120
  try:
121
  if not WHISPER_AVAILABLE:
 
140
  print(tb)
141
  return f"❌ Unhandled Error:\n{tb}", ""
142
 
143
+ # βœ… Audio file upload pipeline
144
+ def run_pipeline_audio(audio_file):
145
+ try:
146
+ if not WHISPER_AVAILABLE:
147
+ return "❌ Whisper is not installed. Run: pip install openai-whisper", ""
148
+ if audio_file is None:
149
+ return "❌ No audio file uploaded", ""
150
+
151
+ temp_audio_path = tempfile.mktemp(suffix=os.path.splitext(audio_file.name)[-1])
152
+ with open(temp_audio_path, "wb") as f:
153
+ f.write(audio_file.read())
154
+
155
+ transcript = transcribe_audio(temp_audio_path)
156
+ if transcript.startswith("❌"):
157
+ return transcript, ""
158
+
159
+ stock_info = extract_stock_info(transcript)
160
+ return "βœ… Complete", stock_info
161
 
162
+ except Exception as e:
163
+ tb = traceback.format_exc()
164
+ print(tb)
165
+ return f"❌ Unhandled Error:\n{tb}", ""
166
 
167
+ # βœ… Gradio UI
168
+ with gr.Blocks(title="Stock Insights from YouTube or Audio") as demo:
169
+ gr.Markdown("""
170
+ # 🎧 Extract Stock Recommendations from YouTube or Uploaded Audio
171
+ Upload a YouTube URL or an audio file. We'll transcribe it and extract stock-related insights!
172
+ """)
173
 
174
+ with gr.Tab("πŸ“Ί From YouTube Video"):
175
+ with gr.Row():
176
+ url_input = gr.Textbox(label="πŸŽ₯ YouTube Video URL")
177
+ cookie_input = gr.File(label="cookies.txt (optional)", file_types=[".txt"])
178
+ yt_run_btn = gr.Button("πŸš€ Extract from YouTube")
179
+ yt_status = gr.Textbox(label="Status")
180
+ yt_result = gr.Textbox(label="Stock Info", lines=12)
181
+ yt_run_btn.click(fn=run_pipeline, inputs=[url_input, cookie_input], outputs=[yt_status, yt_result])
182
+
183
+ with gr.Tab("🎡 From Uploaded Audio"):
184
+ audio_input = gr.File(label="Upload Audio File", file_types=[".mp3", ".wav", ".m4a", ".webm"])
185
+ audio_run_btn = gr.Button("πŸš€ Extract from Audio")
186
+ audio_status = gr.Textbox(label="Status")
187
+ audio_result = gr.Textbox(label="Stock Info", lines=12)
188
+ audio_run_btn.click(fn=run_pipeline_audio, inputs=[audio_input], outputs=[audio_status, audio_result])
189
 
190
  if __name__ == "__main__":
191
  demo.launch(debug=True)