Update app.py
Browse files
app.py
CHANGED
|
@@ -263,6 +263,7 @@ 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 |
idx = conversation_fields.index(current_step)
|
| 267 |
if idx < len(conversation_fields) - 1:
|
| 268 |
current_step = conversation_fields[idx + 1]
|
|
@@ -298,14 +299,17 @@ def stream_to_youtube(input_url, quality_settings, video_codec, audio_codec, out
|
|
| 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,12 +319,16 @@ def stream_to_youtube(input_url, quality_settings, video_codec, audio_codec, out
|
|
| 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,6 +336,7 @@ def stream_to_youtube(input_url, quality_settings, video_codec, audio_codec, out
|
|
| 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,12 +361,17 @@ def stream_to_youtube(input_url, quality_settings, video_codec, audio_codec, out
|
|
| 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,6 +379,7 @@ def stream_to_youtube(input_url, quality_settings, video_codec, audio_codec, out
|
|
| 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,6 +393,7 @@ def start_streaming(chat_id):
|
|
| 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(
|
|
@@ -472,9 +488,11 @@ async def telegram_webhook(request: Request):
|
|
| 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,10 +511,13 @@ async def telegram_webhook(request: Request):
|
|
| 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,12 +530,16 @@ async def telegram_webhook(request: Request):
|
|
| 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"}
|
|
|
|
| 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 |
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 |
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 |
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 |
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 |
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 |
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(
|
|
|
|
| 488 |
update = await request.json()
|
| 489 |
logging.debug(f"Received update: {update}")
|
| 490 |
|
| 491 |
+
# Process messages from users
|
| 492 |
if "message" in update:
|
| 493 |
chat_id = update["message"]["chat"]["id"]
|
| 494 |
text = update["message"].get("text", "").strip()
|
| 495 |
+
|
| 496 |
if text.startswith("/setting"):
|
| 497 |
return handle_setting(chat_id)
|
| 498 |
elif text.startswith("/start"):
|
|
|
|
| 511 |
return stream_status(chat_id)
|
| 512 |
else:
|
| 513 |
return handle_conversation(chat_id, text)
|
| 514 |
+
|
| 515 |
+
# Process inline keyboard callback queries
|
| 516 |
elif "callback_query" in update:
|
| 517 |
callback_data = update["callback_query"]["data"]
|
| 518 |
chat_id = update["callback_query"]["message"]["chat"]["id"]
|
| 519 |
message_id = update["callback_query"]["message"]["message_id"]
|
| 520 |
+
|
| 521 |
if callback_data == "pause":
|
| 522 |
response = pause_stream(chat_id)
|
| 523 |
elif callback_data == "resume":
|
|
|
|
| 530 |
response = start_streaming(chat_id)
|
| 531 |
else:
|
| 532 |
response = send_guide_message(chat_id, "❓ Unknown callback command.")
|
| 533 |
+
|
| 534 |
+
# For streaming control callbacks, update the message with the latest live logs
|
| 535 |
if callback_data in ["pause", "resume", "abort", "status", "start_stream"]:
|
| 536 |
response["method"] = "editMessageText"
|
| 537 |
response["message_id"] = message_id
|
| 538 |
response["text"] = compose_streaming_message()
|
| 539 |
response["parse_mode"] = "HTML"
|
| 540 |
+
# Always include the inline keyboard if streaming is active.
|
| 541 |
if streaming_state in ["streaming", "paused"]:
|
| 542 |
response["reply_markup"] = get_inline_keyboard_for_stream()
|
| 543 |
return response
|
| 544 |
+
|
| 545 |
return {"status": "ok"}
|