|
|
import pandas as pd |
|
|
from konlpy.tag import Okt |
|
|
import os |
|
|
import json |
|
|
from tqdm import tqdm |
|
|
import datetime |
|
|
import multiprocessing |
|
|
import numpy as np |
|
|
import time |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
input_file_path = '/chosun_preprocessed.csv' |
|
|
|
|
|
|
|
|
output_dir = '/koselleck_analysis_results' |
|
|
output_file_path = os.path.join(output_dir, 'chosun_pos_tagged_parallel.jsonl') |
|
|
error_log_path = os.path.join(output_dir, 'pos_tagging_errors_parallel.log') |
|
|
|
|
|
|
|
|
NUM_PROCESSES = max(1, multiprocessing.cpu_count() - 1) |
|
|
|
|
|
CHUNK_SIZE = 200000 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
okt_worker = None |
|
|
progress_counter = None |
|
|
lock = None |
|
|
|
|
|
def init_worker(counter, lk): |
|
|
""" |
|
|
각 Worker 프로세스가 시작될 때 한 번만 실행되는 초기화 함수. |
|
|
Okt 객체, 공유 카운터, 공유 잠금 장치를 전역 변수에 할당합니다. |
|
|
""" |
|
|
global okt_worker, progress_counter, lock |
|
|
okt_worker = Okt() |
|
|
progress_counter = counter |
|
|
lock = lk |
|
|
|
|
|
def process_chunk(chunk_df): |
|
|
""" |
|
|
데이터프레임 덩어리(chunk)를 받아 형태소 분석을 수행하는 함수 (각 프로세스에서 실행됨) |
|
|
""" |
|
|
global okt_worker, progress_counter, lock |
|
|
results = [] |
|
|
errors = [] |
|
|
|
|
|
for index, row in chunk_df.iterrows(): |
|
|
source_text = None |
|
|
year = row['year'] |
|
|
|
|
|
if year < 1954: |
|
|
if pd.notna(row['body_korean']): |
|
|
source_text = str(row['body_korean']) |
|
|
else: |
|
|
if pd.notna(row['body_archaic']): |
|
|
source_text = str(row['body_archaic']) |
|
|
|
|
|
if not source_text: |
|
|
with lock: |
|
|
progress_counter.value += 1 |
|
|
continue |
|
|
|
|
|
try: |
|
|
pos_tagged_body = okt_worker.pos(source_text, norm=True, stem=True) |
|
|
result = { |
|
|
'id': row['id'], |
|
|
'date': str(row['publication_date']), |
|
|
'year': year, |
|
|
'type': row['type'], |
|
|
'pos_tagged_body': pos_tagged_body |
|
|
} |
|
|
results.append(json.dumps(result, ensure_ascii=False) + '\n') |
|
|
except Exception as e: |
|
|
error_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") |
|
|
error_message = f"[{error_time}] - ID: {row['id']}, Year: {year}, Error: {e}\n" |
|
|
errors.append(error_message) |
|
|
|
|
|
with lock: |
|
|
progress_counter.value += 1 |
|
|
|
|
|
return results, errors |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
print("--- 조선일보 데이터 병렬 전처리 시작 (최종 안정화 버전) ---") |
|
|
os.makedirs(output_dir, exist_ok=True) |
|
|
|
|
|
|
|
|
processed_ids = set() |
|
|
if os.path.exists(output_file_path): |
|
|
print(f"\n1. 기존 처리 파일 '{output_file_path}'을(를) 발견했습니다. 처리된 ID를 로드합니다.") |
|
|
with open(output_file_path, 'r', encoding='utf-8') as f: |
|
|
for line in tqdm(f, desc="기존 결과 로딩"): |
|
|
try: |
|
|
processed_ids.add(json.loads(line)['id']) |
|
|
except json.JSONDecodeError: |
|
|
continue |
|
|
print(f"총 {len(processed_ids)}개의 기사가 이미 처리되었습니다.") |
|
|
|
|
|
|
|
|
print("\n2. 처리할 데이터의 전체 규모를 계산합니다.") |
|
|
unprocessed_count = 0 |
|
|
chunk_iterator_for_count = pd.read_csv(input_file_path, usecols=['id'], chunksize=CHUNK_SIZE, low_memory=False) |
|
|
for chunk_df in tqdm(chunk_iterator_for_count, desc="전체 규모 계산"): |
|
|
chunk_df.dropna(subset=['id'], inplace=True) |
|
|
unprocessed_count += chunk_df[~chunk_df['id'].isin(processed_ids)].shape[0] |
|
|
|
|
|
if unprocessed_count == 0: |
|
|
print("\n모든 데이터가 이미 처리되었습니다. 작업을 종료합니다.") |
|
|
exit() |
|
|
print(f"총 {unprocessed_count}개의 미처리 기사를 대상으로 작업을 시작합니다.") |
|
|
|
|
|
|
|
|
print(f"\n3. {NUM_PROCESSES}개의 프로세스로 병렬 처리를 시작합니다.") |
|
|
|
|
|
manager = multiprocessing.Manager() |
|
|
progress_counter = manager.Value('i', 0) |
|
|
lock = manager.Lock() |
|
|
|
|
|
try: |
|
|
with multiprocessing.Pool(processes=NUM_PROCESSES, initializer=init_worker, initargs=(progress_counter, lock)) as pool, \ |
|
|
open(output_file_path, 'a', encoding='utf-8') as f_out, \ |
|
|
open(error_log_path, 'a', encoding='utf-8') as f_err, \ |
|
|
tqdm(total=unprocessed_count, desc="전체 진행률") as pbar: |
|
|
|
|
|
chunk_iterator = pd.read_csv( |
|
|
input_file_path, |
|
|
usecols=['id', 'publication_date', 'type', 'body_korean', 'body_archaic'], |
|
|
chunksize=CHUNK_SIZE, |
|
|
low_memory=False |
|
|
) |
|
|
|
|
|
async_results = [] |
|
|
for chunk_df in chunk_iterator: |
|
|
chunk_df.dropna(subset=['id', 'publication_date'], inplace=True) |
|
|
unprocessed_chunk = chunk_df[~chunk_df['id'].isin(processed_ids)].copy() |
|
|
if unprocessed_chunk.empty: |
|
|
continue |
|
|
|
|
|
unprocessed_chunk['year'] = pd.to_datetime(unprocessed_chunk['publication_date'], errors='coerce').dt.year |
|
|
unprocessed_chunk.dropna(subset=['year'], inplace=True) |
|
|
unprocessed_chunk['year'] = unprocessed_chunk['year'].astype(int) |
|
|
|
|
|
res = pool.apply_async(process_chunk, (unprocessed_chunk,)) |
|
|
async_results.append(res) |
|
|
|
|
|
last_value = 0 |
|
|
for res in async_results: |
|
|
while not res.ready(): |
|
|
current_value = progress_counter.value |
|
|
pbar.update(current_value - last_value) |
|
|
last_value = current_value |
|
|
time.sleep(1) |
|
|
|
|
|
results, errors = res.get() |
|
|
if results: |
|
|
f_out.writelines(results) |
|
|
if errors: |
|
|
f_err.writelines(errors) |
|
|
|
|
|
current_value = progress_counter.value |
|
|
pbar.update(current_value - last_value) |
|
|
|
|
|
except Exception as e: |
|
|
print(f"\n처리 중 심각한 오류 발생: {e}") |
|
|
|
|
|
print(f"\n> 형태소 분석 및 전처리가 완료되었습니다.") |
|
|
print(f"> 전체 결과는 다음 경로에 저장/추가되었습니다: {output_file_path}") |
|
|
|