Merge branch 'main' into scraper-poc
This commit is contained in:
commit
ba26284451
95 files changed
+24175
-22969
No files matched your search
Vendored
BIN
Binary file not shown.
@@ -0,0 +1,29 @@
|
||||
import asyncio
|
||||
from nvMapScraper import nvMapScraper
|
||||
from nvMapPwScraper import nvMapPwScraper
|
||||
|
||||
async def main_function():
|
||||
await nvMapPwScraper.initiate_scraper()
|
||||
selected = {'title': '<b>스테이</b>,<b>머뭄</b>',
|
||||
'link': 'https://www.instagram.com/staymeomoom',
|
||||
'category': '숙박>펜션',
|
||||
'description': '',
|
||||
'telephone': '',
|
||||
'address': '전북특별자치도 군산시 신흥동 63-18',
|
||||
'roadAddress': '전북특별자치도 군산시 절골길 18',
|
||||
'mapx': '1267061254',
|
||||
'mapy': '359864175',
|
||||
'lng': 126.7061254,
|
||||
'lat': 35.9864175}
|
||||
|
||||
async with nvMapPwScraper() as pw_scraper:
|
||||
new_url = await pw_scraper.get_place_id_url(selected)
|
||||
|
||||
print(new_url)
|
||||
nv_scraper = nvMapScraper(new_url) # 이후 동일한 플로우
|
||||
await nv_scraper.scrap()
|
||||
print(nv_scraper.rawdata)
|
||||
return
|
||||
|
||||
print("running main_funtion..")
|
||||
asyncio.run(main_function())
|
||||
@@ -0,0 +1,113 @@
|
||||
import asyncio
|
||||
from playwright.async_api import async_playwright
|
||||
from urllib import parse
|
||||
|
||||
class nvMapPwScraper():
|
||||
# cls vars
|
||||
is_ready = False
|
||||
_playwright = None
|
||||
_browser = None
|
||||
_context = None
|
||||
_win_width = 1280
|
||||
_win_height = 720
|
||||
_max_retry = 30 # place id timeout threshold seconds
|
||||
|
||||
# instance var
|
||||
page = None
|
||||
|
||||
@classmethod
|
||||
def default_context_builder(cls):
|
||||
context_builder_dict = {}
|
||||
context_builder_dict['viewport'] = {
|
||||
'width' : cls._win_width,
|
||||
'height' : cls._win_height
|
||||
}
|
||||
context_builder_dict['screen'] = {
|
||||
'width' : cls._win_width,
|
||||
'height' : cls._win_height
|
||||
}
|
||||
context_builder_dict['user_agent'] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36"
|
||||
context_builder_dict['locale'] = 'ko-KR'
|
||||
context_builder_dict['timezone_id']='Asia/Seoul'
|
||||
|
||||
return context_builder_dict
|
||||
|
||||
@classmethod
|
||||
async def initiate_scraper(cls):
|
||||
if not cls._playwright:
|
||||
cls._playwright = await async_playwright().start()
|
||||
if not cls._browser:
|
||||
cls._browser = await cls._playwright.chromium.launch(headless=True)
|
||||
if not cls._context:
|
||||
cls._context = await cls._browser.new_context(**cls.default_context_builder())
|
||||
cls.is_ready = True
|
||||
|
||||
def __init__(self):
|
||||
if not self.is_ready:
|
||||
raise Exception("nvMapScraper is not initiated")
|
||||
|
||||
async def __aenter__(self):
|
||||
await self.create_page()
|
||||
return self
|
||||
|
||||
async def __aexit__(self, exc_type, exc, tb):
|
||||
await self.page.close()
|
||||
|
||||
async def create_page(self):
|
||||
self.page = await self._context.new_page()
|
||||
await self.page.add_init_script(
|
||||
'''const defaultGetter = Object.getOwnPropertyDescriptor(
|
||||
Navigator.prototype,
|
||||
"webdriver"
|
||||
).get;
|
||||
defaultGetter.apply(navigator);
|
||||
defaultGetter.toString();
|
||||
Object.defineProperty(Navigator.prototype, "webdriver", {
|
||||
set: undefined,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: new Proxy(defaultGetter, {
|
||||
apply: (target, thisArg, args) => {
|
||||
Reflect.apply(target, thisArg, args);
|
||||
return false;
|
||||
},
|
||||
}),
|
||||
});
|
||||
const patchedGetter = Object.getOwnPropertyDescriptor(
|
||||
Navigator.prototype,
|
||||
"webdriver"
|
||||
).get;
|
||||
patchedGetter.apply(navigator);
|
||||
patchedGetter.toString();''')
|
||||
|
||||
await self.page.set_extra_http_headers({
|
||||
'sec-ch-ua': '\"Not?A_Brand\";v=\"99\", \"Chromium\";v=\"130\"'
|
||||
})
|
||||
await self.page.goto("http://google.com")
|
||||
|
||||
async def goto_url(self, url, wait_until="domcontentloaded", timeout=20000):
|
||||
page = self.page
|
||||
await page.goto(url, wait_until=wait_until, timeout=timeout)
|
||||
|
||||
async def get_place_id_url(self, selected):
|
||||
|
||||
title = selected['title'].replace("<b>", "").replace("</b>", "")
|
||||
address = selected.get('roadAddress', selected['address']).replace("<b>", "").replace("</b>", "")
|
||||
encoded_query = parse.quote(f"{address} {title}")
|
||||
url = f"https://map.naver.com/p/search/{encoded_query}"
|
||||
|
||||
await self.goto_url(url, wait_until="networkidle",timeout = self._max_retry/2*1000)
|
||||
|
||||
if "/place/" in self.page.url:
|
||||
return self.page.url
|
||||
|
||||
url = self.page.url.replace("?","?isCorrectAnswer=true&")
|
||||
await self.goto_url(url, wait_until="networkidle",timeout = self._max_retry/2*1000)
|
||||
|
||||
if "/place/" in self.page.url:
|
||||
return self.page.url
|
||||
|
||||
if (count == self._max_retry / 2):
|
||||
raise Exception("Failed to identify place id. loading timeout")
|
||||
else:
|
||||
raise Exception("Failed to identify place id. item is ambiguous")
|
||||
@@ -0,0 +1,119 @@
|
||||
import re
|
||||
import aiohttp
|
||||
import json
|
||||
import asyncio
|
||||
import bs4
|
||||
|
||||
PLACE_PATTERN = r"/place/(\d+)"
|
||||
GRAPHQL_URL = "https://pcmap-api.place.naver.com/graphql"
|
||||
NAVER_COOKIES="NAC=mQ7mBownbQf4A; NNB=TQPII6AKDBFGQ; PLACE_LANGUAGE=ko; NACT=1; nid_inf=1431570813; NID_AUT=k2T7FraXOdIMRCHzEZIFtHQup+I7b87M5fd7+p65AXZTdGB/gelRmW8s/Q4oDxm8; tooltipDisplayed=true; SRT30=1762660151; NID_SES=AAAB1Lpy3y3hGzuPbJpJl8vvFx18C+HXXuZEFou/YPgocHe7k2/5MpFlgE48X1JF7c7IPoU2khZKkkuLx+tsvWAzOf0TnG/G8RrBGeawnSluSJcKcTdKKRJ4cygKc/OabVxoc3TNZJWxer3vFtXBoXkDS5querVNS6wvcMhA/p4vkPKOeepwKLR+1IJERlQJWZw4q29IdAysrbBNn3Akf9mDA5eTYvMDLYyRkToRh10TVMW/yhyNQeMXlIdnR8U1ZCNqe/9ErYdos5gQDstswEJQQA0T2cHFGJOtmlYMPlnhWado5w521iZXGJyKcA9ZawizM/i5nK5xNYtPGS3cvImUYl6B5ulIipUJSqpj8v2XstK0TZlOGxHToXaVDrCNmSfCA9vFYbTb6xJHB2JRAT3Jik/z6QgLjJLBWRnsucMDqldxoiEDAUHEhY3pjgZ89quR3c3hwAuTlI9hBn5I3e5VQR0Y/GxoS9mIkMF8pJmcGneqnE0BNIt91RN6Se5rDM69B+JWppBXtSir1JGuXADaRLLMP8VlxJX949iH0UYTKWKsrD4OgNNK5aUx24nAH494WPknBMlx4fCMIeWzy7K3sEZkNUn/+A+eHraqIFfbGpveSCNM+8EqEjMgA+YRgg3eig==; _naver_usersession_=Kkgzim/64JicPJzgkIIvqQ==; page_uid=jesTPsqVWUZssE4qJeossssssD0-011300; SRT5=1762662010; BUC=z5Fu3sAYtFwpbRDrrDFYdn4AgK5hNkOqX-DdaLU7VJM="
|
||||
|
||||
OVERVIEW_QUERY = '''
|
||||
query getAccommodation($id: String!, $deviceType: String) {
|
||||
business: placeDetail(input: {id: $id, isNx: true, deviceType: $deviceType}) {
|
||||
base {
|
||||
id
|
||||
name
|
||||
category
|
||||
roadAddress
|
||||
address
|
||||
phone
|
||||
virtualPhone
|
||||
microReviews
|
||||
conveniences
|
||||
visitorReviewsTotal
|
||||
}
|
||||
images { images { origin url } }
|
||||
cpImages(source: [ugcImage]) { images { origin url } }
|
||||
}
|
||||
}'''
|
||||
|
||||
REQUEST_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
|
||||
"Referer": "https://map.naver.com/",
|
||||
"Origin": "https://map.naver.com",
|
||||
"Content-Type": "application/json",
|
||||
"Cookie": NAVER_COOKIES
|
||||
}
|
||||
|
||||
class GraphQLException(Exception):
|
||||
pass
|
||||
|
||||
class nvMapScraper():
|
||||
url : str = None
|
||||
scrap_type : str = None
|
||||
rawdata : dict = None
|
||||
image_link_list : list[str] = None
|
||||
base_info : dict = None
|
||||
|
||||
|
||||
def __init__(self, url):
|
||||
self.url = url
|
||||
|
||||
async def parse_url(self):
|
||||
if 'place' not in self.url:
|
||||
if 'naver.me' in self.url:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(self.url) as response:
|
||||
self.url = str(response.url)
|
||||
else:
|
||||
raise GraphQLException("this shorten url not have place id")
|
||||
try:
|
||||
place_id = re.search(PLACE_PATTERN, self.url)[1]
|
||||
except Exception as E:
|
||||
raise GraphQLException("Cannot find place id")
|
||||
|
||||
return place_id
|
||||
|
||||
async def scrap(self):
|
||||
try:
|
||||
place_id = await self.parse_url()
|
||||
data = await self.call_get_accomodation(place_id)
|
||||
self.rawdata = data
|
||||
fac_data = await self.get_facility_string(place_id)
|
||||
self.rawdata['facilities'] = fac_data
|
||||
self.image_link_list = [nv_image['origin'] for nv_image in data['data']['business']['images']['images']]
|
||||
self.base_info = data['data']['business']['base']
|
||||
self.facility_info = fac_data
|
||||
self.scrap_type = "GraphQL"
|
||||
|
||||
except GraphQLException as G:
|
||||
print (G)
|
||||
print("fallback")
|
||||
self.scrap_type = "Playwright"
|
||||
pass # 나중에 pw 이용한 crawling으로 fallback 추가
|
||||
|
||||
return
|
||||
|
||||
async def call_get_accomodation(self, place_id):
|
||||
payload = {
|
||||
"operationName" : "getAccommodation",
|
||||
"variables": { "id": place_id, "deviceType": "pc" },
|
||||
"query": OVERVIEW_QUERY,
|
||||
}
|
||||
json_payload = json.dumps(payload)
|
||||
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(GRAPHQL_URL, data=json_payload, headers=REQUEST_HEADERS) as response:
|
||||
response.encoding = 'utf-8'
|
||||
if response.status == 200: # 요청 성공
|
||||
return await response.json() # await 주의
|
||||
else: # 요청 실패
|
||||
print('실패 상태 코드:', response.status)
|
||||
print(response.text)
|
||||
raise Exception()
|
||||
|
||||
async def get_facility_string(self, place_id):
|
||||
url = f"https://pcmap.place.naver.com/accommodation/{place_id}/home"
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.get(url, headers=REQUEST_HEADERS) as response:
|
||||
soup = bs4.BeautifulSoup(await response.read(), 'html.parser')
|
||||
c_elem = soup.find('span', 'place_blind', string='편의')
|
||||
facilities = c_elem.parent.parent.find('div').string
|
||||
return facilities
|
||||
|
||||
# url = "https://naver.me/IgJGCCic"
|
||||
# scraper = nvMapScraper(url)
|
||||
# asyncio.run(scraper.scrap())
|
||||
# print(scraper.image_link_list)
|
||||
# print(len(scraper.image_link_list))
|
||||
+226
-226
@@ -1,226 +1,226 @@
|
||||
import copy
|
||||
|
||||
import requests
|
||||
|
||||
CREATOMATE_API_KEY = "df9e4382d7e84fe790bf8a2168152be195d5a3568524ceb66ed989a2dea809f7d3065d6803b2e3dd9d02b5e5ec1c9823"
|
||||
# ACCOUNT_URL = "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/"
|
||||
# Creatomate 템플릿 정보 전부 가져오기
|
||||
|
||||
|
||||
class Creatomate:
|
||||
base_url: str = "https://api.creatomate.com"
|
||||
|
||||
def __init__(self, api_key):
|
||||
self.api_key = api_key
|
||||
|
||||
def get_all_templates_data(self) -> dict:
|
||||
url = Creatomate.base_url + "/v1/templates"
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
response = requests.get(url, headers=headers)
|
||||
return response.json()
|
||||
|
||||
# Creatomate 템플릿 ID 로부터 해당 템플릿 정보 가져오기
|
||||
def get_one_template_data(self, template_id: str) -> dict:
|
||||
url = Creatomate.base_url + f"/v1/templates/{template_id}"
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
response = requests.get(url, headers=headers)
|
||||
return response.json()
|
||||
|
||||
# 템플릿 정보 파싱하여 리소스 이름 추출하기
|
||||
def parse_template_component_name(self, template_source: dict) -> dict:
|
||||
def recursive_parse_component(element: dict) -> dict:
|
||||
if "name" in element:
|
||||
result_element_name_type = {element["name"]: element["type"]}
|
||||
else:
|
||||
result_element_name_type = {}
|
||||
|
||||
if element["type"] == "composition":
|
||||
minor_component_list = [
|
||||
recursive_parse_component(minor) for minor in element["elements"]
|
||||
]
|
||||
for minor_component in minor_component_list: ## WARNING : Same name component should shroud other component. be aware
|
||||
result_element_name_type.update(minor_component)
|
||||
|
||||
return result_element_name_type
|
||||
|
||||
result = {}
|
||||
for result_element_dict in [
|
||||
recursive_parse_component(component) for component in template_source
|
||||
]:
|
||||
result.update(result_element_dict)
|
||||
|
||||
return result
|
||||
|
||||
# 템플릿 정보 이미지/가사/음악 리소스와 매핑하기
|
||||
# 이미지는 순차적으로 집어넣기
|
||||
# 가사는 개행마다 한 텍스트 삽입
|
||||
# Template에 audio-music 항목이 있어야 함. (추가된 템플릿 Cafe뿐임)
|
||||
def template_connect_resource_blackbox(
|
||||
self, template_id: str, image_url_list: list[str], lyric: str, music_url: str
|
||||
) -> dict:
|
||||
template_data = self.get_one_template_data(template_id)
|
||||
template_component_data = self.parse_template_component_name(
|
||||
template_data["source"]["elements"]
|
||||
)
|
||||
|
||||
lyric.replace("\r", "")
|
||||
lyric_splited = lyric.split("\n")
|
||||
modifications = {}
|
||||
for idx, (template_component_name, template_type) in enumerate(
|
||||
template_component_data.items()
|
||||
):
|
||||
match template_type:
|
||||
case "image":
|
||||
modifications[template_component_name] = image_url_list[
|
||||
idx % len(image_url_list)
|
||||
]
|
||||
case "text":
|
||||
modifications[template_component_name] = lyric_splited[
|
||||
idx % len(lyric_splited)
|
||||
]
|
||||
|
||||
modifications["audio-music"] = music_url
|
||||
|
||||
return modifications
|
||||
|
||||
def elements_connect_resource_blackbox(
|
||||
self, elements: list, image_url_list: list[str], lyric: str, music_url: str
|
||||
) -> dict:
|
||||
template_component_data = self.parse_template_component_name(elements)
|
||||
|
||||
lyric.replace("\r", "")
|
||||
lyric_splited = lyric.split("\n")
|
||||
modifications = {}
|
||||
for idx, (template_component_name, template_type) in enumerate(
|
||||
template_component_data.items()
|
||||
):
|
||||
match template_type:
|
||||
case "image":
|
||||
modifications[template_component_name] = image_url_list[
|
||||
idx % len(image_url_list)
|
||||
]
|
||||
case "text":
|
||||
modifications[template_component_name] = lyric_splited[
|
||||
idx % len(lyric_splited)
|
||||
]
|
||||
|
||||
modifications["audio-music"] = music_url
|
||||
|
||||
return modifications
|
||||
|
||||
def modify_element(self, elements: list, modification: dict):
|
||||
def recursive_modify(element: dict) -> dict:
|
||||
if "name" in element:
|
||||
match element["type"]:
|
||||
case "image":
|
||||
element["source"] = modification[element["name"]]
|
||||
case "audio":
|
||||
element["source"] = modification.get(element["name"], "")
|
||||
case "video":
|
||||
element["source"] = modification[element["name"]]
|
||||
case "text":
|
||||
element["source"] = modification.get(element["name"], "")
|
||||
case "composition":
|
||||
for minor in element["elements"]:
|
||||
recursive_modify(minor)
|
||||
|
||||
for minor in elements:
|
||||
recursive_modify(minor)
|
||||
|
||||
return elements
|
||||
|
||||
# Creatomate에 생성 요청
|
||||
# response에 요청 정보 있으니 풀링 필요
|
||||
def make_creatomate_call(self, template_id: str, modifications: dict):
|
||||
url = Creatomate.base_url + "/v2/renders"
|
||||
|
||||
data = {"template_id": template_id, "modifications": modifications}
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
|
||||
response = requests.post(url, json=data, headers=headers)
|
||||
return response
|
||||
|
||||
# Creatomate에 생성 요청 without template
|
||||
# response에 요청 정보 있으니 풀링 필요
|
||||
def make_creatomate_custom_call(self, source: str):
|
||||
url = Creatomate.base_url + "/v2/renders"
|
||||
data = source
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
|
||||
response = requests.post(url, json=data, headers=headers)
|
||||
return response
|
||||
|
||||
def calc_scene_duration(self, template: dict):
|
||||
total_template_duration = 0
|
||||
for elem in template["source"]["elements"]:
|
||||
try:
|
||||
if elem["type"] == "audio":
|
||||
continue
|
||||
total_template_duration += elem["duration"]
|
||||
if "animations" not in elem:
|
||||
continue
|
||||
for animation in elem["animations"]:
|
||||
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
||||
if animation["transition"]:
|
||||
total_template_duration -= animation["duration"]
|
||||
except:
|
||||
print(elem)
|
||||
return total_template_duration
|
||||
|
||||
def extend_template_duration(self, template: dict, target_duration: float):
|
||||
template["duration"] = target_duration
|
||||
total_template_duration = self.calc_scene_duration(template)
|
||||
extend_rate = target_duration / total_template_duration
|
||||
new_template = copy.deepcopy(template)
|
||||
for elem in new_template["source"]["elements"]:
|
||||
try:
|
||||
if elem["type"] == "audio":
|
||||
continue
|
||||
elem["duration"] = elem["duration"] * extend_rate
|
||||
if "animations" not in elem:
|
||||
continue
|
||||
for animation in elem["animations"]:
|
||||
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
||||
animation["duration"] = animation["duration"] * extend_rate
|
||||
except:
|
||||
print(elem)
|
||||
return new_template
|
||||
|
||||
|
||||
# Azure사용한 legacy 코드 원본
|
||||
# def template_connect_resource_blackbox(template_id, user_idx, task_idx):
|
||||
# secret_client = get_keyvault_client()
|
||||
# account_url = secret_client.get_secret(BLOB_ACCOUNT_URL_KEY).value
|
||||
# media_folder_path = f"{user_idx}/{task_idx}"
|
||||
# lyric_path = f"{media_folder_path}/lyric.txt"
|
||||
# lyric = az_storage.az_storage_read_ado2_media(lyric_path).readall().decode('UTF-8')
|
||||
# media_list = az_storage.az_storage_get_ado2_media_list(media_folder_path)
|
||||
# image_list = [media.name for media in media_list if '/crawling-images/' in media.name]
|
||||
# template_data = get_one_template_data(template_id)
|
||||
# template_component_data = parse_template_component_name(template_data['source']['elements'])
|
||||
# lyric.replace("\r", "")
|
||||
# lyric_splited = lyric.split("\n")
|
||||
# modifications = {}
|
||||
# for idx, (template_component_name, template_type) in enumerate(template_component_data.items()):
|
||||
# match template_type:
|
||||
# case 'image':
|
||||
# modifications[template_component_name] = f"{account_url}/{BLOB_CONTAINER_NAME}/{image_list[idx % len(image_list)]}"
|
||||
# case 'text':
|
||||
# modifications[template_component_name] = lyric_splited[idx % len(lyric_splited)]
|
||||
|
||||
# modifications["audio-music"] = f"{account_url}/{BLOB_CONTAINER_NAME}/{BLOB_MEDIA_FOLDER}/{media_folder_path}/music_mureka.mp3"
|
||||
# print(modifications)
|
||||
|
||||
# return modifications
|
||||
import copy
|
||||
|
||||
import requests
|
||||
|
||||
CREATOMATE_API_KEY = "df9e4382d7e84fe790bf8a2168152be195d5a3568524ceb66ed989a2dea809f7d3065d6803b2e3dd9d02b5e5ec1c9823"
|
||||
# ACCOUNT_URL = "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/"
|
||||
# Creatomate 템플릿 정보 전부 가져오기
|
||||
|
||||
|
||||
class Creatomate:
|
||||
base_url: str = "https://api.creatomate.com"
|
||||
|
||||
def __init__(self, api_key):
|
||||
self.api_key = api_key
|
||||
|
||||
def get_all_templates_data(self) -> dict:
|
||||
url = Creatomate.base_url + "/v1/templates"
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
response = requests.get(url, headers=headers)
|
||||
return response.json()
|
||||
|
||||
# Creatomate 템플릿 ID 로부터 해당 템플릿 정보 가져오기
|
||||
def get_one_template_data(self, template_id: str) -> dict:
|
||||
url = Creatomate.base_url + f"/v1/templates/{template_id}"
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
response = requests.get(url, headers=headers)
|
||||
return response.json()
|
||||
|
||||
# 템플릿 정보 파싱하여 리소스 이름 추출하기
|
||||
def parse_template_component_name(self, template_source: dict) -> dict:
|
||||
def recursive_parse_component(element: dict) -> dict:
|
||||
if "name" in element:
|
||||
result_element_name_type = {element["name"]: element["type"]}
|
||||
else:
|
||||
result_element_name_type = {}
|
||||
|
||||
if element["type"] == "composition":
|
||||
minor_component_list = [
|
||||
recursive_parse_component(minor) for minor in element["elements"]
|
||||
]
|
||||
for minor_component in minor_component_list: ## WARNING : Same name component should shroud other component. be aware
|
||||
result_element_name_type.update(minor_component)
|
||||
|
||||
return result_element_name_type
|
||||
|
||||
result = {}
|
||||
for result_element_dict in [
|
||||
recursive_parse_component(component) for component in template_source
|
||||
]:
|
||||
result.update(result_element_dict)
|
||||
|
||||
return result
|
||||
|
||||
# 템플릿 정보 이미지/가사/음악 리소스와 매핑하기
|
||||
# 이미지는 순차적으로 집어넣기
|
||||
# 가사는 개행마다 한 텍스트 삽입
|
||||
# Template에 audio-music 항목이 있어야 함. (추가된 템플릿 Cafe뿐임)
|
||||
def template_connect_resource_blackbox(
|
||||
self, template_id: str, image_url_list: list[str], lyric: str, music_url: str
|
||||
) -> dict:
|
||||
template_data = self.get_one_template_data(template_id)
|
||||
template_component_data = self.parse_template_component_name(
|
||||
template_data["source"]["elements"]
|
||||
)
|
||||
|
||||
lyric.replace("\r", "")
|
||||
lyric_splited = lyric.split("\n")
|
||||
modifications = {}
|
||||
for idx, (template_component_name, template_type) in enumerate(
|
||||
template_component_data.items()
|
||||
):
|
||||
match template_type:
|
||||
case "image":
|
||||
modifications[template_component_name] = image_url_list[
|
||||
idx % len(image_url_list)
|
||||
]
|
||||
case "text":
|
||||
modifications[template_component_name] = lyric_splited[
|
||||
idx % len(lyric_splited)
|
||||
]
|
||||
|
||||
modifications["audio-music"] = music_url
|
||||
|
||||
return modifications
|
||||
|
||||
def elements_connect_resource_blackbox(
|
||||
self, elements: list, image_url_list: list[str], lyric: str, music_url: str
|
||||
) -> dict:
|
||||
template_component_data = self.parse_template_component_name(elements)
|
||||
|
||||
lyric.replace("\r", "")
|
||||
lyric_splited = lyric.split("\n")
|
||||
modifications = {}
|
||||
for idx, (template_component_name, template_type) in enumerate(
|
||||
template_component_data.items()
|
||||
):
|
||||
match template_type:
|
||||
case "image":
|
||||
modifications[template_component_name] = image_url_list[
|
||||
idx % len(image_url_list)
|
||||
]
|
||||
case "text":
|
||||
modifications[template_component_name] = lyric_splited[
|
||||
idx % len(lyric_splited)
|
||||
]
|
||||
|
||||
modifications["audio-music"] = music_url
|
||||
|
||||
return modifications
|
||||
|
||||
def modify_element(self, elements: list, modification: dict):
|
||||
def recursive_modify(element: dict) -> dict:
|
||||
if "name" in element:
|
||||
match element["type"]:
|
||||
case "image":
|
||||
element["source"] = modification[element["name"]]
|
||||
case "audio":
|
||||
element["source"] = modification.get(element["name"], "")
|
||||
case "video":
|
||||
element["source"] = modification[element["name"]]
|
||||
case "text":
|
||||
element["source"] = modification.get(element["name"], "")
|
||||
case "composition":
|
||||
for minor in element["elements"]:
|
||||
recursive_modify(minor)
|
||||
|
||||
for minor in elements:
|
||||
recursive_modify(minor)
|
||||
|
||||
return elements
|
||||
|
||||
# Creatomate에 생성 요청
|
||||
# response에 요청 정보 있으니 풀링 필요
|
||||
def make_creatomate_call(self, template_id: str, modifications: dict):
|
||||
url = Creatomate.base_url + "/v2/renders"
|
||||
|
||||
data = {"template_id": template_id, "modifications": modifications}
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
|
||||
response = requests.post(url, json=data, headers=headers)
|
||||
return response
|
||||
|
||||
# Creatomate에 생성 요청 without template
|
||||
# response에 요청 정보 있으니 풀링 필요
|
||||
def make_creatomate_custom_call(self, source: str):
|
||||
url = Creatomate.base_url + "/v2/renders"
|
||||
data = source
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {self.api_key}",
|
||||
}
|
||||
|
||||
response = requests.post(url, json=data, headers=headers)
|
||||
return response
|
||||
|
||||
def calc_scene_duration(self, template: dict):
|
||||
total_template_duration = 0
|
||||
for elem in template["source"]["elements"]:
|
||||
try:
|
||||
if elem["type"] == "audio":
|
||||
continue
|
||||
total_template_duration += elem["duration"]
|
||||
if "animations" not in elem:
|
||||
continue
|
||||
for animation in elem["animations"]:
|
||||
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
||||
if animation["transition"]:
|
||||
total_template_duration -= animation["duration"]
|
||||
except:
|
||||
print(elem)
|
||||
return total_template_duration
|
||||
|
||||
def extend_template_duration(self, template: dict, target_duration: float):
|
||||
template["duration"] = target_duration
|
||||
total_template_duration = self.calc_scene_duration(template)
|
||||
extend_rate = target_duration / total_template_duration
|
||||
new_template = copy.deepcopy(template)
|
||||
for elem in new_template["source"]["elements"]:
|
||||
try:
|
||||
if elem["type"] == "audio":
|
||||
continue
|
||||
elem["duration"] = elem["duration"] * extend_rate
|
||||
if "animations" not in elem:
|
||||
continue
|
||||
for animation in elem["animations"]:
|
||||
assert animation["time"] == 0 # 0이 아닌 경우 확인 필요
|
||||
animation["duration"] = animation["duration"] * extend_rate
|
||||
except:
|
||||
print(elem)
|
||||
return new_template
|
||||
|
||||
|
||||
# Azure사용한 legacy 코드 원본
|
||||
# def template_connect_resource_blackbox(template_id, user_idx, task_idx):
|
||||
# secret_client = get_keyvault_client()
|
||||
# account_url = secret_client.get_secret(BLOB_ACCOUNT_URL_KEY).value
|
||||
# media_folder_path = f"{user_idx}/{task_idx}"
|
||||
# lyric_path = f"{media_folder_path}/lyric.txt"
|
||||
# lyric = az_storage.az_storage_read_ado2_media(lyric_path).readall().decode('UTF-8')
|
||||
# media_list = az_storage.az_storage_get_ado2_media_list(media_folder_path)
|
||||
# image_list = [media.name for media in media_list if '/crawling-images/' in media.name]
|
||||
# template_data = get_one_template_data(template_id)
|
||||
# template_component_data = parse_template_component_name(template_data['source']['elements'])
|
||||
# lyric.replace("\r", "")
|
||||
# lyric_splited = lyric.split("\n")
|
||||
# modifications = {}
|
||||
# for idx, (template_component_name, template_type) in enumerate(template_component_data.items()):
|
||||
# match template_type:
|
||||
# case 'image':
|
||||
# modifications[template_component_name] = f"{account_url}/{BLOB_CONTAINER_NAME}/{image_list[idx % len(image_list)]}"
|
||||
# case 'text':
|
||||
# modifications[template_component_name] = lyric_splited[idx % len(lyric_splited)]
|
||||
|
||||
# modifications["audio-music"] = f"{account_url}/{BLOB_CONTAINER_NAME}/{BLOB_MEDIA_FOLDER}/{media_folder_path}/music_mureka.mp3"
|
||||
# print(modifications)
|
||||
|
||||
# return modifications
|
||||
+55
-55
@@ -1,55 +1,55 @@
|
||||
import creatomate
|
||||
|
||||
CREATOMATE_API_KEY = "df9e4382d7e84fe790bf8a2168152be195d5a3568524ceb66ed989a2dea809f7d3065d6803b2e3dd9d02b5e5ec1c9823"
|
||||
shortform_4_template_id = "e8c7b43f-de4b-4ba3-b8eb-5df688569193"
|
||||
target_duration = 90.0 # s
|
||||
|
||||
creato = creatomate.Creatomate(CREATOMATE_API_KEY)
|
||||
|
||||
template = creato.get_one_template_data(shortform_4_template_id)
|
||||
|
||||
uploaded_image_url_list = [
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818306_000_385523a5_99f2e8a8.jpg",
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818306_001_d4cf6ec9_b81a1fdc.jpg",
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818307_002_e4a0b276_680c5020.jpg",
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818307_003_657f8c26_9f2c7168.jpg",
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818307_004_9500e39d_24b9dad0.jpg",
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818308_005_c3536641_9d490ccf.jpg",
|
||||
]
|
||||
|
||||
lyric = """
|
||||
진짜 맛있는 추어탕의 향연
|
||||
청담추어정 본점이야 말로
|
||||
온 가족이 함께 먹는 그 맛
|
||||
여수동 맛집으로 명성을 떨쳐
|
||||
|
||||
주차 가능, 단체 이용도 OK
|
||||
내 입맛을 사로잡는 맛
|
||||
청담추어정, 그 진정한 맛
|
||||
말복을 지나고 느껴보세요
|
||||
|
||||
한산한 분위기, 편안한 식사
|
||||
상황 추어탕으로 더욱 완벽
|
||||
톡톡 튀는 맛, 한 입에 느껴
|
||||
청담추어정에서 즐겨보세요
|
||||
|
||||
성남 출신의 맛집으로
|
||||
여수대로에서 빛나는 그곳
|
||||
청담추어정, 진짜 맛의 꿈
|
||||
여러분을 초대합니다 여기에
|
||||
|
||||
#청담추어정 #여수동맛집
|
||||
성남에서 만나는 진짜 맛
|
||||
"""
|
||||
|
||||
song_url = "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/stay.mp3"
|
||||
|
||||
modifications = creato.elements_connect_resource_blackbox(
|
||||
template["source"]["elements"], uploaded_image_url_list, lyric, song_url
|
||||
)
|
||||
|
||||
|
||||
new_elements = creato.modify_element(template["source"]["elements"], modifications)
|
||||
template["source"]["elements"] = new_elements
|
||||
last_template = creato.extend_template_duration(template, target_duration)
|
||||
creato.make_creatomate_custom_call(last_template["source"])
|
||||
import creatomate
|
||||
|
||||
CREATOMATE_API_KEY = "df9e4382d7e84fe790bf8a2168152be195d5a3568524ceb66ed989a2dea809f7d3065d6803b2e3dd9d02b5e5ec1c9823"
|
||||
shortform_4_template_id = "e8c7b43f-de4b-4ba3-b8eb-5df688569193"
|
||||
target_duration = 90.0 # s
|
||||
|
||||
creato = creatomate.Creatomate(CREATOMATE_API_KEY)
|
||||
|
||||
template = creato.get_one_template_data(shortform_4_template_id)
|
||||
|
||||
uploaded_image_url_list = [
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818306_000_385523a5_99f2e8a8.jpg",
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818306_001_d4cf6ec9_b81a1fdc.jpg",
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818307_002_e4a0b276_680c5020.jpg",
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818307_003_657f8c26_9f2c7168.jpg",
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818307_004_9500e39d_24b9dad0.jpg",
|
||||
"https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/crawling-images/crawler4_img_1755818308_005_c3536641_9d490ccf.jpg",
|
||||
]
|
||||
|
||||
lyric = """
|
||||
진짜 맛있는 추어탕의 향연
|
||||
청담추어정 본점이야 말로
|
||||
온 가족이 함께 먹는 그 맛
|
||||
여수동 맛집으로 명성을 떨쳐
|
||||
|
||||
주차 가능, 단체 이용도 OK
|
||||
내 입맛을 사로잡는 맛
|
||||
청담추어정, 그 진정한 맛
|
||||
말복을 지나고 느껴보세요
|
||||
|
||||
한산한 분위기, 편안한 식사
|
||||
상황 추어탕으로 더욱 완벽
|
||||
톡톡 튀는 맛, 한 입에 느껴
|
||||
청담추어정에서 즐겨보세요
|
||||
|
||||
성남 출신의 맛집으로
|
||||
여수대로에서 빛나는 그곳
|
||||
청담추어정, 진짜 맛의 꿈
|
||||
여러분을 초대합니다 여기에
|
||||
|
||||
#청담추어정 #여수동맛집
|
||||
성남에서 만나는 진짜 맛
|
||||
"""
|
||||
|
||||
song_url = "https://ado2mediastoragepublic.blob.core.windows.net/ado2-media-public-access/ado2-media-original/dev-user-idx/dev-task-idx/stay.mp3"
|
||||
|
||||
modifications = creato.elements_connect_resource_blackbox(
|
||||
template["source"]["elements"], uploaded_image_url_list, lyric, song_url
|
||||
)
|
||||
|
||||
|
||||
new_elements = creato.modify_element(template["source"]["elements"], modifications)
|
||||
template["source"]["elements"] = new_elements
|
||||
last_template = creato.extend_template_duration(template, target_duration)
|
||||
creato.make_creatomate_custom_call(last_template["source"])
|
||||
Reference in new issue
Block a user