File size: 7,059 Bytes
e022aed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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

# ----------------------------------------
# 1. 설정
# ----------------------------------------
# 입력 파일 경로
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')

# 사용할 CPU 프로세스 수 (시스템 코어 수 - 1을 권장)
NUM_PROCESSES = max(1, multiprocessing.cpu_count() - 1)
# 원본 CSV를 읽을 때 한 번에 메모리에 올릴 행의 수
CHUNK_SIZE = 200000

# ----------------------------------------
# 2. 병렬 처리를 위한 작업 함수 및 초기화 함수 정의
# ----------------------------------------

# 각 Worker 프로세스에서 사용할 전역 변수
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

# ----------------------------------------
# 3. 메인 실행 로직
# ----------------------------------------
if __name__ == "__main__":
    print("--- 조선일보 데이터 병렬 전처리 시작 (최종 안정화 버전) ---")
    os.makedirs(output_dir, exist_ok=True)

    # --- 3.1. 기존 처리된 ID 로드 ---
    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)}개의 기사가 이미 처리되었습니다.")
    
    # --- 3.2. 처리할 데이터 규모 계산 ---
    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}개의 미처리 기사를 대상으로 작업을 시작합니다.")

    # --- 3.3. 병렬 처리 실행 ---
    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}")