-
Notifications
You must be signed in to change notification settings - Fork 1
/
youtube.py
281 lines (242 loc) ยท 13.5 KB
/
youtube.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
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
import os, re
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.base")
import django
django.setup()
import argparse
import pandas as pd
from slack_sdk import WebClient
from django.db import IntegrityError
from googleapiclient.discovery import build
from youtube.models import YouTube
from search.models import Ingredients
class YouTubes():
def __init__(self):
DEVELOPER_KEY = os.getenv('DEVELOPER_KEY')
YOUTUBE_API_SERVICE_NAME='youtube'
YOUTUBE_API_VERSION='v3'
self.youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
def ingredients(self, channel_name):
ingredient_dict = {}
ingredient_list = []
target_description = None
if channel_name == '๋ฐฑ์ข
์':
objs = YouTube.objects.filter(channel_id="UCyn-K7rZLXjGl7VXGweIlcA").values_list('url_pk', 'description')
elif channel_name == '์์ทจ์๋ฆฌ์ ':
objs = YouTube.objects.filter(channel_id="UCC9pQY_uaBSa0WOpMNJHbEQ").values_list('url_pk', 'description')
for obj in objs:
description = obj[1].split("\n")
url_pk = obj[0]
for ingredient in description:
if '[ ์ฌ๋ฃ ]' in ingredient or '[์ฌ๋ฃ]' in ingredient:
target_description = ingredient
if target_description:
index = description.index(target_description)
for i in range(index+1, len(description)):
#! description ์ ๋ด๋ถ ๋ก์ง์ ๋ค๋ฉด์ ํน์ ๋ฌธ์์ด์ด ๋์จ๋ค๋ฉด break ํด์ ์ฌ๋ฃ ๋ฐ์ดํฐ๋ง ์ถ์ถ
if description[i] == '':
break
if description[i].startswith('['):
break
if description[i].startswith('[ ๋ง๋๋ ๋ฒ ]'):
break
if description[i].startswith('[๋ง๋๋ ๋ฒ]'):
break
if description[i].startswith('*'):
break
if description[i] == '*':
break
#! ์์์ ์ฌ๋ฃ ๋ฐ์ดํฐ๋ฅผ 1์ฐจ ํํฐ๋ง์ ํ๋ค๋ฉด, ์ฌ๋ฃ ๋ฐ์ดํฐ์ ๋ถํ์ํ ์ฌ๋ฃ ๋ฐ์ดํฐ๊ฐ ๋ค์ด๊ฐ ์๋ค๋ฉด 2์ฐจ ํํฐ๋ง
ingredient = re.sub(r'[|[a-zA-Z]|[0-9]|[์ฝ์ปตํฐ์ ๊ฐ๋ณ์คํผ์ ํ์ฌ๋ฃ๊ฐ์ข
๋ด๋๊ป์๋ํฉ/()+ยฝยผยพ~ .-]|]', '', description[i])
if '์์ผ๋ฉด' in ingredient:
ingredient = re.sub(r'์์ผ๋ฉด', '', ingredient)
if '์๋ต๊ฐ๋ฅ' in ingredient:
ingredient = re.sub(r'์๋ต๊ฐ๋ฅ', '', ingredient)
if '์ฌ์ด์ฆ๋์ผ๋ฐ์ด์
๋๋ค' in ingredient:
ingredient = re.sub(r'์ฌ์ด์ฆ๋์ผ๋ฐ์ด์
๋๋ค', '', ingredient)
if 'ํฌ๊ธฐ' in ingredient:
ingredient = re.sub(r'ํฌ๊ธฐ', '', ingredient)
if '์ฉ๊ธฐ' in ingredient:
ingredient = re.sub(r'์ฉ๊ธฐ', '', ingredient)
if '๊ณต๊ธฐ' in ingredient:
ingredient = re.sub(r'๊ณต๊ธฐ', '', ingredient)
if '๊ฐ์๋ง๋ ๋ฐฐ์' in ingredient:
ingredient = re.sub(r'๊ฐ์๋ง๋ ๋ฐฐ์', '', ingredient)
if 'ํ์ค' in ingredient:
ingredient = re.sub(r'ํ์ค', '', ingredient)
if '-์ก์ ์๋ฌด๊ฑฐ๋' in ingredient:
ingredient = re.sub(r'-์ก์ ์๋ฌด๊ฑฐ๋', '', ingredient)
if 'ํน์' in ingredient:
ingredient = re.sub(r'ํน์', '', ingredient)
if '์ ์๋ ์ธ์ง์ฉ๊ธฐ' in ingredient:
ingredient = re.sub(r'์ ์๋ ์ธ์ง์ฉ๊ธฐ', '', ingredient)
if (len(ingredient) > 2 and ingredient[-1] == '๊ณผ') or (len(ingredient) > 2 and ingredient[-1] == '๋') or (len(ingredient) > 3 and ingredient[-1] == '๊ฐ'):
ingredient = re.sub(r'.$', '', ingredient)
if (len(ingredient) > 3 and ingredient[-1] == '์ฅ') or (len(ingredient) > 3 and ingredient[-1] == '์'):
ingredient = re.sub(r'(์ฅ|์)$', '', ingredient)
#! '์์ทจ์๋ฆฌ์ '์ ๊ฒฝ์ฐ์ ์ฌ๋ฃ ์ ๋ณด๊ฐ ์ค ๋ฐ๊ฟ ์์ด ๋ฌธ์์ด "๋๋ถ, ์๋๋ถ, ๊น์น" ์ด๋ฐ์์ผ๋ก ๋์ด ์๊ธฐ ๋๋ฌธ์ list ํํ๋ก ๋ณ๊ฒฝํ๊ณ for๋ฌธ์ผ๋ก ์ฌ๋ฃ ๋ฐ์ดํฐ ์ถ์ถ
if channel_name == '์์ทจ์๋ฆฌ์ ':
ingredient = ingredient.split(',')
for i in ingredient:
ingredient_dict = dict(url_pk=url_pk, name=i)
ingredient_list.append(ingredient_dict)
else:
ingredient_dict = dict(url_pk=url_pk, name=ingredient)
ingredient_list.append(ingredient_dict)
else:
pass
#* 1. ๊ฒ์ฆ ๋ ์ฌ๋ฃ๋ฐ์ดํฐ(ingredient_list) ๋ฅผ ๊ฐ์ ธ์์ Ingredient Model ์ ์ ์ฅํ๋ค.
obj_list = [Ingredients(name=info['name'], is_valid=False) for info in ingredient_list]
try:
Ingredients.objects.bulk_create(obj_list, ignore_conflicts=True)
except IntegrityError:
pass
#* 2. Ingredient Model ์ด ์ ์ฅ๋์๊ณ ,
#* Ingredient(obj) ์ ๊ฐ์ ๊ธฐ์ค์ผ๋ก YouTube Model ๋งค์นญ๋๋ ๊ฐ์ m2m ์ผ๋ก ์ฐ๊ฒฐํ๋ค.
obj_ingredients = Ingredients.objects.all()
for obj_i in obj_ingredients:
obj_y = YouTube.objects.filter(description__contains=obj_i.name)
obj_i.youtube.set(obj_y)
def paik_jong_won(self):
response_channel = self.youtube.search().list(
channelId="UCyn-K7rZLXjGl7VXGweIlcA", # ์ฑ๋ ๊ฒ์
part="snippet",
maxResults=50,
).execute()
channel_id = response_channel['items'][0]['snippet']['channelId']
video_list = []
playlists = self.youtube.playlists().list(
channelId=channel_id,
part='snippet',
maxResults=20
).execute()
# * ๋ด๊ฐ ํ์ํ ์ฟ ํน๋ก๊ทธ ๋ฐ์ดํฐ๋ [10] ์ ์์นํด ์๋ค.
cooking_log_ids = playlists['items'][10]['id']
request = self.youtube.playlistItems().list(
part="snippet,contentDetails",
playlistId=cooking_log_ids,
maxResults=50
)
next_page = True
while next_page:
response = request.execute()
data = response['items']
for video in data:
video_id = video['contentDetails']['videoId']
# * video_id ๋ฅผ ์ค๋ณต์์ด video_list ์ ์ฝ์
ํ๋ค.
if video_id not in video_list:
video_list.append(video_id)
# Do we have more pages?
if 'nextPageToken' in response.keys():
next_page = True
request = self.youtube.playlistItems().list(
part="snippet,contentDetails",
playlistId=cooking_log_ids,
pageToken=response['nextPageToken'], # * google-api-python-client ์์ ์ง์ํ๋ nextPageToken
maxResults=50
)
else:
next_page = False # * 'nextPageToken' in response.keys() ๊ฐ ์๋ค๋ฉด End
stats_list = []
# * 0~50 ๊น์ง์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์จ๋ค. 323๊ฐ์ ๋ฐ์ดํฐ ๊น์ง 6๋ฒ ๋ฐ๋ณต
for i in range(0, len(video_list), 50):
response_videos = self.youtube.videos().list(
part="snippet,contentDetails,statistics",
id=video_list[i:i+50]
).execute()
# ! ๋ฐฑ์ข
์
for video in response_videos['items']:
url_pk=video['id']
channel_id=video['snippet']['channelId'] # 'UCyn-K7rZLXjGl7VXGweIlcA'
title=video['snippet']['title']
description=video['snippet']['description']
thumbnails=video['snippet']['thumbnails']['high']['url']
view_count=video['statistics'].get('viewCount',0)
like_count=video['statistics'].get('likeCount',0)
published=video['snippet']['publishedAt']
play_time=video['contentDetails']['duration'].strip('PT, S').replace('M', ':')
stats_dict=dict(url_pk=url_pk, channel_id=channel_id, title=title, description=description, thumbnails=thumbnails, published=published, play_time=play_time, view_count=view_count, like_count=like_count)
stats_list.append(stats_dict)
df=pd.DataFrame(stats_list)
df.to_csv("/home/ubuntu/code/cancook-backend/csv/๋ฐฑ์ข
์_์ฟ ํน๋ก๊ทธ.csv", index=False)
# df.to_csv("/Users/cslee/vscode/self-dining-backend/csv/๋ฐฑ์ข
์_์ฟ ํน๋ก๊ทธ.csv", index=False)
obj_list = [YouTube(**data) for data in stats_list] # YouTube(**data) YouTube Object = ORM
try:
YouTube.objects.bulk_create(objs=obj_list)
count = YouTube.objects.filter(channel_id='UCyn-K7rZLXjGl7VXGweIlcA').count()
client.chat_postMessage(
channel="youtube",
text=f"๋ฐฑ์ข
์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋๋ฐ ์ฑ๊ณตํ์ต๋๋ค.\nํ์ ๋ฐ์ดํฐ: {count} :tada: "
)
except IntegrityError:
client.chat_postMessage(
channel="youtube",
text=f"๋ฐฑ์ข
์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋๋ฐ ์คํจํ์ต๋๋ค.\nํ์ ๋ฐ์ดํฐ: {count} :red_circle: "
)
def simple_cooking(self):
stats_dict = {}
stats_list = []
next_page_token = None
while True:
res = self.youtube.search().list(
part='id',
channelId='UCC9pQY_uaBSa0WOpMNJHbEQ',
maxResults=50,
pageToken=next_page_token,
type='video'
).execute()
video_ids = []
for item in res['items']:
video_ids.append(item['id']['videoId'])
# API๋ฅผ ์ฌ์ฉํ์ฌ ๋์์์ ์ ๋ณด๋ฅผ ๊ฐ์ ธ์ต๋๋ค.
video_details_res = self.youtube.videos().list(
part='id,snippet,statistics,contentDetails',
id=','.join(video_ids),
maxResults=50,
).execute()
# ! ์์ทจ์๋ฆฌ์
for video in video_details_res['items']:
url_pk=video['id']
channel_id=video['snippet']['channelId'] # 'UCC9pQY_uaBSa0WOpMNJHbEQ'
title=video['snippet']['title']
description=video['snippet']['description']
thumbnails=video['snippet']['thumbnails']['high']['url']
view_count=video['statistics'].get('viewCount',0)
like_count=video['statistics'].get('likeCount',0)
published=video['snippet']['publishedAt']
play_time=video['contentDetails']['duration'].strip('PT, S').replace('M', ':')
stats_dict=dict(url_pk=url_pk, channel_id=channel_id, title=title, description=description, thumbnails=thumbnails, published=published, play_time=play_time, view_count=view_count, like_count=like_count)
stats_list.append(stats_dict)
next_page_token = res.get('nextPageToken')
if next_page_token is None:
break
df=pd.DataFrame(stats_list)
df.to_csv("/home/ubuntu/code/cancook-backend/csv/์์ทจ์๋ฆฌ์ .csv", index=False)
# df.to_csv("/Users/cslee/vscode/self-dining-backend/csv/์์ทจ์๋ฆฌ์ .csv", index=False)
obj_list = [YouTube(**data) for data in stats_list] # YouTube(**data) YouTube Object = ORM
try:
YouTube.objects.bulk_create(objs=obj_list)
count = YouTube.objects.filter(channel_id='UCC9pQY_uaBSa0WOpMNJHbEQ').count()
client.chat_postMessage(
channel="youtube",
text=f"์์ทจ์๋ฆฌ์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋๋ฐ ์ฑ๊ณตํ์ต๋๋ค.\nํ์ ๋ฐ์ดํฐ: {count} :tada: "
)
except IntegrityError:
client.chat_postMessage(
channel="youtube",
text=f"์์ทจ์๋ฆฌ์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ค๋๋ฐ ์คํจํ์ต๋๋ค.\nํ์ ๋ฐ์ดํฐ: {count} :red_circle: "
)
if __name__ == '__main__':
slack_token = os.getenv('SLACK_TOKEN')
client = WebClient(token=slack_token)
parser = argparse.ArgumentParser(description='you must choose ๋ฐฑ์ข
์ and ์์ทจ์๋ฆฌ์ ')
parser.add_argument('-c', '--channel')
args = parser.parse_args()
y = YouTubes()
if args.channel == '๋ฐฑ์ข
์':
y.paik_jong_won()
elif args.channel == '์์ทจ์๋ฆฌ์ ':
y.simple_cooking()
elif args.channel == '๋ฐฑ์ข
์_์ฌ๋ฃ':
y.ingredients(channel_name='๋ฐฑ์ข
์')
elif args.channel == '์์ทจ์๋ฆฌ์ _์ฌ๋ฃ':
y.ingredients(channel_name='์์ทจ์๋ฆฌ์ ')