-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathx.py
190 lines (134 loc) · 4.83 KB
/
x.py
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
from os import environ
from time import sleep
from unicodedata import normalize
from emoji import analyze, EmojiMatch
from pytwitter import Api
from pytwitter.models import Tweet
import requests
from streamlit.runtime.uploaded_file_manager import UploadedFile
MAX_WEIGHTED_TWEET_LENGTH = 280
x_api = Api(
consumer_key=environ["X_CONSUMER_KEY"],
consumer_secret=environ["X_CONSUMER_SECRET"],
access_token=environ["X_ACCESS_TOKEN"],
access_secret=environ["X_ACCESS_TOKEN_SECRET"],
)
def get_character_weight(char: str | EmojiMatch) -> int:
if isinstance(char, EmojiMatch):
return 2
weight_one_ranges = [
(0, 4351),
(8192, 8205),
(8208, 8223),
(8242, 8247),
]
char_code_point = ord(char)
for range_start, range_end in weight_one_ranges:
if range_start <= char_code_point <= range_end:
return 1
return 2 # Default weight
def calculate_weighted_tweet_length(text: str) -> int:
normalized_text = normalize("NFC", text)
weighted_length = 0
for _, char in analyze(normalized_text, non_emoji=True):
weighted_length += get_character_weight(char)
return weighted_length
CONT_SUFFIX = " (cont.)"
WEIGHTED_CONT_SUFFIX_LENGTH = calculate_weighted_tweet_length(CONT_SUFFIX)
MAX_WEIGHTED_TWEET_LENGTH_WITHOUT_SUFFIX = (
MAX_WEIGHTED_TWEET_LENGTH - WEIGHTED_CONT_SUFFIX_LENGTH
)
SPACE_WEIGHT = get_character_weight(" ")
def threadify_tweet(text: str) -> list[str]:
parts = []
part = ""
weighted_part_length = 0
for token in text.split():
weighted_token_length = calculate_weighted_tweet_length(token)
weighted_part_length += weighted_token_length
if part:
weighted_part_length += SPACE_WEIGHT
if weighted_part_length <= MAX_WEIGHTED_TWEET_LENGTH_WITHOUT_SUFFIX:
if part:
part = f"{part} {token}"
else:
part = token
else:
parts.append(part + CONT_SUFFIX)
part = token
weighted_part_length = weighted_token_length
if part:
if weighted_part_length == WEIGHTED_CONT_SUFFIX_LENGTH:
parts[-1] = f"{parts[-1][:-WEIGHTED_CONT_SUFFIX_LENGTH]} {part}"
else:
parts.append(part)
return parts
CHUNK_SIZE_IN_BYTES = 1024 * 1024 // 2
def upload_images(images: list[UploadedFile]) -> list[str]:
media_ids = []
for image in images:
media_id = x_api.upload_media_chunked_init(
image.size, image.type, "tweet_image"
).media_id_string
image.seek(0)
segment_index = 0
while chunk := image.read(CHUNK_SIZE_IN_BYTES):
x_api.upload_media_chunked_append(media_id, segment_index, chunk)
segment_index += 1
processing_info = x_api.upload_media_chunked_finalize(media_id).processing_info
if processing_info:
while processing_info.state != "succeeded":
sleep(processing_info.check_after_secs)
processing_info = x_api.upload_media_chunked_status(
media_id
).processing_info
if processing_info.state == "failed":
raise Exception("Image upload failed")
media_ids.append(media_id)
return media_ids
def create_thread(
text: str | None = None,
media_ids: list[str] | None = None,
quote_tweet_id: str | None = None,
) -> list[Tweet]:
texts = threadify_tweet(text)
tweets = []
in_reply_to_tweet_id = None
for text in texts:
tweet = x_api.create_tweet(
text=text,
media_media_ids=media_ids,
quote_tweet_id=quote_tweet_id,
reply_in_reply_to_tweet_id=in_reply_to_tweet_id,
)
tweets.append(tweet)
in_reply_to_tweet_id = tweet.id
if media_ids:
media_ids = None
if quote_tweet_id:
quote_tweet_id = None
return tweets
def create_tweet(
text: str | None = None,
media_ids: list[str] | None = None,
quote_tweet_id: str | None = None,
) -> Tweet | list[Tweet]:
weighted_tweet_length = calculate_weighted_tweet_length(text)
if weighted_tweet_length > MAX_WEIGHTED_TWEET_LENGTH:
return create_thread(text, media_ids, quote_tweet_id)
return x_api.create_tweet(
text=text, media_media_ids=media_ids, quote_tweet_id=quote_tweet_id
)
OEMBED_RESOURCE_URL = "https://publish.twitter.com/oembed"
AUTHOR_URL = "https://twitter.com/ug_fess"
def is_valid_tweet_url(tweet_url: str) -> bool:
response = requests.get(
OEMBED_RESOURCE_URL,
{"url": tweet_url},
headers={"Accept": "application/json"},
)
if response.status_code == 404:
return False
response.raise_for_status()
oembed_data = response.json()
return oembed_data["author_url"] == AUTHOR_URL