빈값 채우기 및 코드 정리
This commit is contained in:
commit
ff19db34a8
36 files changed
+3348
-377
No files matched your search
@@ -1,14 +1,16 @@
|
||||
from common.db.base import execute, fetchone, fetchall
|
||||
from common.db.hospital import select_hospital, update_hospital_status, insert_hospital, update_hospital
|
||||
from common.db.source import (
|
||||
insert_source, select_source_mainpage,
|
||||
insert_raw_info, update_raw_info_status, update_raw_info,
|
||||
insert_source, select_source_mainpage, select_source_by_type,
|
||||
insert_raw_info, update_raw_info_status, update_raw_info, update_raw_info_merge,
|
||||
update_raw_info_logo_url, select_mainpage_logo_url, select_branding_info_id,
|
||||
select_raw_info_data,
|
||||
select_run_sources, select_run_raw_data, select_run_mainpage_url,
|
||||
select_run_sources, select_run_raw_data, select_run_source_raw,
|
||||
select_run_mainpage_url,
|
||||
)
|
||||
from common.db.run import (
|
||||
insert_run, select_run, select_run_status, update_run_status,
|
||||
update_run_report, update_run_plan, select_run_with_clinic,
|
||||
update_run_report, update_run_plan, select_run_with_clinic, select_run_report_data,
|
||||
)
|
||||
from common.db.market import upsert_market_status, upsert_market_result, select_market
|
||||
from common.db.file_data import insert_file, select_run_files, select_file, delete_file
|
||||
@@ -22,6 +22,18 @@ async def select_run(analysis_run_id: str) -> dict | None:
|
||||
)
|
||||
|
||||
|
||||
async def select_run_report_data(analysis_run_id: str) -> dict | None:
|
||||
"""report 결과가 필요할 때만 호출. raw JSON 파싱해서 dict 반환."""
|
||||
import json
|
||||
row = await fetchone(
|
||||
"SELECT report_data FROM analysis_runs WHERE analysis_run_id = %s",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
if not row or not row["report_data"]:
|
||||
return None
|
||||
return json.loads(row["report_data"]) if isinstance(row["report_data"], str) else row["report_data"]
|
||||
|
||||
|
||||
async def select_run_status(analysis_run_id: str) -> str | None:
|
||||
row = await fetchone(
|
||||
"SELECT status FROM analysis_runs WHERE analysis_run_id = %s",
|
||||
|
||||
+86
-5
@@ -17,7 +17,7 @@ async def insert_source(
|
||||
|
||||
async def select_source_mainpage(hospital_id: str) -> dict | None:
|
||||
return await fetchone(
|
||||
"SELECT source_id FROM remote_source WHERE hospital_id = %s AND source_type = 'mainpage'",
|
||||
"SELECT source_id, url FROM remote_source WHERE hospital_id = %s AND source_type = 'mainpage'",
|
||||
(hospital_id,),
|
||||
)
|
||||
|
||||
@@ -64,18 +64,99 @@ async def select_run_sources(analysis_run_id: str) -> list[dict]:
|
||||
|
||||
async def select_run_raw_data(analysis_run_id: str) -> dict:
|
||||
rows = await fetchall(
|
||||
"SELECT rs.source_type, ri.raw_data"
|
||||
"SELECT rs.source_type, rs.language, ri.raw_data, ri.logo_url"
|
||||
" FROM raw_info ri JOIN remote_source rs USING (source_id)"
|
||||
" WHERE ri.analysis_run_id = %s",
|
||||
" WHERE ri.analysis_run_id = %s AND ri.status = 'done'",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
result: dict = {}
|
||||
for row in rows:
|
||||
raw = row["raw_data"]
|
||||
result[row["source_type"]] = json.loads(raw) if isinstance(raw, str) else raw
|
||||
source_type = row["source_type"]
|
||||
if source_type not in result:
|
||||
result[source_type] = list()
|
||||
|
||||
item : dict = {}
|
||||
item["raw_data"] = json.loads(row["raw_data"])
|
||||
item["logo_url"] = row["logo_url"]
|
||||
item["source_type"] = row["source_type"]
|
||||
item["language"] = row["language"]
|
||||
|
||||
result[source_type].append(item)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
async def select_run_source_raw(
|
||||
analysis_run_id: str, source_type: str, language: str | None = None,
|
||||
) -> dict | None:
|
||||
sql = (
|
||||
"SELECT ri.raw_data FROM raw_info ri JOIN remote_source rs USING (source_id)"
|
||||
" WHERE ri.analysis_run_id = %s AND rs.source_type = %s"
|
||||
)
|
||||
args: tuple = (analysis_run_id, source_type)
|
||||
if language:
|
||||
sql += " AND rs.language = %s"
|
||||
args = (*args, language)
|
||||
sql += " LIMIT 1"
|
||||
row = await fetchone(sql, args)
|
||||
if not row or not row["raw_data"]:
|
||||
return None
|
||||
return json.loads(row["raw_data"]) if isinstance(row["raw_data"], str) else row["raw_data"]
|
||||
|
||||
|
||||
async def update_raw_info_logo_url(info_id: int, logo_url: str) -> None:
|
||||
"""raw_info.logo_url 컬럼에 로고 URL 저장 (JSON raw_data 와 분리해 컬럼 인덱스/조회 용이)."""
|
||||
await execute(
|
||||
"UPDATE raw_info SET logo_url = %s WHERE info_id = %s",
|
||||
(logo_url, info_id),
|
||||
)
|
||||
|
||||
|
||||
async def select_branding_info_id(analysis_run_id: str) -> int | None:
|
||||
row = await fetchone(
|
||||
"SELECT ri.info_id FROM raw_info ri JOIN remote_source rs USING (source_id)"
|
||||
" WHERE ri.analysis_run_id = %s AND rs.source_type = 'branding' LIMIT 1",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
return (row or {}).get("info_id")
|
||||
|
||||
|
||||
async def select_mainpage_logo_url(analysis_run_id: str) -> str | None:
|
||||
row = await fetchone(
|
||||
"SELECT ri.logo_url FROM raw_info ri JOIN remote_source rs USING (source_id)"
|
||||
" WHERE ri.analysis_run_id = %s AND rs.source_type = 'mainpage' LIMIT 1",
|
||||
(analysis_run_id,),
|
||||
)
|
||||
return (row or {}).get("logo_url")
|
||||
|
||||
|
||||
async def update_raw_info_merge(info_id: int, patch: dict) -> None:
|
||||
"""raw_info.raw_data 를 read-modify-write 로 top-level 머지.
|
||||
한 source 가 단계별로 (예: branding 의 brandAssets → channelLogos) 키를 덧붙일 때 사용."""
|
||||
row = await fetchone("SELECT raw_data FROM raw_info WHERE info_id = %s", (info_id,))
|
||||
if not row:
|
||||
return
|
||||
raw = row["raw_data"]
|
||||
data = json.loads(raw) if isinstance(raw, str) else (raw or {})
|
||||
data.update(patch)
|
||||
await execute(
|
||||
"UPDATE raw_info SET raw_data = %s, status = 'done' WHERE info_id = %s",
|
||||
(json.dumps(data, ensure_ascii=False), info_id),
|
||||
)
|
||||
|
||||
|
||||
async def select_source_by_type(
|
||||
hospital_id: str, source_type: str, language: str | None = None,
|
||||
) -> dict | None:
|
||||
sql = "SELECT source_id, url FROM remote_source WHERE hospital_id = %s AND source_type = %s"
|
||||
args: tuple = (hospital_id, source_type)
|
||||
if language:
|
||||
sql += " AND language = %s"
|
||||
args = (*args, language)
|
||||
sql += " LIMIT 1"
|
||||
return await fetchone(sql, args)
|
||||
|
||||
|
||||
async def select_run_mainpage_url(analysis_run_id: str) -> str:
|
||||
row = await fetchone(
|
||||
"SELECT rs.url FROM raw_info ri JOIN remote_source rs USING (source_id)"
|
||||
|
||||
@@ -1,11 +1,101 @@
|
||||
import os
|
||||
import re
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from http import HTTPMethod
|
||||
import httpx
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
REQUEST_TIMEOUT = 60
|
||||
|
||||
|
||||
def parse_iso_duration_seconds(iso: str) -> int:
|
||||
m = re.match(r"PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?", iso or "")
|
||||
if not m:
|
||||
return 0
|
||||
h, mins, s = (int(x or 0) for x in m.groups())
|
||||
return h * 3600 + mins * 60 + s
|
||||
|
||||
|
||||
def format_seconds(seconds: int) -> str:
|
||||
m, s = divmod(seconds, 60)
|
||||
h, m = divmod(m, 60)
|
||||
return f"{h}시간 {m}분" if h else f"{m}분 {s}초"
|
||||
|
||||
|
||||
def format_clock(seconds: int) -> str:
|
||||
m, s = divmod(seconds, 60)
|
||||
h, m = divmod(m, 60)
|
||||
return f"{h}:{m:02d}:{s:02d}" if h else f"{m}:{s:02d}"
|
||||
|
||||
|
||||
def calc_avg_video_length(videos: list[dict]) -> str:
|
||||
durations = [parse_iso_duration_seconds(v.get("duration", "")) for v in videos]
|
||||
durations = [d for d in durations if d > 0]
|
||||
if not durations:
|
||||
return ""
|
||||
return format_seconds(sum(durations) // len(durations))
|
||||
|
||||
|
||||
def relative_date(date_str: str) -> str:
|
||||
if not date_str:
|
||||
return ""
|
||||
try:
|
||||
past = datetime.fromisoformat(date_str[:10])
|
||||
except ValueError:
|
||||
return ""
|
||||
days = (datetime.now() - past).days
|
||||
if days < 1:
|
||||
return "오늘"
|
||||
if days < 30:
|
||||
return f"{days}일 전"
|
||||
if days < 365:
|
||||
return f"{days // 30}개월 전"
|
||||
return f"{days // 365}년 전"
|
||||
|
||||
|
||||
def calc_upload_frequency(videos: list[dict]) -> str:
|
||||
dates = sorted(
|
||||
[v["date"][:10] for v in videos if v.get("date")],
|
||||
reverse=True,
|
||||
)
|
||||
if len(dates) < 2:
|
||||
return ""
|
||||
gaps = [
|
||||
(datetime.fromisoformat(dates[i]) - datetime.fromisoformat(dates[i + 1])).days
|
||||
for i in range(len(dates) - 1)
|
||||
]
|
||||
avg_days = sum(gaps) // len(gaps)
|
||||
if avg_days <= 7:
|
||||
return f"주 {7 // max(avg_days, 1)}회"
|
||||
if avg_days <= 30:
|
||||
return f"월 {30 // avg_days}회"
|
||||
return f"{avg_days}일에 1회"
|
||||
|
||||
|
||||
def parse_ts(v) -> datetime | None:
|
||||
"""수집기마다 다른 timestamp 포맷을 통일된 datetime으로 변환.
|
||||
파싱 실패 시 None.
|
||||
"""
|
||||
# 숫자면 epoch (Unix timestamp) — apify가 가끔 epoch로 줌
|
||||
if isinstance(v, (int, float)):
|
||||
return datetime.fromtimestamp(v, tz=timezone.utc)
|
||||
if isinstance(v, str):
|
||||
# 1순위: ISO 8601 (대부분 apify/firecrawl 출력)
|
||||
try:
|
||||
return datetime.fromisoformat(v.replace("Z", "+00:00"))
|
||||
except ValueError:
|
||||
pass
|
||||
# 2순위: RFC 2822 (네이버 블로그 RSS 등 — 표준 라이브러리 파서로)
|
||||
try:
|
||||
from email.utils import parsedate_to_datetime
|
||||
return parsedate_to_datetime(v)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def get_env(key: str) -> str:
|
||||
v = os.environ.get(key, "")
|
||||
@@ -37,3 +127,48 @@ async def http_request(
|
||||
print(f" [error] {label} → {e}")
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
async def _run_optional_step(coro, label: str) -> None:
|
||||
"""부가 단계 실행 헬퍼: 예외를 삼키고 경고 로그만 남겨 호출측 흐름이 멈추지 않게 격리."""
|
||||
try:
|
||||
await coro
|
||||
except Exception as e:
|
||||
logger.warning("%s 실패 (무시하고 진행): %s", label, e)
|
||||
|
||||
|
||||
def _normalize_homepage(url: str) -> str:
|
||||
"""URL을 scheme/www/끝슬래시 제거 + 소문자로 정규화 (homepage 매칭용)."""
|
||||
u = (url or "").strip().lower()
|
||||
for p in ("https://", "http://"):
|
||||
if u.startswith(p):
|
||||
u = u[len(p):]
|
||||
if u.startswith("www."):
|
||||
u = u[4:]
|
||||
return u.rstrip("/")
|
||||
|
||||
|
||||
# SSL 인증서가 www.* 에만 유효한 도메인 — bare 도메인이면 사용자 클릭 시 브라우저 SSL warning 뜸.
|
||||
_WWW_REQUIRED = ("gangnamunni.com", "facebook.com", "instagram.com", "toxnfill.com")
|
||||
|
||||
|
||||
def _with_scheme(u: str | None) -> str | None:
|
||||
"""scheme 없는 URL에 https:// 보정 (수집기/링크 표시용). 빈 값은 None.
|
||||
+ 중첩된 https://가 끼어있으면 마지막 URL만 추출 (LLM이 가끔 'https://www.X/https://Y' 같이 만듦).
|
||||
+ SSL 엄격 도메인(gangnamunni/facebook/instagram)은 www. 자동 보강."""
|
||||
if not u:
|
||||
return None
|
||||
u = u.strip()
|
||||
# 'https://www.facebook.com/https://facebook.com/X' 같은 중첩 → 마지막 'http(s)://' 부터 잘라 사용
|
||||
last = max(u.rfind("https://"), u.rfind("http://"))
|
||||
if last > 0:
|
||||
u = u[last:]
|
||||
if "://" not in u:
|
||||
u = "https://" + u
|
||||
# scheme 뒤가 www. 없이 SSL 엄격 도메인이면 www. 추가
|
||||
for dom in _WWW_REQUIRED:
|
||||
for scheme in ("https://", "http://"):
|
||||
if u.startswith(scheme + dom):
|
||||
u = scheme + "www." + u[len(scheme):]
|
||||
break
|
||||
return u
|
||||
Reference in new issue
Block a user