-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcds_paper_bot.py
More file actions
2078 lines (1919 loc) · 85.1 KB
/
cds_paper_bot.py
File metadata and controls
2078 lines (1919 loc) · 85.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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
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
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Twitter bot to post latest CMS results."""
from __future__ import print_function
import argparse
import configparser
import logging
import os
import re
import shutil
import subprocess
import sys
import time
import zipfile
from io import BytesIO
from pathlib import Path
import daiquiri
import feedparser
import lxml.html as lh
import mastodon
import maya
import requests
import tweepy
# Assuming atproto is installed
from atproto import Client as BlueskyClient
from atproto import models as atproto_models
from atproto.exceptions import AtProtocolError as BlueskyAtpApiError
from pylatexenc.latex2text import LatexNodes2Text
from pylatexenc.latexwalker import LatexWalkerError
from wand.exceptions import CorruptImageError # pylint: disable=no-name-in-module
from wand.image import Color, Image
# Maximum image dimension (both x and y)
MAX_IMG_DIM = 1000 # could be 1280
MAX_IMG_DIM_AREA = 1280 * 720 # 1 megapixel
MAX_IMG_SIZE = 5242880
# TODO: tag actual experiment?
# TODO: Make certain keywords tags
# collection could be: Higgs, NewPhysics, 13TeV/8TeV, StandardModel,
# resonances, DarkMatter, SUSY, BSM
# Also: CMSB2G, CMSHIG, CMSEXO etc.
# TopQuark, BottomQuark Quark/Quarks, Tau
CADI_TO_HASHTAG = {}
CADI_TO_HASHTAG["TOP"] = "#TopQuark"
CADI_TO_HASHTAG["HIG"] = "#HiggsBoson"
CADI_TO_HASHTAG["B2G"] = "#NewPhysics"
CADI_TO_HASHTAG["EXO"] = "#NewPhysics"
CADI_TO_HASHTAG["SUS"] = "#SuperSymmetry"
CADI_TO_HASHTAG["FTR"] = "#Upgrade"
CADI_TO_HASHTAG["SMP"] = "#StandardModel"
CADI_TO_HASHTAG["BPH"] = "#BPhysics"
CADI_TO_HASHTAG["JME"] = "#Jets"
CADI_TO_HASHTAG["BTV"] = "#FlavourTagging"
CADI_TO_HASHTAG["MUO"] = "#Muons"
CADI_TO_HASHTAG["TAU"] = "#Taus #TauLeptons"
CADI_TO_HASHTAG["EGM"] = "#Electrons #Photons"
CADI_TO_HASHTAG["LUM"] = "#Luminosity"
CADI_TO_HASHTAG["PRF"] = "#ParticleFlow"
CADI_TO_HASHTAG["HIN"] = "#HeavyIons"
# identifiers for preliminary results
PRELIM = ["CMS-PAS", "ATLAS-CONF", "LHCb-CONF"]
class Conference(object):
"""Define conference class for hashtag implementation."""
__slots__ = ["name", "start", "end"]
def __init__(self, name, start, end):
"""Initialise with conf name, start and end dates."""
self.name = name
self.start = start
self.end = end
def is_now(self, pub_date):
"""Return conference name if publication date is within date range."""
if self.start <= maya.parse(pub_date) <= self.end:
# return f"#{self.name}{maya.now().year}"
return f"#{self.name}"
return ""
CONFERENCES = []
CONFERENCES.append(
Conference(
"Moriond",
maya.parse(f"{maya.now().year}-03-23"),
maya.parse(f"{maya.now().year}-04-11"),
)
)
CONFERENCES.append(
Conference(
"EPSHEP2023 EPSHEP23", maya.parse("2023-08-20"), maya.parse("2023-08-30")
)
)
CONFERENCES.append(
Conference("LeptonPhoton23", maya.parse("2023-07-16"), maya.parse("2023-07-26"))
)
CONFERENCES.append(
Conference("topq2023", maya.parse("2023-09-23"), maya.parse("2023-10-03"))
)
CONFERENCES.append(
Conference("HiggsCouplings", maya.parse("2019-09-29"), maya.parse("2019-10-06"))
)
CONFERENCES.append(
Conference("Higgs2023", maya.parse("2023-11-26"), maya.parse("2023-12-06"))
)
CONFERENCES.append(
Conference("QM2023", maya.parse("2023-09-01"), maya.parse("2023-09-11"))
)
CONFERENCES.append(
Conference("LHCP #LHCP2024", maya.parse("2024-06-01"), maya.parse("2024-06-10"))
)
CONFERENCES.append(
Conference("ICHEP2024", maya.parse("2024-07-16"), maya.parse("2024-07-26"))
)
CONFERENCES.append(
Conference("BOOST2024", maya.parse("2023-07-27"), maya.parse("2023-08-07"))
)
daiquiri.setup(level=logging.INFO)
logger = daiquiri.getLogger() # pylint: disable=invalid-name
def get_twitter_conn_v1(
api_key, api_secret, access_token, access_token_secret
) -> tweepy.API:
"""Get twitter conn 1.1"""
auth = tweepy.OAuth1UserHandler(api_key, api_secret)
auth.set_access_token(
access_token,
access_token_secret,
)
return tweepy.API(auth)
def get_twitter_conn_v2(
api_key, api_secret, access_token, access_token_secret
) -> tweepy.Client:
"""Get twitter conn 2.0"""
client = tweepy.Client(
consumer_key=api_key,
consumer_secret=api_secret,
access_token=access_token,
access_token_secret=access_token_secret,
)
return client
def read_feed(rss_url):
"""read the RSS feed and return dictionary"""
try:
response = requests.get(rss_url, timeout=10)
except requests.ReadTimeout:
logger.error("Timeout when reading RSS %s", rss_url)
return
# Turn stream into memory stream object for universal feedparser
content = BytesIO(response.content)
# Parse content
feed = feedparser.parse(content)
return feed
def read_html(html_url):
"""read the HTML page and return dictionary"""
try:
response = requests.get(html_url, timeout=10)
except requests.ReadTimeout:
logger.error("Timeout when reading HTML %s", html_url)
return
# Turn stream into memory stream object for universal feedparser
content = BytesIO(response.content)
# Parse content
# html = lh.fromstring(content)
html = lh.parse(content)
return html
def convert_to_unicode(text):
"""Convert some standard sub- and superscripts to unicode."""
# Check https://github.com/svenkreiss/unicodeit in the long run
unicode_text = text
unicode_text = unicode_text.replace("_S^0", "⁰_S ")
unicode_text = unicode_text.replace("^0_S", "⁰_S ")
# s quarks
unicode_text = unicode_text.replace("_(s)^0", "⁰_s ")
unicode_text = unicode_text.replace("^0_(s)", "⁰_s ")
unicode_text = unicode_text.replace("_s^*±", "*^±_s ")
unicode_text = unicode_text.replace("_s^0", "⁰_s ")
unicode_text = unicode_text.replace("^0_s", "⁰_s ")
unicode_text = unicode_text.replace("_s^+", "⁺_s ")
unicode_text = unicode_text.replace("^+_s", "⁺_s ")
unicode_text = unicode_text.replace("_s^-", "⁻_s ")
unicode_text = unicode_text.replace("^-_s", "⁻_s ")
unicode_text = unicode_text.replace("_s^±", "^±_s ")
# b quarks
unicode_text = unicode_text.replace("_b^*±", "*^±_b ")
unicode_text = unicode_text.replace("_b^0", "⁰_b ")
unicode_text = unicode_text.replace("^0_b", "⁰_b ")
unicode_text = unicode_text.replace("_b^+", "⁺_b ")
unicode_text = unicode_text.replace("^+_b", "⁺_b ")
unicode_text = unicode_text.replace("_b^-", "⁻_b ")
unicode_text = unicode_text.replace("^-_b", "⁻_b ")
unicode_text = unicode_text.replace("_b^±", "^±_b ")
# c quarks
unicode_text = unicode_text.replace("_c^*±", "*^±_c ")
unicode_text = unicode_text.replace("_c^0", "⁰_c ")
unicode_text = unicode_text.replace("^0_c", "⁰_c ")
unicode_text = unicode_text.replace("_c^+", "⁺_c ")
unicode_text = unicode_text.replace("^+_c", "⁺_c ")
unicode_text = unicode_text.replace("_c^-", "⁻_c ")
unicode_text = unicode_text.replace("^-_c", "⁻_c ")
unicode_text = unicode_text.replace("_c^±", "^±_c ")
# more complicated combinations
unicode_text = unicode_text.replace("_cc^+", "⁺_cc ")
unicode_text = unicode_text.replace("(770)^0", "⁰(770)")
unicode_text = unicode_text.replace("(892)^0", "⁰(892)")
unicode_text = unicode_text.replace("_c(4312)^+", "⁺_c(4312)")
unicode_text = unicode_text.replace("_c(4450)^+", "⁺_c(4450)")
unicode_text = unicode_text.replace("^-1", "⁻¹")
unicode_text = unicode_text.replace("^-2", "⁻²")
unicode_text = unicode_text.replace("^∗+", "*⁺")
unicode_text = unicode_text.replace("^+*", "⁺*")
unicode_text = unicode_text.replace("^∗-", "*⁻")
unicode_text = unicode_text.replace("^-*", "⁻*")
unicode_text = unicode_text.replace("^∗0", "*⁰")
unicode_text = unicode_text.replace("^0*", "⁰*")
unicode_text = unicode_text.replace("^*0", "*⁰")
unicode_text = unicode_text.replace("^*±", "*^±")
unicode_text = unicode_text.replace("^++", "⁺⁺")
unicode_text = unicode_text.replace("^+", "⁺")
unicode_text = unicode_text.replace("^--", "⁻⁻")
unicode_text = unicode_text.replace("^-", "⁻")
unicode_text = unicode_text.replace("_-", "₊")
unicode_text = unicode_text.replace("_-", "₋")
unicode_text = unicode_text.replace("^0", "⁰")
unicode_text = unicode_text.replace("_0", "₀")
unicode_text = unicode_text.replace("^*", "*")
# Remove parentheses for pp centre-of-mass energy
unicode_text = unicode_text.replace("√(s)", "√s")
return unicode_text
def format_title(title):
"""format the publication title"""
logger.info("Formatting title.")
logger.info(title)
title = title.replace("\\sqrt s", "\\sqrt{s}")
title = title.replace(" sqrts ", " \\sqrt{s} ")
title = title.replace(" \\bar{", "\\bar{")
title = title.replace("\\smash[b]", "")
title = title.replace("\\smash [b]", "")
title = title.replace("\\mbox{", "{")
title = title.replace("{\\rm ", "{")
title = title.replace("{\\rm\\scriptscriptstyle ", "{")
title = title.replace("\\kern -0.1em ", "")
title = title.replace("$~\\mathrm{", "~$\\mathrm{")
if re.search(r"rightarrow\S", title):
title = title.replace("rightarrow", "rightarrow ")
# fix overline without space
overline = re.search(r"overline\s([a-zA-Z])", title)
if overline:
title = title.replace(
f"overline {overline.group(1)}", "overline{%s}" % overline.group(1)
)
title = title.replace(" \\overline{", "\\overline{")
# overline{D} gives problems when in mathrm
title = title.replace("\\overline{D", "\\bar{D")
try:
text_title = LatexNodes2Text().latex_to_text(title)
except LatexWalkerError as identifier:
logger.error(identifier)
text_title = title
logger.debug(text_title)
# Convert some of remaining text to unicode
text_title = convert_to_unicode(text_title)
# insert spaces before and after the following characters
char_with_spaces = ["=", "→"]
for my_char in char_with_spaces:
pat = re.compile(r"\s?%s\s?" % my_char)
text_title = re.sub(pat, " %s " % my_char, text_title)
# insert space before eV/keV/MeV/GeV/TeV in case of wrong formatting
text_title = re.sub(r"(\d)([kMGT]?eV)", r"\1 \2", text_title)
# reduce all spaces to a maximum of one
text_title = re.sub(r"\s+", " ", text_title)
# reduce all underscores to a maximum of one
text_title = re.sub(r"_+", "_", text_title)
# reduce all hyphens to a maximum of one
text_title = re.sub(r"-+", "-", text_title)
# remove space before comma
text_title = text_title.replace(" ,", ",")
# merge s_NN
text_title = text_title.replace("s_ NN", "s_NN").strip()
return text_title
def execute_command(command):
"""execute shell command using subprocess..."""
proc = subprocess.Popen(
command,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True,
universal_newlines=True,
)
result = ""
exit_code = proc.wait()
if exit_code != 0:
for line in proc.stderr:
result = result + line
logger.error(result)
else:
for line in proc.stdout:
result = result + line
logger.debug(result)
def convert_gif_to_mp4(gif_path, output_path=None):
"""Convert GIF to MP4 video for BlueSky compatibility."""
if output_path is None:
output_path = gif_path.replace(".gif", ".mp4")
try:
command = (
f"ffmpeg -i {gif_path} -movflags faststart -pix_fmt yuv420p -vf "
f'"scale=trunc(iw/2)*2:trunc(ih/2)*2" -y {output_path}'
)
execute_command(command)
if os.path.exists(output_path) and os.path.getsize(output_path) > 0:
logger.info(f"Successfully converted {gif_path} to {output_path}")
return output_path
else:
logger.error(f"MP4 conversion failed or produced empty file for {gif_path}")
return None
except Exception as e:
logger.error(f"Error converting GIF to MP4: {e}")
return None
def process_images(
identifier, downloaded_image_list, post_gif, use_wand=True, platform="twitter"
):
"""Convert/resize all images to png."""
logger.info("Processing %d images." % len(downloaded_image_list))
logger.debug(
"process_images(): identifier = {}, downloaded_image_list = {},\
use_wand = {}".format(identifier, downloaded_image_list, use_wand)
)
image_list = []
images_for_gif = []
max_dim = [0, 0]
new_image_format = "png"
# also calculate average dimensions to scale down very large images
dim_list_x = []
dim_list_y = []
# first loop to find maximum PDF dimensions to have high quality images
for image_file in downloaded_image_list:
if use_wand:
# , resolution=300
try:
with Image(filename="{}[0]".format(image_file)) as img:
# process pdfs here only, others seem to be far too big
img.format = new_image_format
img.background_color = Color("white")
img.compression_quality = 85 # was 75
filename = image_file
img.alpha_channel = "remove"
img.trim(fuzz=0.01)
img.reset_coords() # equivalent of repage
# give the file a different name
filesplit = image_file.rsplit(".", 1)
filename = filesplit[0] + "_." + filesplit[1]
if filename.endswith("pdf"):
filename = filename.replace(".pdf", ".%s" % new_image_format)
# save image in list
image_list.append(filename)
img.save(filename=filename)
dim_list_x.append(img.size[0])
dim_list_y.append(img.size[1])
# need to save max dimensions for gif canvas
for i, _ in enumerate(max_dim):
if img.size[i] > max_dim[i]:
max_dim[i] = img.size[i]
except CorruptImageError as corrupt_except:
logger.error(
f"CorruptImageError: {corrupt_except} for file {image_file}"
)
logger.warning(f"Ignoring {image_file} due to CorruptImageError.")
except Exception as general_exception: # pylint: disable=broad-except
logger.error(
f"General exception processing image {image_file}: {general_exception}"
)
# rescale images
average_dims = (
float(sum(dim_list_x)) / max(len(dim_list_x), 1),
float(sum(dim_list_y)) / max(len(dim_list_y), 1),
)
dim_xy = int(
max(min(MAX_IMG_DIM, average_dims[0]), min(MAX_IMG_DIM, average_dims[0]))
)
# reset max_dim again
max_dim = [0, 0]
# scale individual images
for image_file in image_list:
if use_wand:
filename = image_file
with Image(filename=filename) as img:
# logger.debug(f"Initial dimensions for {filename}: {img.size[0]}x{img.size[1]}")
if (img.size[0] > dim_xy) or (img.size[1] > dim_xy):
scale_factor = dim_xy / float(max(img.size[0], img.size[1]))
area = scale_factor * scale_factor * img.size[0] * img.size[1]
logger.debug(
f"Scaling {filename}: dim_xy={dim_xy}, scale_factor={scale_factor:.2f}, area={area:.0f}, MAX_IMG_DIM_AREA={MAX_IMG_DIM_AREA}, original_size={img.size}"
)
if area > MAX_IMG_DIM_AREA:
scale_factor *= (
float(MAX_IMG_DIM_AREA / area) * 0.97
) # factor 0.97 accounts for additional margin below
img.resize(
int(img.size[0] * scale_factor), int(img.size[1] * scale_factor)
)
for i, _ in enumerate(max_dim):
if img.size[i] > max_dim[i]:
max_dim[i] = img.size[i]
img.save(filename=filename)
# bring list in order again
image_list = sorted(image_list)
if post_gif:
# now we need another loop to create the gif canvas
for image_file in image_list:
with Image(filename=image_file) as foreground:
foreground.format = "gif"
image_file = image_file.replace(".%s" % new_image_format, ".gif")
# foreground.transform(resize="{0}x{1}".format(*max_dim))
add_margin = 1.03
with Image(
width=int(max_dim[0] * add_margin),
height=int(max_dim[1] * add_margin),
background=Color("white"),
) as out:
left = int((max_dim[0] * add_margin - foreground.size[0]) / 2)
top = int((max_dim[1] * add_margin - foreground.size[1]) / 2)
out.composite(foreground, left=left, top=top)
out.save(filename=image_file)
images_for_gif.append(image_file)
img_size = MAX_IMG_SIZE + 1
# the gif can only have a certain size, so we loop until it's small enough
while img_size > MAX_IMG_SIZE:
command = "convert -delay 200 -loop 0 "
# command = "gifsicle --delay=120 --loop "
command += " ".join(images_for_gif)
command += " {id}/{id}.gif".format(id=identifier)
# command += ' > {id}/{id}.gif'.format(id=identifier)
execute_command(command)
img_size = os.path.getsize("{id}/{id}.gif".format(id=identifier))
if img_size > MAX_IMG_SIZE:
images_for_gif = images_for_gif[:-1]
logger.info(
"Image to big ({} bytes), dropping last figure, {} images in GIF".format(
img_size, len(images_for_gif)
)
)
# os.remove('{id}/{id}.gif'.format(id=identifier))
# replace image list by GIF only
image_list = ["{id}/{id}.gif".format(id=identifier)]
# For BlueSky platform, convert GIF to MP4
if platform == "bluesky":
gif_path = "{id}/{id}.gif".format(id=identifier)
mp4_path = convert_gif_to_mp4(gif_path)
if mp4_path and os.path.exists(mp4_path):
image_list = [mp4_path]
logger.info(f"Created MP4 for BlueSky: {mp4_path}")
else:
logger.warning(
"Failed to create MP4 for BlueSky, falling back to static images"
)
# Return individual PNG files instead
image_list = sorted(
[img for img in image_list if not img.endswith(".gif")]
)[:4]
return image_list
def twitter_auth(auth_dict):
"""Authenticate to twitter."""
twitter_client_v1 = None
twitter_client_v2 = None
if "CONSUMER_KEY" not in auth_dict:
return None
try:
twitter_client_v1 = get_twitter_conn_v1(
api_key=auth_dict["CONSUMER_KEY"],
api_secret=auth_dict["CONSUMER_SECRET"],
access_token=auth_dict["ACCESS_TOKEN"],
access_token_secret=auth_dict["ACCESS_TOKEN_SECRET"],
)
twitter_client_v2 = get_twitter_conn_v2(
api_key=auth_dict["CONSUMER_KEY"],
api_secret=auth_dict["CONSUMER_SECRET"],
access_token=auth_dict["ACCESS_TOKEN"],
access_token_secret=auth_dict["ACCESS_TOKEN_SECRET"],
)
except tweepy.TweepyException as tweepy_exception:
logger.error(f"Twitter v1/v2 auth error: {tweepy_exception}")
logger.error(f"Twitter client v1 state: {twitter_client_v1}")
logger.error(f"Twitter client v2 state: {twitter_client_v2}")
sys.exit(1)
return {"v1": twitter_client_v1, "v2": twitter_client_v2}
def mastodon_auth(auth_dict):
"""Authenticate to mastodon."""
mastodon_client = None
if "MASTODON_ACCESS_TOKEN" not in auth_dict:
return None
# Extract api_base_url from MASTODON_HANDLE
api_base_url = f"https://{auth_dict['MASTODON_BOT_HANDLE'].split('@')[-1]}/"
logger.info(
f"Using api_base_url: {api_base_url} for {auth_dict['MASTODON_BOT_HANDLE']}"
)
try:
mastodon_client = mastodon.Mastodon(
access_token=auth_dict["MASTODON_ACCESS_TOKEN"],
api_base_url=api_base_url,
)
except Exception as mastodon_exception: # pylint: disable=broad-except
logger.error(f"Mastodon auth error: {mastodon_exception}")
logger.error(f"Mastodon client state: {mastodon_client}")
sys.exit(1)
return mastodon_client
def bluesky_auth(auth_dict):
"""Authenticate to BlueSky."""
# Assuming atproto is installed, so direct check for credentials.
if "BLUESKY_HANDLE" not in auth_dict or "BLUESKY_APP_PASSWORD" not in auth_dict:
logger.info(
"BlueSky handle or app password not found in auth config. Skipping BlueSky."
)
return None
bluesky_client = None
try:
bluesky_client = BlueskyClient()
bluesky_client.login(
auth_dict["BLUESKY_HANDLE"], auth_dict["BLUESKY_APP_PASSWORD"]
)
logger.info(
f"Successfully logged into BlueSky as {auth_dict['BLUESKY_HANDLE']}"
)
except Exception as bluesky_exception:
logger.error(f"BlueSky auth error: {bluesky_exception}")
# We don't sys.exit here to allow other platforms to continue
return None
return bluesky_client
def load_config(experiment, feed_file, auth_file):
"""Load configs into dict."""
config_dict = {}
config = configparser.RawConfigParser()
# load the feed config
config.read(feed_file)
if experiment not in config.sections():
logger.error(f"Experiment {experiment} not found in {feed_file}")
config_dict["FEED_DICT"] = {}
for key in config[experiment]:
config_dict["FEED_DICT"][key.upper()] = config[experiment][key]
# now load the secrets
config.clear()
config.read(auth_file)
if experiment not in config.sections():
logger.error("Experiment {} not found in {}".format(experiment, auth_file))
config_dict["AUTH"] = {}
for key in config[experiment]:
config_dict["AUTH"][key.upper()] = config[experiment][key]
return config_dict
def twitter_upload_images(twitter, image_list, post_gif):
"""Upload images to twitter and return locations."""
logger.info("Uploading images to Twitter.")
image_ids = []
# loop over sorted images to get the plots in the right order
for image_path in sorted(image_list):
response = None
if post_gif:
if image_path.endswith("gif"):
try:
# while media_category="tweet_gif" should be used, this breaks the gif...
# response = twitter.media_upload(filename=image_path,
# media_category="tweet_gif")
response = twitter.media_upload(filename=image_path)
except tweepy.TweepyException as tweepy_exception:
logger.error(
f"Twitter GIF upload error for {image_path}: {tweepy_exception}"
)
logger.error(f"Response state: {response}")
sys.exit(1)
logger.info(response)
image_ids.append(response.media_id)
else:
try:
response = twitter.media_upload(filename=image_path)
except tweepy.TweepyException as tweepy_exception:
logger.error(
f"Twitter image upload error for {image_path}: {tweepy_exception}"
)
logger.error(f"Response state: {response}")
sys.exit(1)
logger.info(response)
image_ids.append(response.media_id)
logger.info(image_ids)
return image_ids
def mastodon_upload_images(mastodon_client, image_list, post_gif):
"""Upload images to Mastodon and return locations."""
logger.info("Uploading images to Mastodon.")
image_ids = []
# loop over sorted images to get the plots in the right order
for image_path in sorted(image_list):
if post_gif:
if image_path.endswith("gif"):
try:
response = mastodon_client.media_post(
media_file=image_path,
description=f"Animated GIF image for {image_path.split('/')[0]}",
)
except mastodon.MastodonError as mastodon_exception:
logger.error(
f"Mastodon: Failed to upload media {image_path}. Error: {mastodon_exception}"
)
raise mastodon_exception
logger.info(response)
image_ids.append(response.id)
else:
try:
response = mastodon_client.media_post(
media_file=image_path,
description=f"Image for {image_path.split('/')[0]}",
)
except mastodon.MastodonError as mastodon_exception:
logger.error(
f"Mastodon: Failed to upload media {image_path}. Error: {mastodon_exception}"
)
raise mastodon_exception
logger.info(response)
image_ids.append(response.id)
logger.info(image_ids)
return image_ids
def bluesky_upload_media(bluesky_client, media_list, identifier_for_alt_text):
"""Upload media (images or video) to BlueSky and return blob references."""
if not bluesky_client:
return []
logger.info("Uploading media to BlueSky.")
image_blobs = []
# If we have a video file (converted GIF), try to upload it first
mp4_files = [f for f in media_list if f.endswith(".mp4")]
if mp4_files:
video_path = mp4_files[0]
logger.info(f"Attempting to upload video file: {video_path}")
# Get video file size and other properties
file_size = os.path.getsize(video_path)
logger.info(f"Video file size: {file_size} bytes")
try:
with open(mp4_files[0], "rb") as f:
video_data = f.read()
blob_response = bluesky_client.com.atproto.repo.upload_blob(video_data)
logger.info(f"Blob upload response: {blob_response}")
alt_text = f"Video animation for {identifier_for_alt_text}"
# Create video embed
video_blob = atproto_models.AppBskyEmbedVideo.Main(
video=blob_response.blob, alt=alt_text
)
logger.info(f"Video blob: {video_blob}")
return [video_blob]
except Exception as e:
logger.error(f"Failed to upload video, falling back to images: {e}")
# Continue to image upload fallback
# Fallback: Upload up to 4 static images
for image_path in sorted(media_list)[:4]:
if image_path.endswith(".mp4"):
continue # Skip mp4 files in image processing
try:
with open(image_path, "rb") as f:
img_data = f.read()
alt_text = (
f"Image for {identifier_for_alt_text}: {os.path.basename(image_path)}"
)
# Truncate alt text if too long
max_alt_text_len = 500
if len(alt_text) > max_alt_text_len:
alt_text = alt_text[: max_alt_text_len - 3] + "..."
response = bluesky_client.com.atproto.repo.upload_blob(img_data)
image_blobs.append(
atproto_models.AppBskyEmbedImages.Image(
image=response.blob, alt=alt_text
)
)
logger.info(f"BlueSky: Uploaded {image_path}")
except Exception as e:
logger.error(f"BlueSky: Failed to upload media {image_path}. Error: {e}")
continue
return image_blobs
def detect_facets(text):
"""Detect URLs and hashtags in text and create facets for them."""
facets = []
# URL pattern
url_pattern = r"https?://[^\s]+"
# Hashtag pattern - matches # followed by word chars (excluding spaces)
hashtag_pattern = r"#[\w]+"
# Process URLs
for match in re.finditer(url_pattern, text):
start = len(text[: match.start()].encode("utf-8"))
end = len(text[: match.end()].encode("utf-8"))
url = text[match.start() : match.end()]
facet = {
"index": {"byteStart": start, "byteEnd": end},
"features": [{"$type": "app.bsky.richtext.facet#link", "uri": url}],
}
facets.append(facet)
# Process hashtags
for match in re.finditer(hashtag_pattern, text):
start = len(text[: match.start()].encode("utf-8"))
end = len(text[: match.end()].encode("utf-8"))
tag = text[match.start() + 1 : match.end()] # Remove the # symbol
facet = {
"index": {"byteStart": start, "byteEnd": end},
"features": [{"$type": "app.bsky.richtext.facet#tag", "tag": tag}],
}
facets.append(facet)
return facets if facets else None
def split_text(
type_hashtag,
title,
identifier,
link,
conf_hashtags,
phys_hashtags,
post_length,
bot_handle,
):
"""Split tweet into several including hashtags and URL in first one"""
# type_hashtag: aaa bbb ccc .. link conf_hashtags
# .. ddd eee (identifier)
logger.info("Splitting text ...")
message_list = []
# add length+1 if value set
length_link_and_tags = sum(
(len(x) > 0) + len(x) for x in [link, conf_hashtags, phys_hashtags]
)
remaining_text = f"{type_hashtag}: {title} ({identifier})"
first_message = True
while remaining_text:
message = remaining_text.lstrip()
allowed_length = post_length - length_link_and_tags
if not first_message:
allowed_length = post_length - len(bot_handle) - 3
message = bot_handle + " .." + message
if len(message) > allowed_length:
# strip message at last whitespace and account for 3 dots
cut_position = message[: allowed_length - 3].rfind(" ")
message = message[:cut_position]
remaining_text = remaining_text[cut_position:]
if cut_position + 3 > len(remaining_text):
message = message.strip() + ".."
else:
remaining_text = ""
if first_message:
message = " ".join(
filter(None, [message, link, conf_hashtags, phys_hashtags])
)
first_message = False
message_list.append(message)
logger.info(" '" + message + "'")
return message_list
def tweet(
twitter,
type_hashtag,
title,
identifier,
link,
conf_hashtags,
phys_hashtags,
image_ids,
post_gif,
bot_handle,
):
"""tweet the new results with title and link and pictures taking care of length limitations."""
# type_hashtag: title (identifier) link conf_hashtags
logger.info("Creating tweet ...")
# https://dev.twitter.com/rest/reference/get/help/configuration
tweet_allowed_length = 280
message_list = split_text(
type_hashtag,
title,
identifier,
link,
conf_hashtags,
phys_hashtags,
tweet_allowed_length,
bot_handle,
)
first_message = True
previous_status_id = None
response = {}
for i, message in enumerate(message_list):
logger.info(message)
logger.debug(len(message))
if "id" in response:
previous_status_id = response["id"]
if post_gif:
if first_message:
try:
if image_ids:
response = twitter.create_tweet(
text=message, media_ids=image_ids
)
else:
response = twitter.create_tweet(text=message)
except tweepy.TweepyException as tweepy_exception:
logger.error(
f"TweepyException during first message (GIF) tweet: {tweepy_exception}"
)
logger.error(f"Response state: {response}")
sys.exit(1)
first_message = False
logger.debug(response)
else:
try:
response = twitter.create_tweet(
text=message, in_reply_to_tweet_id=previous_status_id
)
except tweepy.TweepyException as tweepy_exception:
logger.error(
f"TweepyException during subsequent message (GIF) tweet: {tweepy_exception}"
)
logger.error(f"Response state: {response}")
return None
logger.debug(response)
else:
try:
if image_ids:
response = twitter.create_tweet(
text=message,
media_ids=image_ids[i * 4 : (i + 1) * 4],
in_reply_to_status_id=previous_status_id,
)
else:
response = twitter.create_tweet(
text=message,
in_reply_to_status_id=previous_status_id,
)
except tweepy.TweepyException as tweepy_exception:
logger.error(f"TweepyException during image tweet: {tweepy_exception}")
logger.error(f"Response state: {response}")
return None
logger.debug(response)
return response
def toot(
mastodon_client,
type_hashtag,
title,
identifier,
link,
conf_hashtags,
phys_hashtags,
image_ids,
post_gif,
bot_handle,
):
"""toot the new results with title and link and pictures taking care of length limitations."""
# type_hashtag: title (identifier) link conf_hashtags
logger.info("Creating toot ...")
toot_allowed_length = 500
message_list = split_text(
type_hashtag,
title,
identifier,
link,
conf_hashtags,
phys_hashtags,
toot_allowed_length,
bot_handle,
)
first_message = True
previous_status_id = None
response = {}
for i, message in enumerate(message_list):
logger.info(message)
logger.debug(len(message))
if "id" in response:
previous_status_id = response["id"]
if post_gif:
if first_message:
try:
if image_ids:
response = mastodon_client.status_post(
status=message, media_ids=image_ids
)
else:
response = mastodon_client.status_post(status=message)
except mastodon.MastodonError as mastodon_exception:
logger.error(
f"MastodonError during first message (GIF) toot: {mastodon_exception}"
)
logger.error(f"Response state: {response}")
return None
first_message = False
logger.debug(response)
else:
try:
response = mastodon_client.status_post(
status=message, in_reply_to_id=previous_status_id
)
except mastodon.MastodonError as mastodon_exception:
logger.error(
f"MastodonError during subsequent message (GIF) toot: {mastodon_exception}"
)
logger.error(f"Response state: {response}")
return None
logger.debug(response)
else:
try:
if image_ids:
response = mastodon_client.status_post(
status=message,
media_ids=image_ids[i * 4 : (i + 1) * 4],
in_reply_to_id=previous_status_id,
)
else:
response = mastodon_client.status_post(
status=message,
in_reply_to_id=previous_status_id,
)
except mastodon.MastodonError as mastodon_exception:
logger.error(f"MastodonError during image toot: {mastodon_exception}")
logger.error(f"Response state: {response}")
return None
logger.debug(response)
return response
def skeet(
bluesky_client,
type_hashtag,
title,
identifier,
link,
conf_hashtags,
phys_hashtags,
image_blobs, # List of blob objects from bluesky_upload_images
bot_handle,
previous_skeet_ref=None, # StrongRef of the previous skeet in a thread
root_skeet_ref=None, # StrongRef of the root skeet in a thread
):
"""Post (skeet) the new results to BlueSky."""
if (
not bluesky_client
or BlueskyClient is None
or atproto_models is None
or BlueskyAtpApiError is None
):