Spaces:
Running
Running
fix
Browse files
main.py
CHANGED
@@ -1,858 +1,879 @@
|
|
1 |
-
# main.py
|
2 |
-
import os
|
3 |
-
import re
|
4 |
-
import logging
|
5 |
-
import asyncio
|
6 |
-
import json
|
7 |
-
from flask import Flask, request, Response # For web server
|
8 |
-
|
9 |
-
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
|
10 |
-
from telegram.ext import (
|
11 |
-
Application,
|
12 |
-
CommandHandler,
|
13 |
-
MessageHandler,
|
14 |
-
filters,
|
15 |
-
ContextTypes,
|
16 |
-
CallbackQueryHandler
|
17 |
-
)
|
18 |
-
from telegram.constants import ParseMode # Import ParseMode explicitly
|
19 |
-
|
20 |
-
# Import specific libraries (Ensure these are covered in requirements.txt)
|
21 |
-
from youtube_transcript_api import YouTubeTranscriptApi
|
22 |
-
import requests
|
23 |
-
from bs4 import BeautifulSoup
|
24 |
-
# Only import ApifyClient if you might use it (i.e., have the secret)
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
#
|
31 |
-
|
32 |
-
nest_asyncio
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
#
|
42 |
-
logging.
|
43 |
-
|
44 |
-
|
45 |
-
)
|
46 |
-
|
47 |
-
logging.getLogger("
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
logger
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
logger.
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
#
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
#
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
#
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
"
|
160 |
-
|
161 |
-
|
162 |
-
"
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
|
215 |
-
|
216 |
-
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
|
222 |
-
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
)
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
|
251 |
-
|
252 |
-
|
253 |
-
|
254 |
-
|
255 |
-
|
256 |
-
|
257 |
-
|
258 |
-
|
259 |
-
|
260 |
-
|
261 |
-
|
262 |
-
|
263 |
-
logger.
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
-
|
269 |
-
|
270 |
-
|
271 |
-
|
272 |
-
|
273 |
-
|
274 |
-
|
275 |
-
|
276 |
-
|
277 |
-
|
278 |
-
|
279 |
-
#
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
|
295 |
-
|
296 |
-
|
297 |
-
|
298 |
-
|
299 |
-
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
350 |
-
#
|
351 |
-
|
352 |
-
|
353 |
-
|
354 |
-
|
355 |
-
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
|
361 |
-
|
362 |
-
|
363 |
-
|
364 |
-
|
365 |
-
|
366 |
-
|
367 |
-
|
368 |
-
|
369 |
-
"
|
370 |
-
|
371 |
-
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
-
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
|
399 |
-
|
400 |
-
|
401 |
-
|
402 |
-
|
403 |
-
|
404 |
-
|
405 |
-
|
406 |
-
|
407 |
-
|
408 |
-
|
409 |
-
|
410 |
-
|
411 |
-
|
412 |
-
|
413 |
-
|
414 |
-
|
415 |
-
|
416 |
-
|
417 |
-
|
418 |
-
|
419 |
-
|
420 |
-
|
421 |
-
|
422 |
-
|
423 |
-
|
424 |
-
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
-
|
438 |
-
|
439 |
-
|
440 |
-
|
441 |
-
|
442 |
-
|
443 |
-
|
444 |
-
|
445 |
-
|
446 |
-
|
447 |
-
|
448 |
-
|
449 |
-
|
450 |
-
|
451 |
-
|
452 |
-
|
453 |
-
|
454 |
-
|
455 |
-
|
456 |
-
|
457 |
-
|
458 |
-
|
459 |
-
|
460 |
-
|
461 |
-
|
462 |
-
|
463 |
-
|
464 |
-
|
465 |
-
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
|
470 |
-
|
471 |
-
|
472 |
-
|
473 |
-
|
474 |
-
|
475 |
-
|
476 |
-
|
477 |
-
|
478 |
-
|
479 |
-
|
480 |
-
|
481 |
-
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
|
496 |
-
|
497 |
-
|
498 |
-
|
499 |
-
|
500 |
-
|
501 |
-
|
502 |
-
|
503 |
-
|
504 |
-
|
505 |
-
|
506 |
-
|
507 |
-
|
508 |
-
|
509 |
-
|
510 |
-
|
511 |
-
|
512 |
-
|
513 |
-
|
514 |
-
|
515 |
-
|
516 |
-
|
517 |
-
|
518 |
-
|
519 |
-
|
520 |
-
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
|
525 |
-
|
526 |
-
|
527 |
-
|
528 |
-
|
529 |
-
|
530 |
-
|
531 |
-
|
532 |
-
|
533 |
-
|
534 |
-
|
535 |
-
|
536 |
-
#
|
537 |
-
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
|
545 |
-
"
|
546 |
-
|
547 |
-
|
548 |
-
|
549 |
-
|
550 |
-
|
551 |
-
|
552 |
-
|
553 |
-
|
554 |
-
|
555 |
-
|
556 |
-
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
569 |
-
|
570 |
-
logger.info(f"User {
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
|
576 |
-
|
577 |
-
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
-
|
592 |
-
|
593 |
-
|
594 |
-
|
595 |
-
|
596 |
-
|
597 |
-
|
598 |
-
|
599 |
-
|
600 |
-
|
601 |
-
|
602 |
-
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
|
607 |
-
|
608 |
-
|
609 |
-
|
610 |
-
|
611 |
-
|
612 |
-
|
613 |
-
|
614 |
-
|
615 |
-
|
616 |
-
|
617 |
-
|
618 |
-
|
619 |
-
|
620 |
-
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
|
633 |
-
|
634 |
-
|
635 |
-
|
636 |
-
|
637 |
-
|
638 |
-
|
639 |
-
|
640 |
-
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
|
652 |
-
|
653 |
-
|
654 |
-
|
655 |
-
|
656 |
-
|
657 |
-
|
658 |
-
|
659 |
-
|
660 |
-
|
661 |
-
|
662 |
-
|
663 |
-
|
664 |
-
|
665 |
-
|
666 |
-
|
667 |
-
|
668 |
-
|
669 |
-
|
670 |
-
|
671 |
-
|
672 |
-
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
|
677 |
-
|
678 |
-
|
679 |
-
|
680 |
-
|
681 |
-
|
682 |
-
|
683 |
-
|
684 |
-
|
685 |
-
|
686 |
-
|
687 |
-
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
|
692 |
-
|
693 |
-
|
694 |
-
|
695 |
-
|
696 |
-
|
697 |
-
|
698 |
-
|
699 |
-
|
700 |
-
|
701 |
-
|
702 |
-
|
703 |
-
|
704 |
-
#
|
705 |
-
|
706 |
-
|
707 |
-
|
708 |
-
|
709 |
-
|
710 |
-
|
711 |
-
|
712 |
-
|
713 |
-
|
714 |
-
|
715 |
-
|
716 |
-
|
717 |
-
|
718 |
-
|
719 |
-
|
720 |
-
|
721 |
-
|
722 |
-
|
723 |
-
|
724 |
-
|
725 |
-
|
726 |
-
|
727 |
-
|
728 |
-
|
729 |
-
|
730 |
-
|
731 |
-
|
732 |
-
|
733 |
-
|
734 |
-
|
735 |
-
|
736 |
-
|
737 |
-
|
738 |
-
|
739 |
-
|
740 |
-
|
741 |
-
|
742 |
-
|
743 |
-
|
744 |
-
|
745 |
-
|
746 |
-
|
747 |
-
|
748 |
-
|
749 |
-
|
750 |
-
|
751 |
-
|
752 |
-
|
753 |
-
|
754 |
-
|
755 |
-
|
756 |
-
|
757 |
-
|
758 |
-
|
759 |
-
|
760 |
-
|
761 |
-
|
762 |
-
|
763 |
-
|
764 |
-
|
765 |
-
|
766 |
-
|
767 |
-
|
768 |
-
|
769 |
-
|
770 |
-
|
771 |
-
|
772 |
-
|
773 |
-
|
774 |
-
|
775 |
-
|
776 |
-
|
777 |
-
|
778 |
-
|
779 |
-
|
780 |
-
|
781 |
-
|
782 |
-
|
783 |
-
|
784 |
-
|
785 |
-
|
786 |
-
#
|
787 |
-
|
788 |
-
|
789 |
-
|
790 |
-
|
791 |
-
#
|
792 |
-
|
793 |
-
|
794 |
-
|
795 |
-
|
796 |
-
|
797 |
-
|
798 |
-
|
799 |
-
|
800 |
-
|
801 |
-
#
|
802 |
-
|
803 |
-
|
804 |
-
|
805 |
-
|
806 |
-
|
807 |
-
|
808 |
-
|
809 |
-
|
810 |
-
|
811 |
-
|
812 |
-
|
813 |
-
|
814 |
-
|
815 |
-
|
816 |
-
|
817 |
-
|
818 |
-
|
819 |
-
|
820 |
-
|
821 |
-
|
822 |
-
|
823 |
-
|
824 |
-
|
825 |
-
|
826 |
-
|
827 |
-
|
828 |
-
|
829 |
-
|
830 |
-
|
831 |
-
|
832 |
-
|
833 |
-
|
834 |
-
|
835 |
-
|
836 |
-
|
837 |
-
|
838 |
-
|
839 |
-
|
840 |
-
|
841 |
-
|
842 |
-
|
843 |
-
|
844 |
-
|
845 |
-
#
|
846 |
-
|
847 |
-
|
848 |
-
|
849 |
-
|
850 |
-
|
851 |
-
|
852 |
-
|
853 |
-
|
854 |
-
|
855 |
-
|
856 |
-
|
857 |
-
|
858 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# main.py (Revised for Hugging Face - Corrected Logs & Added Debugging)
|
2 |
+
import os
|
3 |
+
import re
|
4 |
+
import logging
|
5 |
+
import asyncio
|
6 |
+
import json
|
7 |
+
from flask import Flask, request, Response # For web server
|
8 |
+
|
9 |
+
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
|
10 |
+
from telegram.ext import (
|
11 |
+
Application,
|
12 |
+
CommandHandler,
|
13 |
+
MessageHandler,
|
14 |
+
filters,
|
15 |
+
ContextTypes,
|
16 |
+
CallbackQueryHandler
|
17 |
+
)
|
18 |
+
from telegram.constants import ParseMode # Import ParseMode explicitly
|
19 |
+
|
20 |
+
# Import specific libraries (Ensure these are covered in requirements.txt)
|
21 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
22 |
+
import requests
|
23 |
+
from bs4 import BeautifulSoup
|
24 |
+
# Only import ApifyClient if you might use it (i.e., have the secret)
|
25 |
+
# Check environment variable existence *before* conditional import
|
26 |
+
_apify_token_exists = bool(os.environ.get('APIFY_API_TOKEN'))
|
27 |
+
if _apify_token_exists:
|
28 |
+
from apify_client import ApifyClient
|
29 |
+
else:
|
30 |
+
ApifyClient = None # Define it as None if not used, to avoid errors later
|
31 |
+
|
32 |
+
# Apply nest_asyncio early, can help prevent event loop conflicts in web frameworks
|
33 |
+
import nest_asyncio
|
34 |
+
nest_asyncio.apply()
|
35 |
+
|
36 |
+
# --- Logging Setup ---
|
37 |
+
logging.basicConfig(
|
38 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
39 |
+
level=logging.INFO # Set to INFO to see processing steps, DEBUG for finer detail
|
40 |
+
)
|
41 |
+
# Reduce noise from libraries
|
42 |
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
43 |
+
if ApifyClient: # Only set level if imported
|
44 |
+
logging.getLogger("apify_client").setLevel(logging.WARNING)
|
45 |
+
logging.getLogger("telegram.ext").setLevel(logging.INFO)
|
46 |
+
logging.getLogger('telegram.bot').setLevel(logging.INFO)
|
47 |
+
logging.getLogger("urllib3").setLevel(logging.INFO) # From requests
|
48 |
+
logging.getLogger('gunicorn.error').setLevel(logging.INFO) # Gunicorn logs
|
49 |
+
logger = logging.getLogger(__name__)
|
50 |
+
logger.info("Logging configured.")
|
51 |
+
|
52 |
+
# --- Environment Variable Loading & Debugging ---
|
53 |
+
logger.info("Attempting to load secrets from environment variables...")
|
54 |
+
|
55 |
+
def get_secret(secret_name):
|
56 |
+
"""Reads secret and logs the attempt and result."""
|
57 |
+
logger.debug(f"Attempting to read secret: {secret_name}")
|
58 |
+
value = os.environ.get(secret_name)
|
59 |
+
if value:
|
60 |
+
logger.info(f"Secret '{secret_name}': Found (Value length: {len(value)})") # Log length, not value itself
|
61 |
+
else:
|
62 |
+
logger.warning(f"Secret '{secret_name}': Not Found")
|
63 |
+
return value
|
64 |
+
|
65 |
+
TELEGRAM_TOKEN = get_secret('TELEGRAM_TOKEN')
|
66 |
+
OPENROUTER_API_KEY = get_secret('OPENROUTER_API_KEY')
|
67 |
+
URLTOTEXT_API_KEY = get_secret('URLTOTEXT_API_KEY') # Will be None if not set in Secrets
|
68 |
+
SUPADATA_API_KEY = get_secret('SUPADATA_API_KEY') # Will be None if not set in Secrets
|
69 |
+
APIFY_API_TOKEN = get_secret('APIFY_API_TOKEN') # Will be None if not set in Secrets
|
70 |
+
|
71 |
+
logger.info("Secret loading attempt finished.")
|
72 |
+
|
73 |
+
# --- Initial Validation ---
|
74 |
+
# Perform validation *after* attempting to load all secrets
|
75 |
+
if not TELEGRAM_TOKEN:
|
76 |
+
logger.critical("FATAL: TELEGRAM_TOKEN environment variable not found or empty!")
|
77 |
+
# In a deployed environment, exiting might not be helpful. Log critical error.
|
78 |
+
# exit("Telegram Token Missing")
|
79 |
+
else:
|
80 |
+
logger.info("TELEGRAM_TOKEN seems present.")
|
81 |
+
|
82 |
+
if not OPENROUTER_API_KEY:
|
83 |
+
# Log error but allow running, summaries will just fail gracefully later
|
84 |
+
logger.error("OPENROUTER_API_KEY not found or empty! Summarization will fail.")
|
85 |
+
else:
|
86 |
+
logger.info("OPENROUTER_API_KEY seems present.")
|
87 |
+
|
88 |
+
# (Optional checks log warnings if keys were not found by get_secret)
|
89 |
+
|
90 |
+
|
91 |
+
# --- Bot Logic Functions (Simplified Version - No Crawl4AI) ---
|
92 |
+
# (Functions: is_youtube_url, extract_youtube_id, get_transcript_via_supadata,
|
93 |
+
# get_transcript_via_apify, get_youtube_transcript, get_website_content_via_requests,
|
94 |
+
# get_website_content_via_urltotext_api, generate_summary remain EXACTLY THE SAME
|
95 |
+
# as in the previous complete main.py code block. Ensure they are included here.)
|
96 |
+
|
97 |
+
# --- [PASTE ALL BOT LOGIC FUNCTIONS HERE - FROM is_youtube_url to generate_summary ] ---
|
98 |
+
# Helper Functions
|
99 |
+
def is_youtube_url(url):
|
100 |
+
"""Checks if the URL is a valid YouTube video or shorts URL."""
|
101 |
+
youtube_regex = r'(https?://)?(www\.)?(youtube\.com/(watch\?v=|shorts/)|youtu\.be/)([\w-]{11})'
|
102 |
+
return bool(re.search(youtube_regex, url))
|
103 |
+
|
104 |
+
def extract_youtube_id(url):
|
105 |
+
"""Extracts the YouTube video ID from a URL."""
|
106 |
+
youtube_id_regex = r'(?:youtube\.com/(?:watch\?v=|shorts/)|youtu\.be/)([\w-]{11})'
|
107 |
+
match = re.search(youtube_id_regex, url)
|
108 |
+
if match:
|
109 |
+
return match.group(1)
|
110 |
+
logger.warning(f"Could not extract YouTube ID from URL: {url}")
|
111 |
+
return None
|
112 |
+
|
113 |
+
# Supadata Transcript Fetching
|
114 |
+
async def get_transcript_via_supadata(video_id: str, api_key: str):
|
115 |
+
"""Fetches YouTube transcript via Supadata API."""
|
116 |
+
if not video_id: logger.error("[Supadata] get_transcript_via_supadata called with no video_id"); return None
|
117 |
+
if not api_key: logger.error("[Supadata] API key is missing."); return None # Already checked before calling
|
118 |
+
logger.info(f"[Supadata] Attempting fetch for video ID: {video_id}")
|
119 |
+
api_endpoint = f"https://api.supadata.net/v1/youtube/transcript"
|
120 |
+
params = {"videoId": video_id, "format": "text"}
|
121 |
+
headers = {"X-API-Key": api_key}
|
122 |
+
try:
|
123 |
+
# Use asyncio.to_thread to run blocking requests.get in a separate thread
|
124 |
+
response = await asyncio.to_thread(requests.get, api_endpoint, headers=headers, params=params, timeout=30)
|
125 |
+
logger.debug(f"[Supadata] Received status code {response.status_code} for {video_id}")
|
126 |
+
if response.status_code == 200:
|
127 |
+
try:
|
128 |
+
data = response.json()
|
129 |
+
content = data if isinstance(data, str) else data.get("transcript") or data.get("text") or data.get("data")
|
130 |
+
if content and isinstance(content, str):
|
131 |
+
logger.info(f"[Supadata] Successfully fetched transcript for {video_id}. Length: {len(content)}")
|
132 |
+
return content.strip()
|
133 |
+
else:
|
134 |
+
logger.warning(f"[Supadata] API success but content empty/invalid for {video_id}. Response: {data}")
|
135 |
+
return None
|
136 |
+
except json.JSONDecodeError: # Handle cases where API might return plain text on success
|
137 |
+
if response.text:
|
138 |
+
logger.info(f"[Supadata] Successfully fetched transcript (plain text) for {video_id}. Length: {len(response.text)}")
|
139 |
+
return response.text.strip()
|
140 |
+
else:
|
141 |
+
logger.error(f"[Supadata] Failed to decode JSON response (and no text body) for {video_id}. Response: {response.text[:200]}...")
|
142 |
+
return None
|
143 |
+
except Exception as e:
|
144 |
+
logger.error(f"[Supadata] Error processing successful response for {video_id}: {e}", exc_info=True)
|
145 |
+
return None
|
146 |
+
elif response.status_code in [401, 403]:
|
147 |
+
logger.error(f"[Supadata] Authentication error ({response.status_code}). Check API key.")
|
148 |
+
return None # Don't retry if key is bad
|
149 |
+
elif response.status_code == 404:
|
150 |
+
logger.warning(f"[Supadata] Transcript not found ({response.status_code}) for {video_id}.")
|
151 |
+
return None
|
152 |
+
else:
|
153 |
+
logger.error(f"[Supadata] Unexpected status code {response.status_code} for {video_id}. Response: {response.text[:200]}...")
|
154 |
+
return None
|
155 |
+
except requests.exceptions.Timeout:
|
156 |
+
logger.error(f"[Supadata] Timeout error connecting to API for {video_id}")
|
157 |
+
return None
|
158 |
+
except requests.exceptions.RequestException as e:
|
159 |
+
logger.error(f"[Supadata] Request error connecting to API for {video_id}: {e}")
|
160 |
+
return None
|
161 |
+
except Exception as e:
|
162 |
+
logger.error(f"[Supadata] Unexpected error during API call for {video_id}: {e}", exc_info=True)
|
163 |
+
return None
|
164 |
+
|
165 |
+
# Apify Transcript Fetching
|
166 |
+
async def get_transcript_via_apify(video_url: str, api_token: str):
|
167 |
+
"""Fetches YouTube transcript via Apify API."""
|
168 |
+
if not video_url: logger.error("[Apify] get_transcript_via_apify called with no video_url"); return None
|
169 |
+
if not api_token: logger.error("[Apify] API token is missing."); return None # Already checked
|
170 |
+
if not ApifyClient: logger.error("[Apify] ApifyClient not available/imported."); return None
|
171 |
+
|
172 |
+
logger.info(f"[Apify] Attempting fetch for URL: {video_url}")
|
173 |
+
actor_id = "karamelo~youtube-transcripts"
|
174 |
+
api_endpoint = f"https://api.apify.com/v2/acts/{actor_id}/run-sync-get-dataset-items"
|
175 |
+
params = {"token": api_token}
|
176 |
+
payload = json.dumps({
|
177 |
+
"urls": [video_url],
|
178 |
+
"outputFormat": "singleStringText",
|
179 |
+
"maxRetries": 5,
|
180 |
+
"channelHandleBoolean": False,
|
181 |
+
"channelNameBoolean": False,
|
182 |
+
"datePublishedBoolean": False,
|
183 |
+
"relativeDateTextBoolean": False,
|
184 |
+
})
|
185 |
+
headers = {"Content-Type": "application/json"}
|
186 |
+
try:
|
187 |
+
logger.debug(f"[Apify] Sending request to run actor {actor_id} synchronously for {video_url}")
|
188 |
+
response = await asyncio.to_thread(requests.post, api_endpoint, headers=headers, params=params, data=payload, timeout=90) # Longer timeout for actor run
|
189 |
+
logger.debug(f"[Apify] Received status code {response.status_code} for {video_url}")
|
190 |
+
if response.status_code == 200:
|
191 |
+
try:
|
192 |
+
results = response.json()
|
193 |
+
if isinstance(results, list) and len(results) > 0:
|
194 |
+
item = results[0]
|
195 |
+
content = item.get("text") or item.get("transcript") or item.get("captions_concatenated")
|
196 |
+
if not content and item.get("captions") and isinstance(item["captions"], list): # Handle 'captions' format if primary keys fail
|
197 |
+
logger.info("[Apify] Processing 'captions' format.")
|
198 |
+
content = " ".join(cap.get("text", "") for cap in item["captions"] if cap.get("text"))
|
199 |
+
if content and isinstance(content, str):
|
200 |
+
logger.info(f"[Apify] Successfully fetched transcript for {video_url}. Length: {len(content)}")
|
201 |
+
return content.strip()
|
202 |
+
else:
|
203 |
+
logger.warning(f"[Apify] Actor run successful but transcript content not found/empty in result for {video_url}. Result item: {item}")
|
204 |
+
return None
|
205 |
+
else:
|
206 |
+
logger.warning(f"[Apify] Actor run successful but dataset was empty for {video_url}. Response: {results}")
|
207 |
+
return None
|
208 |
+
except json.JSONDecodeError:
|
209 |
+
logger.error(f"[Apify] Failed to decode JSON response for {video_url}. Status: {response.status_code}. Response text: {response.text[:200]}...")
|
210 |
+
return None
|
211 |
+
except Exception as e:
|
212 |
+
logger.error(f"[Apify] Error processing successful response for {video_url}: {e}", exc_info=True)
|
213 |
+
return None
|
214 |
+
elif response.status_code == 400:
|
215 |
+
logger.error(f"[Apify] Bad Request (400) for {video_url}. Check input payload. Response: {response.text[:200]}...")
|
216 |
+
return None
|
217 |
+
elif response.status_code == 401:
|
218 |
+
logger.error("[Apify] Authentication error (401). Check API token.")
|
219 |
+
return None # Don't retry if token is bad
|
220 |
+
else:
|
221 |
+
logger.error(f"[Apify] Unexpected status code {response.status_code} for {video_url}. Response: {response.text[:200]}...")
|
222 |
+
return None
|
223 |
+
except requests.exceptions.Timeout:
|
224 |
+
logger.error(f"[Apify] Timeout error running actor for {video_url}")
|
225 |
+
return None
|
226 |
+
except requests.exceptions.RequestException as e:
|
227 |
+
logger.error(f"[Apify] Request error running actor for {video_url}: {e}")
|
228 |
+
return None
|
229 |
+
except Exception as e:
|
230 |
+
logger.error(f"[Apify] Unexpected error during Apify call for {video_url}: {e}", exc_info=True)
|
231 |
+
return None
|
232 |
+
|
233 |
+
# Combined YouTube Transcript Function (with Fallbacks)
|
234 |
+
async def get_youtube_transcript(video_id: str, video_url: str, supadata_key: str | None, apify_token: str | None):
|
235 |
+
"""Fetches YouTube transcript using library, then Supadata, then Apify."""
|
236 |
+
if not video_id: logger.error("get_youtube_transcript called with no video_id"); return None
|
237 |
+
logger.info(f"Fetching transcript for video ID: {video_id} (URL: {video_url})")
|
238 |
+
transcript_text = None
|
239 |
+
|
240 |
+
# 1. Primary Method: youtube-transcript-api
|
241 |
+
logger.info("[Primary YT] Attempting youtube-transcript-api...")
|
242 |
+
try:
|
243 |
+
# Run synchronous library call in a thread
|
244 |
+
transcript_list = await asyncio.to_thread(
|
245 |
+
YouTubeTranscriptApi.get_transcript,
|
246 |
+
video_id,
|
247 |
+
languages=['en', 'en-GB', 'en-US'] # Prioritize English variations
|
248 |
+
)
|
249 |
+
if transcript_list:
|
250 |
+
transcript_text = " ".join([item['text'] for item in transcript_list if 'text' in item])
|
251 |
+
if transcript_text:
|
252 |
+
logger.info(f"[Primary YT] Successfully fetched transcript via library for {video_id} (length: {len(transcript_text)})")
|
253 |
+
return transcript_text # Return immediately on success
|
254 |
+
else:
|
255 |
+
logger.warning(f"[Primary YT] Joined transcript text is empty for {video_id}")
|
256 |
+
transcript_text = None # Ensure it's None if empty after join
|
257 |
+
else:
|
258 |
+
logger.warning(f"[Primary YT] Transcript list empty for {video_id}")
|
259 |
+
transcript_text = None
|
260 |
+
except Exception as e:
|
261 |
+
logger.warning(f"[Primary YT] Error getting transcript via library for {video_id}: {e}")
|
262 |
+
if "No transcript found" in str(e): logger.warning(f"[Primary YT] No transcript found for {video_id}. May be unavailable/private.")
|
263 |
+
elif "disabled" in str(e): logger.warning(f"[Primary YT] Transcripts disabled for {video_id}.")
|
264 |
+
transcript_text = None # Ensure it's None on error
|
265 |
+
|
266 |
+
# 2. Fallback 1: Supadata API
|
267 |
+
if transcript_text is None:
|
268 |
+
logger.info("[Fallback YT 1] Primary method failed. Trying Supadata API...")
|
269 |
+
if supadata_key:
|
270 |
+
transcript_text = await get_transcript_via_supadata(video_id, supadata_key)
|
271 |
+
if transcript_text:
|
272 |
+
logger.info(f"[Fallback YT 1] Successfully fetched transcript via Supadata for {video_id}")
|
273 |
+
return transcript_text # Return on success
|
274 |
+
else:
|
275 |
+
logger.warning(f"[Fallback YT 1] Supadata API failed or returned no content for {video_id}.")
|
276 |
+
else:
|
277 |
+
logger.warning("[Fallback YT 1] Supadata API key not available. Skipping.")
|
278 |
+
|
279 |
+
# 3. Fallback 2: Apify API
|
280 |
+
if transcript_text is None:
|
281 |
+
logger.info("[Fallback YT 2] Primary & Supadata failed. Trying Apify API...")
|
282 |
+
if apify_token:
|
283 |
+
transcript_text = await get_transcript_via_apify(video_url, apify_token)
|
284 |
+
if transcript_text:
|
285 |
+
logger.info(f"[Fallback YT 2] Successfully fetched transcript via Apify for {video_url}")
|
286 |
+
return transcript_text # Return on success
|
287 |
+
else:
|
288 |
+
logger.warning(f"[Fallback YT 2] Apify API failed or returned no content for {video_url}.")
|
289 |
+
else:
|
290 |
+
logger.warning("[Fallback YT 2] Apify API token not available. Skipping.")
|
291 |
+
|
292 |
+
# If all methods failed
|
293 |
+
if transcript_text is None:
|
294 |
+
logger.error(f"All methods failed to fetch transcript for video ID: {video_id}")
|
295 |
+
return None
|
296 |
+
|
297 |
+
# Should not be reached if logic above is correct, but as a safeguard
|
298 |
+
return transcript_text
|
299 |
+
|
300 |
+
# Website Content via Requests/BS4 (Primary Method for Simplified Bot)
|
301 |
+
async def get_website_content_via_requests(url):
|
302 |
+
"""Attempts to scrape website content using requests/BeautifulSoup (Primary Method)."""
|
303 |
+
if not url: logger.error("[Web Scraper - Requests/BS4] called with no URL"); return None
|
304 |
+
logger.info(f"[Web Scraper - Requests/BS4] Fetching website content for: {url}")
|
305 |
+
try:
|
306 |
+
headers = {
|
307 |
+
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36', # Updated UA
|
308 |
+
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
|
309 |
+
'Accept-Language': 'en-US,en;q=0.9',
|
310 |
+
'Connection': 'keep-alive',
|
311 |
+
'DNT': '1', # Do Not Track
|
312 |
+
'Upgrade-Insecure-Requests': '1'
|
313 |
+
}
|
314 |
+
logger.debug(f"[Web Scraper - Requests/BS4] Sending request to {url}")
|
315 |
+
# Run blocking I/O in a separate thread
|
316 |
+
response = await asyncio.to_thread(requests.get, url, headers=headers, timeout=25, allow_redirects=True)
|
317 |
+
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
|
318 |
+
logger.debug(f"[Web Scraper - Requests/BS4] Received response {response.status_code} from {url}")
|
319 |
+
|
320 |
+
content_type = response.headers.get('content-type', '').lower()
|
321 |
+
if 'html' not in content_type:
|
322 |
+
logger.warning(f"[Web Scraper - Requests/BS4] Non-HTML content type received from {url}: {content_type}")
|
323 |
+
return None # Don't try to parse non-html
|
324 |
+
|
325 |
+
# Use html.parser, it's built-in
|
326 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
327 |
+
|
328 |
+
# Remove common unwanted tags more aggressively
|
329 |
+
for element in soup(["script", "style", "header", "footer", "nav", "aside", "form", "button", "input", "textarea", "select", "option", "label", "iframe", "img", "svg", "link", "meta", "noscript", "figure", "figcaption", "video", "audio"]):
|
330 |
+
element.extract()
|
331 |
+
|
332 |
+
# Try finding common main content containers
|
333 |
+
main_content = soup.find('main') or \
|
334 |
+
soup.find('article') or \
|
335 |
+
soup.find(id='content') or \
|
336 |
+
soup.find(class_='content') or \
|
337 |
+
soup.find(id='main-content') or \
|
338 |
+
soup.find(class_='main-content') or \
|
339 |
+
soup.find(role='main')
|
340 |
+
|
341 |
+
# Fallback to body if no specific container found
|
342 |
+
target_element = main_content if main_content else soup.body
|
343 |
+
|
344 |
+
if not target_element:
|
345 |
+
logger.warning(f"[Web Scraper - Requests/BS4] Could not find body or main content container for parsing {url}")
|
346 |
+
return None # Nothing to parse
|
347 |
+
|
348 |
+
# Get text, joining lines smartly
|
349 |
+
lines = [line.strip() for line in target_element.get_text(separator='\n', strip=True).splitlines() if line.strip()]
|
350 |
+
text = "\n".join(lines) # Join with newlines to preserve some structure
|
351 |
+
|
352 |
+
# Basic length check
|
353 |
+
if not text or len(text) < 50: # Arbitrary short length check
|
354 |
+
logger.warning(f"[Web Scraper - Requests/BS4] Extracted text is very short or empty after cleaning for {url} (Length: {len(text)})")
|
355 |
+
# Consider returning None if too short, depends on use case
|
356 |
+
# return None
|
357 |
+
|
358 |
+
logger.info(f"[Web Scraper - Requests/BS4] Successfully scraped content for {url} (final length: {len(text)})")
|
359 |
+
return text
|
360 |
+
|
361 |
+
except requests.exceptions.Timeout:
|
362 |
+
logger.error(f"[Web Scraper - Requests/BS4] Timeout error scraping website: {url}")
|
363 |
+
return None
|
364 |
+
except requests.exceptions.TooManyRedirects:
|
365 |
+
logger.error(f"[Web Scraper - Requests/BS4] Too many redirects error scraping website: {url}")
|
366 |
+
return None
|
367 |
+
except requests.exceptions.RequestException as e:
|
368 |
+
# This catches ConnectTimeout, HTTPError, ConnectionError etc.
|
369 |
+
logger.error(f"[Web Scraper - Requests/BS4] Request error scraping website {url}: {e}")
|
370 |
+
return None
|
371 |
+
except Exception as e:
|
372 |
+
# Catch-all for unexpected errors during parsing etc.
|
373 |
+
logger.error(f"[Web Scraper - Requests/BS4] Error scraping or parsing website {url}: {e}", exc_info=True)
|
374 |
+
return None
|
375 |
+
|
376 |
+
# Website Content via URLToText API (Fallback Method)
|
377 |
+
async def get_website_content_via_urltotext_api(url: str, api_key: str):
|
378 |
+
"""Fetches website content using the URLToText API (Fallback)."""
|
379 |
+
if not url: logger.error("[Web Scraper - URLToText API] called with no URL"); return None
|
380 |
+
if not api_key: logger.error("[Web Scraper - URLToText API] API key is missing."); return None # Already checked
|
381 |
+
logger.info(f"[Web Scraper - URLToText API] Attempting to fetch content for: {url}")
|
382 |
+
api_endpoint = "https://urltotext.com/api/v1/urltotext/"
|
383 |
+
payload = json.dumps({
|
384 |
+
"url": url,
|
385 |
+
"output_format": "text",
|
386 |
+
"extract_main_content": True,
|
387 |
+
"render_javascript": True, # Often needed for modern sites
|
388 |
+
"residential_proxy": False, # Start with standard
|
389 |
+
})
|
390 |
+
headers = {
|
391 |
+
"Authorization": f"Token {api_key}",
|
392 |
+
"Content-Type": "application/json"
|
393 |
+
}
|
394 |
+
try:
|
395 |
+
logger.debug(f"[Web Scraper - URLToText API] Sending request for {url}")
|
396 |
+
response = await asyncio.to_thread(requests.post, api_endpoint, headers=headers, data=payload, timeout=45)
|
397 |
+
logger.debug(f"[Web Scraper - URLToText API] Received status code {response.status_code} for {url}")
|
398 |
+
if response.status_code == 200:
|
399 |
+
try:
|
400 |
+
data = response.json()
|
401 |
+
content = data.get("data", {}).get("content")
|
402 |
+
credits = data.get("credits_used", "N/A")
|
403 |
+
warning = data.get("data", {}).get("warning")
|
404 |
+
if warning: logger.warning(f"[Web Scraper - URLToText API] Warning for {url}: {warning}")
|
405 |
+
if content:
|
406 |
+
logger.info(f"[Web Scraper - URLToText API] Successfully fetched content via API for {url}. Length: {len(content)}. Credits: {credits}")
|
407 |
+
return content.strip()
|
408 |
+
else:
|
409 |
+
logger.warning(f"[Web Scraper - URLToText API] API returned success but content was empty for {url}. Response: {data}")
|
410 |
+
return None
|
411 |
+
except json.JSONDecodeError:
|
412 |
+
logger.error(f"[Web Scraper - URLToText API] Failed to decode JSON response for {url}. Response: {response.text[:500]}...")
|
413 |
+
return None
|
414 |
+
except Exception as e:
|
415 |
+
logger.error(f"[Web Scraper - URLToText API] Error processing successful API response for {url}: {e}", exc_info=True)
|
416 |
+
return None
|
417 |
+
elif response.status_code in [400, 402, 422, 500]: # Known client/server errors
|
418 |
+
logger.error(f"[Web Scraper - URLToText API] Error {response.status_code} from API for {url}. Response: {response.text[:200]}...")
|
419 |
+
return None
|
420 |
+
else: # Other unexpected codes
|
421 |
+
logger.error(f"[Web Scraper - URLToText API] Unexpected status {response.status_code} from API for {url}. Response: {response.text[:200]}...")
|
422 |
+
return None
|
423 |
+
except requests.exceptions.Timeout:
|
424 |
+
logger.error(f"[Web Scraper - URLToText API] Timeout error connecting to API for {url}")
|
425 |
+
return None
|
426 |
+
except requests.exceptions.RequestException as e:
|
427 |
+
logger.error(f"[Web Scraper - URLToText API] Request error connecting to API for {url}: {e}")
|
428 |
+
return None
|
429 |
+
except Exception as e:
|
430 |
+
logger.error(f"[Web Scraper - URLToText API] Unexpected error during API call for {url}: {e}", exc_info=True)
|
431 |
+
return None
|
432 |
+
|
433 |
+
# DeepSeek Summary Function (via OpenRouter)
|
434 |
+
async def generate_summary(text: str, summary_type: str, api_key: str) -> str:
|
435 |
+
"""Generates summary using DeepSeek via OpenRouter API."""
|
436 |
+
logger.info(f"Generating {summary_type} summary using DeepSeek/OpenRouter. Input text length: {len(text)}")
|
437 |
+
if not api_key:
|
438 |
+
logger.error("OpenRouter API key was not provided to generate_summary.")
|
439 |
+
return "Error: AI model configuration key (OpenRouter) is missing."
|
440 |
+
|
441 |
+
openrouter_api_endpoint = "https://openrouter.ai/api/v1/chat/completions"
|
442 |
+
# Check OpenRouter docs for the latest recommended free/low-cost models
|
443 |
+
model_name = "deepseek/deepseek-chat:free"
|
444 |
+
|
445 |
+
if summary_type == "paragraph":
|
446 |
+
prompt = "You are an AI model designed to provide concise summaries using British English spellings. Your output MUST be: • Clear and simple language suitable for someone unfamiliar with the topic. • Uses British English spellings throughout. • Straightforward and understandable vocabulary; avoid complex terms. • Presented as ONE SINGLE PARAGRAPH. • No more than 85 words maximum; but does not have to be exactly 85. • Considers the entire text content equally. • Uses semicolons (;) instead of em dashes (– or —). Here is the text to summarise:"
|
447 |
+
else: # points summary
|
448 |
+
prompt = """You are an AI model designed to provide concise summaries using British English spellings. Your output MUST strictly follow this Markdown format:
|
449 |
+
• For each distinct topic or section identified in the text, create a heading.
|
450 |
+
• Each heading MUST be enclosed in double asterisks for bolding (e.g., **Section Title**).
|
451 |
+
• Immediately following each heading, list the key points as a bulleted list.
|
452 |
+
• Each bullet point MUST start with a hyphen and a space (`- `) on a new line.
|
453 |
+
• The text within each bullet point should NOT contain any bold formatting.
|
454 |
+
• Use clear, simple, and straightforward language suitable for someone unfamiliar with the topic.
|
455 |
+
• Use British English spellings throughout.
|
456 |
+
• Avoid overly complex or advanced vocabulary.
|
457 |
+
• Keep bullet points concise.
|
458 |
+
• Ensure the entire summary takes no more than two minutes to read.
|
459 |
+
• Consider the entire text's content, not just the beginning or a few topics.
|
460 |
+
• Use semicolons (;) instead of em dashes (– or —).
|
461 |
+
|
462 |
+
Here is the text to summarise:"""
|
463 |
+
|
464 |
+
MAX_INPUT_LENGTH = 500000 # Truncate long inputs to avoid high costs/errors
|
465 |
+
if len(text) > MAX_INPUT_LENGTH:
|
466 |
+
logger.warning(f"Input text length ({len(text)}) exceeds limit ({MAX_INPUT_LENGTH}). Truncating.")
|
467 |
+
text = text[:MAX_INPUT_LENGTH] + "... (Content truncated)"
|
468 |
+
full_prompt = f"{prompt}\n\n{text}"
|
469 |
+
|
470 |
+
headers = {
|
471 |
+
"Authorization": f"Bearer {api_key}",
|
472 |
+
"Content-Type": "application/json",
|
473 |
+
# Recommended headers for OpenRouter identification
|
474 |
+
"HTTP-Referer": "https://huggingface.co/spaces/", # Identify source as HF Space
|
475 |
+
"X-Title": "Telegram Summary Bot (HF Space)", # Identify app
|
476 |
+
}
|
477 |
+
payload = json.dumps({
|
478 |
+
"model": model_name,
|
479 |
+
"messages": [
|
480 |
+
{"role": "user", "content": full_prompt}
|
481 |
+
],
|
482 |
+
# Optional: Add max_tokens if needed, check model defaults
|
483 |
+
# "max_tokens": 1024,
|
484 |
+
})
|
485 |
+
|
486 |
+
try:
|
487 |
+
logger.debug(f"Sending request to OpenRouter ({model_name})...")
|
488 |
+
# Run blocking request in thread
|
489 |
+
response = await asyncio.to_thread(requests.post, openrouter_api_endpoint, headers=headers, data=payload, timeout=60)
|
490 |
+
logger.debug(f"Received status code {response.status_code} from OpenRouter.")
|
491 |
+
|
492 |
+
if response.status_code == 200:
|
493 |
+
try:
|
494 |
+
data = response.json()
|
495 |
+
if data.get("choices") and isinstance(data["choices"], list) and len(data["choices"]) > 0:
|
496 |
+
message = data["choices"][0].get("message")
|
497 |
+
if message and isinstance(message, dict):
|
498 |
+
summary = message.get("content")
|
499 |
+
if summary:
|
500 |
+
logger.info(f"Successfully generated summary via OpenRouter. Output length: {len(summary)}")
|
501 |
+
return summary.strip()
|
502 |
+
else:
|
503 |
+
logger.warning(f"OpenRouter response successful, but content was empty. Response: {data}")
|
504 |
+
return "Sorry, the AI model returned an empty summary."
|
505 |
+
else:
|
506 |
+
logger.error(f"Unexpected message structure in OpenRouter response: {message}. Full response: {data}")
|
507 |
+
return "Sorry, could not parse the AI model's response (unexpected format)."
|
508 |
+
else:
|
509 |
+
# Handle cases like moderation flags, empty choices list
|
510 |
+
if data.get("error"): logger.error(f"OpenRouter API Error: {data['error']}")
|
511 |
+
else: logger.error(f"Unexpected choices structure in OpenRouter response: {data.get('choices')}. Full response: {data}")
|
512 |
+
return "Sorry, could not parse the AI model's response (choices missing/invalid or API error)."
|
513 |
+
|
514 |
+
except json.JSONDecodeError:
|
515 |
+
logger.error(f"Failed to decode JSON response from OpenRouter. Status: {response.status_code}. Response text: {response.text[:500]}...")
|
516 |
+
return "Sorry, failed to understand the response from the AI model."
|
517 |
+
except Exception as e:
|
518 |
+
logger.error(f"Error processing successful OpenRouter response: {e}", exc_info=True)
|
519 |
+
return "Sorry, an error occurred while processing the AI model's response."
|
520 |
+
|
521 |
+
elif response.status_code == 401:
|
522 |
+
logger.error("OpenRouter API key is invalid (401 Unauthorized). Check HF Space Secrets.")
|
523 |
+
return "Error: The AI model configuration key (OpenRouter) is invalid."
|
524 |
+
elif response.status_code == 402:
|
525 |
+
logger.error("OpenRouter Payment Required (402). Check credits/limits on OpenRouter.")
|
526 |
+
return "Sorry, there might be an issue with the AI model service limits or payment. Please try again later or check OpenRouter account."
|
527 |
+
elif response.status_code == 429:
|
528 |
+
logger.warning("OpenRouter Rate Limit Exceeded (429).")
|
529 |
+
return "Sorry, the AI model is currently busy due to high demand. Please try again in a moment."
|
530 |
+
elif response.status_code == 500:
|
531 |
+
logger.error(f"OpenRouter Internal Server Error (500). Response: {response.text[:500]}...")
|
532 |
+
return "Sorry, the AI model service encountered an internal error. Please try again later."
|
533 |
+
else:
|
534 |
+
# Handle other potential errors (e.g., 400 Bad Request, 404 Not Found for model)
|
535 |
+
logger.error(f"Unexpected status code {response.status_code} from OpenRouter. Response: {response.text[:500]}...")
|
536 |
+
try: # Try to parse error message from response body
|
537 |
+
error_data = response.json()
|
538 |
+
error_msg = error_data.get("error", {}).get("message", response.text[:100])
|
539 |
+
return f"Sorry, the AI model service returned an error ({response.status_code}): {error_msg}"
|
540 |
+
except: # Fallback if parsing fails
|
541 |
+
return f"Sorry, the AI model service returned an unexpected status ({response.status_code})."
|
542 |
+
|
543 |
+
except requests.exceptions.Timeout:
|
544 |
+
logger.error("Timeout error connecting to OpenRouter API.")
|
545 |
+
return "Sorry, the request to the AI model timed out. Please try again."
|
546 |
+
except requests.exceptions.RequestException as e:
|
547 |
+
logger.error(f"Request error connecting to OpenRouter API: {e}")
|
548 |
+
return "Sorry, there was an error connecting to the AI model service."
|
549 |
+
except Exception as e:
|
550 |
+
logger.error(f"Unexpected error in generate_summary (OpenRouter): {e}", exc_info=True)
|
551 |
+
return "Sorry, an unexpected error occurred while generating the summary."
|
552 |
+
|
553 |
+
|
554 |
+
|
555 |
+
# --- Telegram Bot Handlers (Command, Message, CallbackQuery) ---
|
556 |
+
|
557 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
558 |
+
"""Sends a welcome message when the /start command is issued."""
|
559 |
+
user = update.effective_user
|
560 |
+
logger.info(f"User {user.id} ({user.username or 'NoUsername'}) used /start.")
|
561 |
+
mention = user.mention_html() if user.username else user.first_name
|
562 |
+
await update.message.reply_html(
|
563 |
+
f"👋 Hello {mention}! I can summarize YouTube links or website URLs.\n\n"
|
564 |
+
"Just send me a link anytime!",
|
565 |
+
# Optional: disable_web_page_preview=True
|
566 |
+
)
|
567 |
+
|
568 |
+
async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
569 |
+
"""Sends a help message when the /help command is issued."""
|
570 |
+
logger.info(f"User {update.effective_user.id} used /help.")
|
571 |
+
await update.message.reply_text(
|
572 |
+
"🔍 **How to use this bot:**\n\n"
|
573 |
+
"1. Send me any YouTube video link or website URL.\n"
|
574 |
+
"2. I'll ask how you want it summarized (paragraph or points).\n"
|
575 |
+
"3. Click the button for your choice.\n"
|
576 |
+
"4. Wait for the summary!\n\n"
|
577 |
+
"I use multiple methods if the first fails (especially for YT transcripts & website content).\n\n"
|
578 |
+
"**Commands:**\n"
|
579 |
+
"/start - Display welcome message\n"
|
580 |
+
"/help - Show this help message",
|
581 |
+
parse_mode=ParseMode.MARKDOWN
|
582 |
+
)
|
583 |
+
|
584 |
+
async def handle_potential_url(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
585 |
+
"""Handles text messages, checks for URLs, and asks for summary type."""
|
586 |
+
if not update.message or not update.message.text: return # Ignore empty messages
|
587 |
+
url = update.message.text.strip()
|
588 |
+
user = update.effective_user
|
589 |
+
logger.info(f"User {user.id} ({user.username or 'NoUsername'}) sent potential URL: {url}")
|
590 |
+
|
591 |
+
# Basic URL validation
|
592 |
+
if not (url.startswith('http://') or url.startswith('https://')) or '.' not in url[8:]:
|
593 |
+
logger.debug(f"Ignoring non-URL message from user {user.id}: {url}")
|
594 |
+
# Optional: Reply if you want to guide the user
|
595 |
+
# await update.message.reply_text("Please send a valid URL starting with http:// or https://")
|
596 |
+
return
|
597 |
+
|
598 |
+
# Store URL in user_data (simple state management)
|
599 |
+
context.user_data['url_to_summarize'] = url
|
600 |
+
logger.debug(f"Stored URL '{url}' for user {user.id} in user_data")
|
601 |
+
|
602 |
+
# Ask for summary type with Inline Keyboard
|
603 |
+
keyboard = [
|
604 |
+
[
|
605 |
+
InlineKeyboardButton("Paragraph Summary", callback_data="paragraph"),
|
606 |
+
InlineKeyboardButton("Points Summary", callback_data="points")
|
607 |
+
]
|
608 |
+
]
|
609 |
+
reply_markup = InlineKeyboardMarkup(keyboard)
|
610 |
+
await update.message.reply_text(
|
611 |
+
f"Okay, I see this link:\n{url}\n\nHow would you like it summarized?",
|
612 |
+
reply_markup=reply_markup,
|
613 |
+
disable_web_page_preview=True
|
614 |
+
)
|
615 |
+
|
616 |
+
async def handle_summary_type_callback(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
|
617 |
+
"""Handles button presses for summary type selection."""
|
618 |
+
query = update.callback_query
|
619 |
+
if not query: return
|
620 |
+
await query.answer() # Acknowledge button press immediately
|
621 |
+
|
622 |
+
summary_type = query.data
|
623 |
+
user = update.effective_user or query.from_user # Get user info
|
624 |
+
url = context.user_data.get('url_to_summarize', None) # Retrieve stored URL
|
625 |
+
|
626 |
+
logger.info(f"User {user.id} chose '{summary_type}' summary. Checking for URL '{url}' in context.")
|
627 |
+
|
628 |
+
# Check if URL is still in context (it might expire or be lost)
|
629 |
+
if not url:
|
630 |
+
logger.warning(f"User {user.id} pressed button, but NO URL found in user_data context.")
|
631 |
+
try:
|
632 |
+
# Edit the message where the button was, informing the user
|
633 |
+
await query.edit_message_text(text="Sorry, I couldn't find the URL associated with this request. Please send the link again.")
|
634 |
+
except Exception as edit_err:
|
635 |
+
# If editing fails (e.g., message too old), log it but don't crash
|
636 |
+
logger.warning(f"Failed to edit message for missing URL context: {edit_err}")
|
637 |
+
# Maybe send a new message as a fallback? Depends on desired behavior.
|
638 |
+
# await context.bot.send_message(chat_id=user.id, text="Sorry, context lost. Please send link again.")
|
639 |
+
return # Stop processing if URL is missing
|
640 |
+
|
641 |
+
# Clear the URL from context now that we're processing it
|
642 |
+
context.user_data.pop('url_to_summarize', None)
|
643 |
+
logger.debug(f"Retrieved and cleared URL {url} from user_data for user {user.id}")
|
644 |
+
|
645 |
+
# --- Get API Keys (Read fresh from environment - cheap operation) ---
|
646 |
+
# This ensures if secrets are updated in HF UI, the next request uses them
|
647 |
+
logger.debug("Reading API keys from environment variables within handler...")
|
648 |
+
current_openrouter_key = os.environ.get('OPENROUTER_API_KEY')
|
649 |
+
current_urltotext_key = os.environ.get('URLTOTEXT_API_KEY')
|
650 |
+
current_supadata_key = os.environ.get('SUPADATA_API_KEY')
|
651 |
+
current_apify_token = os.environ.get('APIFY_API_TOKEN')
|
652 |
+
logger.debug(f"Keys read: OpenRouter={'Yes' if current_openrouter_key else 'No'}, URLToText={'Yes' if current_urltotext_key else 'No'}, Supadata={'Yes' if current_supadata_key else 'No'}, Apify={'Yes' if current_apify_token else 'No'}")
|
653 |
+
|
654 |
+
|
655 |
+
# Check *essential* key for summarization
|
656 |
+
if not current_openrouter_key:
|
657 |
+
logger.error("OpenRouter API key missing in handler. Cannot generate summary.")
|
658 |
+
# Inform user and clean up the button message
|
659 |
+
await context.bot.send_message(chat_id=user.id, text="Error: AI model configuration key (OpenRouter) is missing. Cannot generate summary.")
|
660 |
+
try: await query.delete_message() # Delete the message with buttons
|
661 |
+
except Exception: pass
|
662 |
+
return
|
663 |
+
|
664 |
+
# --- Start Processing ---
|
665 |
+
processing_message = f"Got it! Generating '{summary_type}' summary for:\n{url}\n\nThis might take a moment..."
|
666 |
+
message_to_delete_later = None # In case editing fails
|
667 |
+
try:
|
668 |
+
# Edit the message to show processing status
|
669 |
+
await query.edit_message_text(processing_message)
|
670 |
+
except Exception as e:
|
671 |
+
# If editing fails (e.g., message too old), send a new status message
|
672 |
+
logger.warning(f"Could not edit original message: {e}, sending new status message.")
|
673 |
+
try:
|
674 |
+
message_to_delete_later = await context.bot.send_message(chat_id=user.id, text=processing_message)
|
675 |
+
except Exception as send_err:
|
676 |
+
# If even sending fails, log and give up on this request
|
677 |
+
logger.error(f"Failed to send status message after edit failure: {send_err}")
|
678 |
+
return
|
679 |
+
|
680 |
+
content = None
|
681 |
+
user_feedback_message = None # Stores error messages for the user
|
682 |
+
success = False
|
683 |
+
is_youtube = is_youtube_url(url)
|
684 |
+
|
685 |
+
try:
|
686 |
+
# Show "typing..." status in Telegram chat
|
687 |
+
await context.bot.send_chat_action(chat_id=user.id, action='typing')
|
688 |
+
|
689 |
+
# --- Content Fetching Logic ---
|
690 |
+
if is_youtube:
|
691 |
+
video_id = extract_youtube_id(url)
|
692 |
+
if video_id:
|
693 |
+
# Fetch YT transcript using the function with fallbacks
|
694 |
+
content = await get_youtube_transcript(
|
695 |
+
video_id,
|
696 |
+
url, # Pass full URL for Apify
|
697 |
+
current_supadata_key,
|
698 |
+
current_apify_token
|
699 |
+
)
|
700 |
+
# Set feedback message only if content fetching failed
|
701 |
+
user_feedback_message = None if content else "Sorry, I couldn't get the transcript for that YouTube video using any available method (unavailable/private/no captions?)."
|
702 |
+
else:
|
703 |
+
user_feedback_message = "Sorry, I couldn't understand that YouTube URL format."
|
704 |
+
else: # Website Logic (Requests/BS4 -> URLToText API)
|
705 |
+
logger.info(f"Attempting website scrape (Requests/BS4) for {url}")
|
706 |
+
content = await get_website_content_via_requests(url)
|
707 |
+
|
708 |
+
if content:
|
709 |
+
logger.info("Primary website scraping (Requests/BS4) successful.")
|
710 |
+
user_feedback_message = None
|
711 |
+
else:
|
712 |
+
logger.warning(f"Primary web scraping failed for {url}. Attempting fallback API (URLToText).")
|
713 |
+
if current_urltotext_key:
|
714 |
+
await context.bot.send_chat_action(chat_id=user.id, action='typing') # Show activity for fallback
|
715 |
+
content = await get_website_content_via_urltotext_api(url, current_urltotext_key)
|
716 |
+
if content:
|
717 |
+
user_feedback_message = None
|
718 |
+
logger.info("Fallback URLToText API scraping successful.")
|
719 |
+
else:
|
720 |
+
user_feedback_message = "Sorry, I couldn't fetch content from that website using either method (blocked/inaccessible/empty?)."
|
721 |
+
logger.error(f"Both primary (Requests/BS4) and fallback API failed for website {url}.")
|
722 |
+
else:
|
723 |
+
# Primary failed, and fallback key is missing
|
724 |
+
user_feedback_message = "Sorry, I couldn't fetch content from that website (blocked/inaccessible/empty?). The fallback method is not configured."
|
725 |
+
logger.warning(f"Primary web scraping failed for {url}, and fallback API key (URLToText) is missing.")
|
726 |
+
# --- End Content Fetching ---
|
727 |
+
|
728 |
+
# --- Generate Summary if Content was Fetched ---
|
729 |
+
if content:
|
730 |
+
logger.info("Content fetched successfully, proceeding to generate summary.")
|
731 |
+
await context.bot.send_chat_action(chat_id=user.id, action='typing')
|
732 |
+
# Pass the OpenRouter key to the summary function
|
733 |
+
summary = await generate_summary(content, summary_type, current_openrouter_key)
|
734 |
+
|
735 |
+
# Check if summary generation returned an error message
|
736 |
+
if summary.startswith("Error:") or summary.startswith("Sorry,"):
|
737 |
+
user_feedback_message = summary # Use the error from the summary function
|
738 |
+
success = False
|
739 |
+
logger.warning(f"Summary generation failed or returned error: {summary}")
|
740 |
+
else:
|
741 |
+
# Send the successful summary
|
742 |
+
await context.bot.send_message(
|
743 |
+
chat_id=user.id,
|
744 |
+
text=summary,
|
745 |
+
parse_mode=ParseMode.MARKDOWN,
|
746 |
+
disable_web_page_preview=True
|
747 |
+
)
|
748 |
+
success = True
|
749 |
+
user_feedback_message = None # Clear any previous failure message from fetching stage
|
750 |
+
elif not user_feedback_message:
|
751 |
+
# If content is None but no specific error message was set during fetching
|
752 |
+
user_feedback_message = "Sorry, couldn't retrieve any content to summarize from the provided link."
|
753 |
+
logger.warning(f"Content fetching resulted in None for {url}, but no specific user feedback message was set.")
|
754 |
+
|
755 |
+
# --- Send Feedback if any step failed ---
|
756 |
+
if user_feedback_message and not success:
|
757 |
+
await context.bot.send_message(chat_id=user.id, text=user_feedback_message)
|
758 |
+
|
759 |
+
except Exception as e:
|
760 |
+
# Catch unexpected errors during the whole process
|
761 |
+
logger.error(f"Unexpected error during processing callback for {url}: {e}", exc_info=True)
|
762 |
+
try:
|
763 |
+
# Send a generic error message to the user
|
764 |
+
await context.bot.send_message(chat_id=user.id, text="Oops! Something went really wrong while processing your request. Please try again later.")
|
765 |
+
except Exception as final_err:
|
766 |
+
# If even sending the error message fails... log it.
|
767 |
+
logger.error(f"Failed to send final error message to user {user.id}: {final_err}")
|
768 |
+
finally:
|
769 |
+
# --- Cleanup ---
|
770 |
+
# Delete the "Processing..." status message or the original message with buttons
|
771 |
+
try:
|
772 |
+
if message_to_delete_later: # If we sent a separate status message
|
773 |
+
await context.bot.delete_message(chat_id=user.id, message_id=message_to_delete_later.message_id)
|
774 |
+
elif query: # Otherwise, delete the original message with the buttons
|
775 |
+
# We might have already edited it, but deleting ensures cleanup
|
776 |
+
await query.delete_message()
|
777 |
+
except Exception as del_e:
|
778 |
+
# Log if deletion fails, but don't let it stop anything
|
779 |
+
logger.warning(f"Could not delete status/button message: {del_e}")
|
780 |
+
|
781 |
+
|
782 |
+
async def error_handler(update: object, context: ContextTypes.DEFAULT_TYPE) -> None:
|
783 |
+
"""Log Errors caused by Updates."""
|
784 |
+
logger.error("Exception while handling an update:", exc_info=context.error)
|
785 |
+
# Optionally, notify the developer or user about the error
|
786 |
+
# developer_chat_id = 12345678 # Replace with your chat ID if desired
|
787 |
+
# if update and hasattr(update, 'effective_chat') and update.effective_chat:
|
788 |
+
# chat_id = update.effective_chat.id
|
789 |
+
# error_message = f"Error processing update {update.update_id} for chat {chat_id}. Error: {context.error}"
|
790 |
+
# else:
|
791 |
+
# error_message = f"Error in handler: {context.error}"
|
792 |
+
# try:
|
793 |
+
# await context.bot.send_message(chat_id=developer_chat_id, text=error_message)
|
794 |
+
# except Exception as e:
|
795 |
+
# logger.error(f"Failed to send error notification to developer: {e}")
|
796 |
+
|
797 |
+
|
798 |
+
# --- Initialize Telegram Bot Application ---
|
799 |
+
# Do this setup once when the script starts
|
800 |
+
logger.info("Initializing Telegram Application...")
|
801 |
+
if not TELEGRAM_TOKEN: # Check again, as initialization needs it
|
802 |
+
logger.critical("Cannot initialize PTB Application: TELEGRAM_TOKEN not found.")
|
803 |
+
ptb_app = None
|
804 |
+
else:
|
805 |
+
# Build PTB Application instance
|
806 |
+
ptb_app_builder = Application.builder().token(TELEGRAM_TOKEN)
|
807 |
+
# Removed concurrency settings for simplicity, PTB defaults should be okay with Flask + asyncio.create_task
|
808 |
+
# ptb_app_builder.concurrent_updates(True)
|
809 |
+
ptb_app = ptb_app_builder.build()
|
810 |
+
|
811 |
+
# Register handlers with the PTB application instance
|
812 |
+
ptb_app.add_handler(CommandHandler("start", start))
|
813 |
+
ptb_app.add_handler(CommandHandler("help", help_command))
|
814 |
+
ptb_app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_potential_url))
|
815 |
+
ptb_app.add_handler(CallbackQueryHandler(handle_summary_type_callback))
|
816 |
+
# Add the error handler
|
817 |
+
ptb_app.add_error_handler(error_handler)
|
818 |
+
logger.info("Telegram handlers registered.")
|
819 |
+
|
820 |
+
|
821 |
+
# --- Flask App Setup ---
|
822 |
+
app = Flask(__name__) # Create Flask web server instance
|
823 |
+
logger.info("Flask app created.")
|
824 |
+
|
825 |
+
|
826 |
+
# --- Webhook Endpoint ---
|
827 |
+
@app.route('/webhook', methods=['POST'])
|
828 |
+
async def webhook() -> Response:
|
829 |
+
"""Webhook endpoint to receive updates from Telegram"""
|
830 |
+
logger.info("Webhook request received...")
|
831 |
+
if not ptb_app: # Check if PTB initialization failed
|
832 |
+
logger.error("Telegram application not initialized. Cannot process update.")
|
833 |
+
return Response('Bot not configured properly', status=500)
|
834 |
+
|
835 |
+
if request.is_json:
|
836 |
+
try:
|
837 |
+
update_data = request.get_json()
|
838 |
+
# Use PTB's built-in deserialization
|
839 |
+
update = Update.de_json(update_data, ptb_app.bot)
|
840 |
+
logger.debug(f"Processing update ID: {update.update_id}")
|
841 |
+
|
842 |
+
# Process the update using PTB's internal dispatcher in a background task
|
843 |
+
asyncio.create_task(ptb_app.process_update(update))
|
844 |
+
|
845 |
+
# Respond quickly to Telegram that we received the update
|
846 |
+
return Response('ok', status=200)
|
847 |
+
except json.JSONDecodeError:
|
848 |
+
logger.error("Failed to decode JSON from Telegram webhook.")
|
849 |
+
return Response('Bad Request - Invalid JSON', status=400)
|
850 |
+
except Exception as e:
|
851 |
+
logger.error(f"Error processing update in webhook handler: {e}", exc_info=True)
|
852 |
+
return Response('Internal Server Error', status=500)
|
853 |
+
else:
|
854 |
+
logger.warning("Received non-JSON request to webhook endpoint.")
|
855 |
+
return Response('Bad Request - Expected JSON', status=400)
|
856 |
+
|
857 |
+
@app.route('/')
|
858 |
+
def index():
|
859 |
+
"""A simple health check endpoint for the web server"""
|
860 |
+
logger.debug("Health check endpoint '/' accessed.")
|
861 |
+
# You could add more checks here if needed (e.g., check PTB status)
|
862 |
+
bot_status = "PTB App Initialized" if ptb_app else "PTB App FAILED Initialization"
|
863 |
+
return f"Hello! Telegram Bot Webhook Listener ({bot_status}) is running."
|
864 |
+
|
865 |
+
|
866 |
+
# --- Main Execution Block ---
|
867 |
+
# This part runs the Flask web server when the Docker container starts via Gunicorn
|
868 |
+
if __name__ == '__main__':
|
869 |
+
# This block might not run when deployed via Gunicorn as specified in Dockerfile CMD
|
870 |
+
# Gunicorn imports the 'app' object directly from 'main.py'.
|
871 |
+
# However, it's good practice to have for potential local testing.
|
872 |
+
if not ptb_app:
|
873 |
+
logger.critical("Aborting Flask server start (local test?) because Telegram App failed initialization.")
|
874 |
+
else:
|
875 |
+
logger.info("Starting Flask web server directly (for local testing?)...")
|
876 |
+
# Use a development server port like 5000 for local testing
|
877 |
+
port = int(os.environ.get('PORT', 5000)) # Changed default for local test
|
878 |
+
# Run with debug=True ONLY for local testing, NEVER in production/deployment
|
879 |
+
app.run(host='0.0.0.0', port=port, debug=True)
|