AstraOS commited on
Commit
c1241b9
·
verified ·
1 Parent(s): 3850296

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -26
app.py CHANGED
@@ -263,7 +263,6 @@ def handle_conversation(chat_id, text):
263
  else:
264
  user_inputs[current_step] = text.strip()
265
  logging.info(f"Received {current_step}: {text.strip()}")
266
-
267
  idx = conversation_fields.index(current_step)
268
  if idx < len(conversation_fields) - 1:
269
  current_step = conversation_fields[idx + 1]
@@ -299,17 +298,14 @@ def stream_to_youtube(input_url, quality_settings, video_codec, audio_codec, out
299
  try:
300
  streaming_state = "streaming"
301
  reset_statistics()
302
-
303
  input_stream = av.open(input_url)
304
  output_stream = av.open(output_url, mode='w', format='flv')
305
-
306
  # Configure video stream
307
  video_stream = output_stream.add_stream(video_codec, rate=30)
308
  video_stream.width = input_stream.streams.video[0].width
309
  video_stream.height = input_stream.streams.video[0].height
310
  video_stream.pix_fmt = input_stream.streams.video[0].format.name
311
  video_stream.codec_context.options.update({'g': '30'})
312
-
313
  if quality_settings.lower() == "high":
314
  video_stream.bit_rate = 3000000
315
  video_stream.bit_rate_tolerance = 1000000
@@ -319,16 +315,12 @@ def stream_to_youtube(input_url, quality_settings, video_codec, audio_codec, out
319
  elif quality_settings.lower() == "low":
320
  video_stream.bit_rate = 800000
321
  video_stream.bit_rate_tolerance = 200000
322
-
323
  # Configure audio stream
324
  audio_stream_in = input_stream.streams.audio[0]
325
  out_audio_stream = output_stream.add_stream(audio_codec, rate=audio_stream_in.rate)
326
  out_audio_stream.layout = "stereo"
327
-
328
  video_stream.codec_context.time_base = fractions.Fraction(1, video_stream.rate)
329
-
330
  logging.info("Streaming started successfully.")
331
-
332
  # Start the live log updater in a background thread if not already running.
333
  global live_log_thread
334
  if live_log_thread is None or not live_log_thread.is_alive():
@@ -336,7 +328,6 @@ def stream_to_youtube(input_url, quality_settings, video_codec, audio_codec, out
336
  live_log_thread.daemon = True
337
  live_log_thread.start()
338
  logging.info("Live log updater thread started.")
339
-
340
  # Stream loop: process packets until state changes
341
  while streaming_state in ["streaming", "paused"]:
342
  for packet in input_stream.demux():
@@ -361,17 +352,12 @@ def stream_to_youtube(input_url, quality_settings, video_codec, audio_codec, out
361
  output_stream.mux(out_packet)
362
  if hasattr(out_packet, "size"):
363
  bytes_sent += out_packet.size
364
-
365
- # Flush remaining packets
366
  for out_packet in video_stream.encode():
367
  output_stream.mux(out_packet)
368
  for out_packet in out_audio_stream.encode():
369
  output_stream.mux(out_packet)
370
-
371
  if streaming_state == "paused":
372
  time.sleep(1)
373
-
374
- # Clean up resources
375
  try:
376
  video_stream.close()
377
  out_audio_stream.close()
@@ -379,7 +365,6 @@ def stream_to_youtube(input_url, quality_settings, video_codec, audio_codec, out
379
  input_stream.close()
380
  except Exception as cleanup_error:
381
  logging.error(f"Error during cleanup: {cleanup_error}")
382
-
383
  logging.info("Streaming complete, resources cleaned up.")
384
  streaming_state = "idle"
385
  except Exception as e:
@@ -393,7 +378,6 @@ def start_streaming(chat_id):
393
  valid, msg = validate_inputs()
394
  if not valid:
395
  return send_guide_message(chat_id, f"Validation error: {msg}")
396
-
397
  stream_chat_id = chat_id
398
  try:
399
  stream_thread = threading.Thread(
@@ -410,7 +394,6 @@ def start_streaming(chat_id):
410
  stream_thread.daemon = True
411
  stream_thread.start()
412
  logging.info("Streaming thread started.")
413
- # Immediately return a message that includes the live log display via compose_streaming_message()
414
  return {
415
  "method": "sendMessage",
416
  "chat_id": chat_id,
@@ -489,11 +472,9 @@ async def telegram_webhook(request: Request):
489
  update = await request.json()
490
  logging.debug(f"Received update: {update}")
491
 
492
- # Process messages from users
493
  if "message" in update:
494
  chat_id = update["message"]["chat"]["id"]
495
  text = update["message"].get("text", "").strip()
496
-
497
  if text.startswith("/setting"):
498
  return handle_setting(chat_id)
499
  elif text.startswith("/start"):
@@ -512,13 +493,10 @@ async def telegram_webhook(request: Request):
512
  return stream_status(chat_id)
513
  else:
514
  return handle_conversation(chat_id, text)
515
-
516
- # Process inline keyboard callback queries
517
  elif "callback_query" in update:
518
  callback_data = update["callback_query"]["data"]
519
  chat_id = update["callback_query"]["message"]["chat"]["id"]
520
  message_id = update["callback_query"]["message"]["message_id"]
521
-
522
  if callback_data == "pause":
523
  response = pause_stream(chat_id)
524
  elif callback_data == "resume":
@@ -531,16 +509,12 @@ async def telegram_webhook(request: Request):
531
  response = start_streaming(chat_id)
532
  else:
533
  response = send_guide_message(chat_id, "❓ Unknown callback command.")
534
-
535
- # For streaming control callbacks, update the message with the latest live logs
536
  if callback_data in ["pause", "resume", "abort", "status", "start_stream"]:
537
  response["method"] = "editMessageText"
538
  response["message_id"] = message_id
539
  response["text"] = compose_streaming_message()
540
  response["parse_mode"] = "HTML"
541
- # Always include the inline keyboard if streaming is active.
542
  if streaming_state in ["streaming", "paused"]:
543
  response["reply_markup"] = get_inline_keyboard_for_stream()
544
  return response
545
-
546
  return {"status": "ok"}
 
263
  else:
264
  user_inputs[current_step] = text.strip()
265
  logging.info(f"Received {current_step}: {text.strip()}")
 
266
  idx = conversation_fields.index(current_step)
267
  if idx < len(conversation_fields) - 1:
268
  current_step = conversation_fields[idx + 1]
 
298
  try:
299
  streaming_state = "streaming"
300
  reset_statistics()
 
301
  input_stream = av.open(input_url)
302
  output_stream = av.open(output_url, mode='w', format='flv')
 
303
  # Configure video stream
304
  video_stream = output_stream.add_stream(video_codec, rate=30)
305
  video_stream.width = input_stream.streams.video[0].width
306
  video_stream.height = input_stream.streams.video[0].height
307
  video_stream.pix_fmt = input_stream.streams.video[0].format.name
308
  video_stream.codec_context.options.update({'g': '30'})
 
309
  if quality_settings.lower() == "high":
310
  video_stream.bit_rate = 3000000
311
  video_stream.bit_rate_tolerance = 1000000
 
315
  elif quality_settings.lower() == "low":
316
  video_stream.bit_rate = 800000
317
  video_stream.bit_rate_tolerance = 200000
 
318
  # Configure audio stream
319
  audio_stream_in = input_stream.streams.audio[0]
320
  out_audio_stream = output_stream.add_stream(audio_codec, rate=audio_stream_in.rate)
321
  out_audio_stream.layout = "stereo"
 
322
  video_stream.codec_context.time_base = fractions.Fraction(1, video_stream.rate)
 
323
  logging.info("Streaming started successfully.")
 
324
  # Start the live log updater in a background thread if not already running.
325
  global live_log_thread
326
  if live_log_thread is None or not live_log_thread.is_alive():
 
328
  live_log_thread.daemon = True
329
  live_log_thread.start()
330
  logging.info("Live log updater thread started.")
 
331
  # Stream loop: process packets until state changes
332
  while streaming_state in ["streaming", "paused"]:
333
  for packet in input_stream.demux():
 
352
  output_stream.mux(out_packet)
353
  if hasattr(out_packet, "size"):
354
  bytes_sent += out_packet.size
 
 
355
  for out_packet in video_stream.encode():
356
  output_stream.mux(out_packet)
357
  for out_packet in out_audio_stream.encode():
358
  output_stream.mux(out_packet)
 
359
  if streaming_state == "paused":
360
  time.sleep(1)
 
 
361
  try:
362
  video_stream.close()
363
  out_audio_stream.close()
 
365
  input_stream.close()
366
  except Exception as cleanup_error:
367
  logging.error(f"Error during cleanup: {cleanup_error}")
 
368
  logging.info("Streaming complete, resources cleaned up.")
369
  streaming_state = "idle"
370
  except Exception as e:
 
378
  valid, msg = validate_inputs()
379
  if not valid:
380
  return send_guide_message(chat_id, f"Validation error: {msg}")
 
381
  stream_chat_id = chat_id
382
  try:
383
  stream_thread = threading.Thread(
 
394
  stream_thread.daemon = True
395
  stream_thread.start()
396
  logging.info("Streaming thread started.")
 
397
  return {
398
  "method": "sendMessage",
399
  "chat_id": chat_id,
 
472
  update = await request.json()
473
  logging.debug(f"Received update: {update}")
474
 
 
475
  if "message" in update:
476
  chat_id = update["message"]["chat"]["id"]
477
  text = update["message"].get("text", "").strip()
 
478
  if text.startswith("/setting"):
479
  return handle_setting(chat_id)
480
  elif text.startswith("/start"):
 
493
  return stream_status(chat_id)
494
  else:
495
  return handle_conversation(chat_id, text)
 
 
496
  elif "callback_query" in update:
497
  callback_data = update["callback_query"]["data"]
498
  chat_id = update["callback_query"]["message"]["chat"]["id"]
499
  message_id = update["callback_query"]["message"]["message_id"]
 
500
  if callback_data == "pause":
501
  response = pause_stream(chat_id)
502
  elif callback_data == "resume":
 
509
  response = start_streaming(chat_id)
510
  else:
511
  response = send_guide_message(chat_id, "❓ Unknown callback command.")
 
 
512
  if callback_data in ["pause", "resume", "abort", "status", "start_stream"]:
513
  response["method"] = "editMessageText"
514
  response["message_id"] = message_id
515
  response["text"] = compose_streaming_message()
516
  response["parse_mode"] = "HTML"
 
517
  if streaming_state in ["streaming", "paused"]:
518
  response["reply_markup"] = get_inline_keyboard_for_stream()
519
  return response
 
520
  return {"status": "ok"}