ddokbaro commited on
Commit
e022aed
·
verified ·
1 Parent(s): 8c1aeef

Create 01_preprocess_Okt_parallel.py

Browse files
Files changed (1) hide show
  1. scripts/01_preprocess_Okt_parallel.py +177 -0
scripts/01_preprocess_Okt_parallel.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ from konlpy.tag import Okt
3
+ import os
4
+ import json
5
+ from tqdm import tqdm
6
+ import datetime
7
+ import multiprocessing
8
+ import numpy as np
9
+ import time
10
+
11
+ # ----------------------------------------
12
+ # 1. 설정
13
+ # ----------------------------------------
14
+ # 입력 파일 경로
15
+ input_file_path = '/chosun_preprocessed.csv'
16
+
17
+ # 출력 디렉토리 및 파일 경로 (고정된 파일명으로 이어하기 지원)
18
+ output_dir = '/koselleck_analysis_results'
19
+ output_file_path = os.path.join(output_dir, 'chosun_pos_tagged_parallel.jsonl')
20
+ error_log_path = os.path.join(output_dir, 'pos_tagging_errors_parallel.log')
21
+
22
+ # 사용할 CPU 프로세스 수 (시스템 코어 수 - 1을 권장)
23
+ NUM_PROCESSES = max(1, multiprocessing.cpu_count() - 1)
24
+ # 원본 CSV를 읽을 때 한 번에 메모리에 올릴 행의 수
25
+ CHUNK_SIZE = 200000
26
+
27
+ # ----------------------------------------
28
+ # 2. 병렬 처리를 위한 작업 함수 및 초기화 함수 정의
29
+ # ----------------------------------------
30
+
31
+ # 각 Worker 프로세스에서 사용할 전역 변수
32
+ okt_worker = None
33
+ progress_counter = None
34
+ lock = None
35
+
36
+ def init_worker(counter, lk):
37
+ """
38
+ 각 Worker 프로세스가 시작될 때 한 번만 실행되는 초기화 함수.
39
+ Okt 객체, 공유 카운터, 공유 잠금 장치를 전역 변수에 할당합니다.
40
+ """
41
+ global okt_worker, progress_counter, lock
42
+ okt_worker = Okt()
43
+ progress_counter = counter
44
+ lock = lk
45
+
46
+ def process_chunk(chunk_df):
47
+ """
48
+ 데이터프레임 덩어리(chunk)를 받아 형태소 분석을 수행하는 함수 (각 프로세스에서 실행됨)
49
+ """
50
+ global okt_worker, progress_counter, lock
51
+ results = []
52
+ errors = []
53
+
54
+ for index, row in chunk_df.iterrows():
55
+ source_text = None
56
+ year = row['year']
57
+
58
+ if year < 1954:
59
+ if pd.notna(row['body_korean']):
60
+ source_text = str(row['body_korean'])
61
+ else:
62
+ if pd.notna(row['body_archaic']):
63
+ source_text = str(row['body_archaic'])
64
+
65
+ if not source_text:
66
+ with lock:
67
+ progress_counter.value += 1
68
+ continue
69
+
70
+ try:
71
+ pos_tagged_body = okt_worker.pos(source_text, norm=True, stem=True)
72
+ result = {
73
+ 'id': row['id'],
74
+ 'date': str(row['publication_date']),
75
+ 'year': year,
76
+ 'type': row['type'],
77
+ 'pos_tagged_body': pos_tagged_body
78
+ }
79
+ results.append(json.dumps(result, ensure_ascii=False) + '\n')
80
+ except Exception as e:
81
+ error_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
82
+ error_message = f"[{error_time}] - ID: {row['id']}, Year: {year}, Error: {e}\n"
83
+ errors.append(error_message)
84
+
85
+ with lock:
86
+ progress_counter.value += 1
87
+
88
+ return results, errors
89
+
90
+ # ----------------------------------------
91
+ # 3. 메인 실행 로직
92
+ # ----------------------------------------
93
+ if __name__ == "__main__":
94
+ print("--- 조선일보 데이터 병렬 전처리 시작 (최종 안정화 버전) ---")
95
+ os.makedirs(output_dir, exist_ok=True)
96
+
97
+ # --- 3.1. 기존 처리된 ID 로드 ---
98
+ processed_ids = set()
99
+ if os.path.exists(output_file_path):
100
+ print(f"\n1. 기존 처리 파일 '{output_file_path}'을(를) 발견했습니다. 처리된 ID를 로드합니다.")
101
+ with open(output_file_path, 'r', encoding='utf-8') as f:
102
+ for line in tqdm(f, desc="기존 결과 로딩"):
103
+ try:
104
+ processed_ids.add(json.loads(line)['id'])
105
+ except json.JSONDecodeError:
106
+ continue
107
+ print(f"총 {len(processed_ids)}개의 기사가 이미 처리되었습니다.")
108
+
109
+ # --- 3.2. 처리할 데이터 규모 계산 ---
110
+ print("\n2. 처리할 데이터의 전체 규모를 계산합니다.")
111
+ unprocessed_count = 0
112
+ chunk_iterator_for_count = pd.read_csv(input_file_path, usecols=['id'], chunksize=CHUNK_SIZE, low_memory=False)
113
+ for chunk_df in tqdm(chunk_iterator_for_count, desc="전체 규모 계산"):
114
+ chunk_df.dropna(subset=['id'], inplace=True)
115
+ unprocessed_count += chunk_df[~chunk_df['id'].isin(processed_ids)].shape[0]
116
+
117
+ if unprocessed_count == 0:
118
+ print("\n모든 데이터가 이미 처리되었습니다. 작업을 종료합니다.")
119
+ exit()
120
+ print(f"총 {unprocessed_count}개의 미처리 기사를 대상으로 작업을 시작합니다.")
121
+
122
+ # --- 3.3. 병렬 처리 실행 ---
123
+ print(f"\n3. {NUM_PROCESSES}개의 프로세스로 병렬 처리를 시작합니다.")
124
+
125
+ manager = multiprocessing.Manager()
126
+ progress_counter = manager.Value('i', 0)
127
+ lock = manager.Lock()
128
+
129
+ try:
130
+ with multiprocessing.Pool(processes=NUM_PROCESSES, initializer=init_worker, initargs=(progress_counter, lock)) as pool, \
131
+ open(output_file_path, 'a', encoding='utf-8') as f_out, \
132
+ open(error_log_path, 'a', encoding='utf-8') as f_err, \
133
+ tqdm(total=unprocessed_count, desc="전체 진행률") as pbar:
134
+
135
+ chunk_iterator = pd.read_csv(
136
+ input_file_path,
137
+ usecols=['id', 'publication_date', 'type', 'body_korean', 'body_archaic'],
138
+ chunksize=CHUNK_SIZE,
139
+ low_memory=False
140
+ )
141
+
142
+ async_results = []
143
+ for chunk_df in chunk_iterator:
144
+ chunk_df.dropna(subset=['id', 'publication_date'], inplace=True)
145
+ unprocessed_chunk = chunk_df[~chunk_df['id'].isin(processed_ids)].copy()
146
+ if unprocessed_chunk.empty:
147
+ continue
148
+
149
+ unprocessed_chunk['year'] = pd.to_datetime(unprocessed_chunk['publication_date'], errors='coerce').dt.year
150
+ unprocessed_chunk.dropna(subset=['year'], inplace=True)
151
+ unprocessed_chunk['year'] = unprocessed_chunk['year'].astype(int)
152
+
153
+ res = pool.apply_async(process_chunk, (unprocessed_chunk,))
154
+ async_results.append(res)
155
+
156
+ last_value = 0
157
+ for res in async_results:
158
+ while not res.ready():
159
+ current_value = progress_counter.value
160
+ pbar.update(current_value - last_value)
161
+ last_value = current_value
162
+ time.sleep(1)
163
+
164
+ results, errors = res.get()
165
+ if results:
166
+ f_out.writelines(results)
167
+ if errors:
168
+ f_err.writelines(errors)
169
+
170
+ current_value = progress_counter.value
171
+ pbar.update(current_value - last_value)
172
+
173
+ except Exception as e:
174
+ print(f"\n처리 중 심각한 오류 발생: {e}")
175
+
176
+ print(f"\n> 형태소 분석 및 전처리가 완료되었습니다.")
177
+ print(f"> 전체 결과는 다음 경로에 저장/추가되었습니다: {output_file_path}")