RD_relation/relation/join_qanon_rag.py

86 lines
3.6 KiB
Python
Raw Permalink Normal View History

2025-01-19 16:42:36 +00:00
import json
from tqdm import tqdm
import numpy as np
import time
from hazm import *
from nltk.chunk import tree2conlltags
print('start')
start_time = time.time()
inputfile = open('./data/main_qanon_170k_metadata.json', "r", encoding='utf-8')
data = json.load(inputfile)
inputfile.close()
dict = {}
datalength = len(data)
tagger = POSTagger(model='pos_tagger.model')
chunker = Chunker(model='chunker.model')
count = 0
new_qanon_sections = []
long_chunks = 0
for qid in tqdm(data):
if(qid == "qq114127"):
pass
print('progress: ' + str(((count + 1)/datalength)*100))
q_sections = data[qid]
new_qanon_chunks = []
pivot_index = 0
for index, section in enumerate(q_sections):
content = section['content']
child_order = section['child_order']
level =section['level']
if index == 0:
pivot_index = index
pivot_level = level
# به دست آوردن لول ماده قبل از ماده جاری
if (index == 0):
prev_section_level = 0
else:
prev_section_level = q_sections[index-1]['level']
# حالتی که ماده جاری، آخرین ماده از قانون جاری باشد
if (index+1 == len(q_sections)):
if(level <= prev_section_level):# در این حالت، ماده جاری، آخرین ماده قانون است و در مرحله قبل اضافه نشده است بنابراین به تنهایی باید به مجموعه ماده های قانون جاری اضافه شود
new_chunk = content
else:# در این حالت، سکشن در مرحله قبل به ماده والد خود اضافه شده است
continue
else:
next_section_level = q_sections[index+1]['level']
if (int(pivot_level)+1) == (int(next_section_level)):# اگر ماده بعدی، فرزند ماده فعلی بود، دو ماده را به هم بچسباند. در این روش ممکن است تکرار رخ دهد، اما مهم نیست
new_chunk = content + " " + q_sections[index+1]['content']
count += 1
if len(new_chunk.split()) > 512:
print("long chunk !!!")
long_chunks += 1
elif(int(pivot_level) +1 > (int(next_section_level))):# ماده بعدی از نظر لول، هم ارز ماده فعلی است
pivot_index = (int(index+1))# ماده بعدی به عنوان پیووت قرار می گیرد
pivot_level = (int(next_section_level))# ماده بعدی به عنوان پیووت قرار می گیرد
new_chunk = content
else: #(int(pivot_index) +1 < (int(next_section_level))) for example: 2<3
pivot_index = (int(level)) # ماده فعلی به عنوان پیووت قرار می گیرد
new_chunk = content
new_qanon_chunks.append(new_chunk)
new_qanon_sections.append({
"qanon_id": qid,
"new_sections": new_qanon_chunks
})
print("long_chunks: " + str(long_chunks))
print()
outputfile = open('./data/new_joint_qanon_170k2.json', "w", encoding='utf-8')
outputfile.write(json.dumps(new_qanon_sections, ensure_ascii=False, indent = 4))
outputfile.close()
print(len(new_qanon_sections))
print(f'join count {count}')
end_time = time.time()
print(f"elapsed time: {end_time-start_time}")
print("end")