common -> app.common.

This commit is contained in:
hsafaei
2025-09-18 14:32:19 +03:30
parent a507fff651
commit b4d5671809
83 changed files with 192 additions and 163 deletions
+2
View File
@@ -0,0 +1,2 @@
+246
View File
@@ -0,0 +1,246 @@
import re
import os
import sys
import zipfile
from dotenv import load_dotenv
from ..common.text_normalizer import TextNormalizer
# from general import *
from ..common.general_functions import *
from ..common.elastic_helper import ElasticHelper
### --------------------------------------------------------------
## این کد برای استخراج و بهینه سازی کلیدواژه های تولید شده با مدلهای زبانی بزرگ و انتقال به الاستیک نوشته شد
## کلیدواژه ها با ساختار مشخص و مقداری خطا تولید شده بودند
def moveKeywords(elastic, index_name_o, path_file, fields=['content'], body={}):
text_normal = TextNormalizer()
dic_main = json.loads(open(path_file,'r', encoding="utf-8").read())
index = 0
percent_prev = 0
list=[]
for item in dic_main:
index += 1
percent = int((index / len(dic_main)) * 100)
if percent != percent_prev:
print("progress -> %.2f %%" % percent)
percent_prev = percent
id = item['id']
keywords = set()
for key in item['keywords']:
# "•\t1.\tقانون جدید",
# "2.\tکلاه برداری"
key = text_normal.normalize_qanon(key)
key = key.replace('\t', ' ').strip()
key = key.replace('\n', ' ').strip()
key = key.replace('\r', ' ').strip()
key = key.strip(' •.')
key = re.sub(r"^[ \t]*[\d•]+[ .\t]*", '', key).strip()
if key :
key = text_normal.normalize_qanon(key)
keywords.add(key)
content = item['content']
words = text_normal.split_words(content)
sorted_keys=[]
if len(keywords) > 10 and (len(words) * 2) < len(keywords) :
# print('id ', id , ' content', content)
print('id ', id , 'len words ', len(words) , ' len keywords', len(keywords) )
list_temp = sorted(keywords, key=len)
sorted_keys=list_temp[0:len(words)]
# print( ' keywords : ', sorted_keys)
# exit()
else:
sorted_keys = sorted(keywords, key=len)
list.append({
'_id': id,
'_source': {
"ai_keywords" : sorted_keys
}
})
if len(list) > 200 :
elastic.updateBulkList(list, index_name_o)
list = []
if len(list) :
elastic.updateBulkList(list, index_name_o)
### --------------------------------------------------------------
## برای انتقال جملات ساده سازی شده توسط مدلهای زبانی بزرگ به الاستیک قانون نوشته شد
def moveZipSimplifies(elastic, index_name, file_path):
fileNo = 0
with zipfile.ZipFile(file_path, 'r') as zObject:
fileNo +=1
print("="*10, " zip fileNo: " , fileNo ," - ( ", index_name," ) | File Numbers:" ,len(zObject.namelist()) , "=" * 10)
packNo = 0
for filename in zObject.namelist():
packNo += 1
print("index:" , index_name , '=>' , filename )
with zObject.open(filename) as file:
data = json.loads(file.read())
moveSimplifies(elastic, index_name, data)
elastic.es.indices.refresh(index=index_name)
print(elastic.es.cat.count(index=index_name, format="json"))
print(" END Of Import to elastic ", index_name ,"\n")
def moveSimplifies(elastic, index_name_o, data):
text_normal = TextNormalizer()
index = 0
percent_prev = 0
list_bulk=[]
for item in data:
index += 1
# percent = int((index / len(data)) * 100)
# if percent != percent_prev:
# print("progress -> %.2f %%" % percent)
# percent_prev = percent
id = item['id']
simplified = item['simplified']
list_simp = simplified.split('\n')
simplifies = set()
for key in list_simp:
# "1.ddddd",
key = key.replace('\t', ' ').strip()
key = key.replace('\r', ' ').strip()
key = key.strip(' •.')
key = re.sub(r"^[ \t]*[\d•]+[ .\t]*", '', key).strip()
if key :
key = text_normal.normalize_qanon(key)
simplifies.add(key)
list_bulk.append({
'_id': id,
'_source': {
"simplifies" : list(simplifies)
}
})
if len(list_bulk) > 200 :
elastic.updateBulkList(list_bulk, index_name_o)
list_bulk = []
if len(list_bulk) :
elastic.updateBulkList(list_bulk, index_name_o)
def moveClassifierAiCodes(elastic, index_name_o, data):
text_normal = TextNormalizer()
index = 0
percent_prev = 0
send_round = 1
list_bulk=[]
for item in data:
index += 1
percent = int((index / len(data)) * 100)
if percent != percent_prev:
print("progress -> %.2f %%" % percent)
percent_prev = percent
id = item
best_code = data[item]['best-class']
other_codes = data[item]['other-classes']
ai_code = best_code
ai_codes = other_codes
#----------------------------------------------
for label_doc in ai_codes:
label = label_doc["label"]
label = re.sub(r"\u00AD|\u00AC", "\u200C", label) # نیم اسپیس خاص
label = label.replace(" ", " ")
label = label.replace("ـ", "")
label = label.strip().strip("\u200C")
label_doc["label"] = label
if label_doc["score"] >= 1 :
label_doc["score"] = label_doc["score"] / 100
if ai_code["score"] >= 1 :
ai_code["score"] = ai_code["score"] / 100
label = ai_code["label"]
label = re.sub(r"\u00AD|\u00AC", "\u200C", label) # نیم اسپیس خاص
label = label.replace(" ", " ")
label = label.replace("ـ", "")
label = label.strip().strip("\u200C")
ai_code["label"] = label
#----------------------------------------------
list_bulk.append({
'_id': id,
'_source': {
"ai_code" : ai_code,
"ai_codes" : ai_codes
}
})
if len(list_bulk) > 200 :
elastic.updateBulkList(list_bulk, index_name_o)
list_bulk = []
# print(f"send_round -> {send_round}")
send_round += 1
if len(list_bulk) :
elastic.updateBulkList(list_bulk, index_name_o)
# print(f"last ::: send_round -> {send_round}")
load_dotenv(dotenv_path='config.env')
# host=os.getenv('HOST_160')
# password=os.getenv('HOST_160_PASS')
# host=os.getenv('HOST_112')
# password=os.getenv('HOST_112_PASS')
host=os.getenv('HOST_113')
password=os.getenv('HOST_113_PASS')
# host=os.getenv('HOST_60')
# password=os.getenv('HOST_60_PASS')
print(host)
# print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# moveKeywords(elastic,"mj_qa_section", "data/sections_kw_llama8b_170k_concatenated.json")
# moveKeywords(elastic,"mj_qa_section", "data/sections_kw_llama8b_40k_concatenated.json")
# moveZipSimplifies(elastic,"mj_qa_section", "G:\Work\_majles\_data\simpilified_final.zip")
#-----نسخه قبلی اجرای مدل
# with open("./data/all_sections_classes.json", "r", encoding="utf-8") as f:
# classes = json.load(f)
#-----نسخه آخر اجرای مدل
# with open("./data/all_sections_classes_full_140405.json", "r", encoding="utf-8") as f:
# classes = json.load(f)
# moveClassifierAiCodes(elastic,"mj_qa_section", classes)
# print('finished!')
#-----داده های جدید نسخه آخر اجرای مدل
with open("./data/all_sections_classes_new_140406.json", "r", encoding="utf-8") as f:
classes = json.load(f)
moveClassifierAiCodes(elastic,"mj_qa_section", classes)
print('finished!')
+41
View File
@@ -0,0 +1,41 @@
import json
import datetime
from app.common.general_functions import read_file_by_address, read_from_json
if __name__ == "__main__":
start_time = datetime.datetime.now()
print(f'start time: {start_time}')
# inputfile = open('./data/main_classes_dataset_03.json', "r", encoding='utf-8')
# inputfile = open('./data/sections_40k_normalized.json', "r", encoding='utf-8')
# data = json.load(inputfile)
# inputfile.close()
# prev_ids = read_file_by_address('./data/prev_kw_ids_170k.txt').splitlines()
counter = 1
file_counter = 1
temp_dict = []
temp_data_text = ''
period_sections = []
period_ids_text = f'***** file number: {file_counter} *****\n'
finall_sections = []
for file_counter in range(1,41):
# inputfile = open(f'./data/sections_kw_llama8b_170k_{str(file_counter)}.json', "a+", encoding='utf-8')
data = read_from_json(f'./data/sections_kw_llama8b_40k_{str(file_counter)}.json')
print(f'file {file_counter} is in proccess ... ')
for item in data:
id = item['id']
finall_sections.append(item)
outputfile = open(f'./data/sections_kw_llama8b_40k_concatenated.json', "a+", encoding='utf-8')
outputfile.write(json.dumps(finall_sections, ensure_ascii=False, indent=2))
outputfile.close()
end_time = datetime.datetime.now()
print(f"end_time: {end_time}")
print("end")
+117
View File
@@ -0,0 +1,117 @@
from app.common.text_normalizer import TextNormalizer
from app.common.general_functions import *
from app.common.elastic_helper import ElasticHelper
dict_qanon = {}
def getContext(parent_id, qanon_title):
context = ''
context += f"\n** قانون: {qanon_title} "
pid = parent_id
path=''
while True:
if not pid or pid == '0' or pid not in dict_qanon:
break # اگر pid '0' است یا در dict_qanon وجود ندارد، حلقه متوقف می‌شود
# دریافت content والد
parent_content = dict_qanon[pid].get("content", "")
if parent_content :
path += f"\\{parent_content}"
# بروزرسانی pid به والد بالاتر
pid = dict_qanon[pid].get("parent_id", '0')
if path :
context += f"\n** سرفصل: {qanon_title} "
return context
def create_context_ai(elastic, index_name_i, fields=["qanon_title", "tree" ], index_name_o = '' ):
body={
# "query": {
# "bool": {
# "must_not": [
# {"exists": {"field": "nlp_parser.type"}},
# {"match": {"content_len": 0}},
# {"match": {"parse_state": 1}},
# {"match": {"parse_state": 2}}
# ]
# }
# },
"sort": [
{
"qanon_id": {"order": "asc"},
"child_order": {"order": "asc"}
}
]
}
if index_name_o == '' :
index_name_o = index_name_i
try:
try:
list = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
count = 0
cur_qanon_id = 0
text_normal = TextNormalizer()
result = []
data={}
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
content = entry.get("content", "")
content = text_normal.normalize_qanon(content)
qanon_title = entry.get("qanon_title", "")
parent_id = entry.get("parent_id", "")
other_info = entry.get("other_info", "")
level = other_info["level"]
qanon_id = entry.get("qanon_id", "")
data = {}
### /////////////////////////////////
# جمله اصلی برای سند فعلی
if parent_id == '0' or parent_id == 0 or parent_id == '':
dict_qanon = {}
if qanon_id != cur_qanon_id :
dict_qanon = {}
cur_qanon_id = qanon_id
dict_qanon[id] = {
"content" : content,
"other_info" : other_info,
"id" : id,
"parent_id" : parent_id,
}
context = getContext(parent_id, qanon_title)
data["context_llm"] = context
#### ///////////////////////////////////
eid = id
try:
resp = elastic.update_index_doc(True, index_name_o, eid, data)
#if not update :
# dicIds[eid] = True
except Exception as e:
save_error(id, e)
except Exception as e:
save_error(id, e)
+167
View File
@@ -0,0 +1,167 @@
from time import time
import requests
from app.common.general_functions import *
from app.common.config_base import *
from app.common.text_normalizer import TextNormalizer
def fill_chunk_tags(elasticHelper, ai_url, index_name_o = "mj_qa_section", path_resource='resource/my/') :
id = ""
body = {
### این فهرست قوانینی است که تعداد زیادی از اجزاء دارای لول بزرگتر از 8 دارند
# "query": {
# "bool": {
# "must_not": [
# {
# "terms": {
# "qanon_id":["qq86911", "qq83307", "qq178971", "qq111830", "qq233930", "qq85434"]
# }
# }
# ]
# }
# },
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "asc"}}
]
}
try:
try:
list = elasticHelper.es_iterate_all_documents(index_name_o, body)
except Exception as e:
save_error(0, e)
count = 0
print('*' * 20 , ' count=', elasticHelper.total)
path_heading=[]
level_parent= 0
file_error = open('error_fill_nlp_tags.txt', 'w+', encoding='utf-8')
text_normal = TextNormalizer()
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
qanon_id = entry.get("qanon_id", "0")
other_info = entry.get("other_info", {})
content = entry.get("content", "")
html = entry.get("html", "")
chunk_tags = []
if html :
content = ''
if not content :
continue
content_normal = text_normal.normalize_qanon_test(content)
payload={
'text': content_normal
}
response = requests.request("POST", ai_url, headers=HEADERS, json=payload)
if response.status_code == 500 :
print(response.text)
continue
resp = json.loads(response.text)
# print(resp)
pos_tags = []
chunk_tags = ''
for item in resp['data'] :
item_pos_tags = item['pos_tags']
for pt in item_pos_tags :
pos_tags.append({
"word": pt[0],
"hazm_tags": pt[1].split(',')
})
if chunk_tags :
chunk_tags += ' ' + item['chunk_tree']
else :
chunk_tags = item['chunk_tree']
####--------------------------------------
# chunk_keywords = []
# # chunks = chunk_tags.replace('] [', ']#[').split('#')
# pattern = r'\[([^\[\]]+) ([A-Z]{1,10})\] '
# iter = re.finditer(pattern, chunk_tags.strip())
# index = 0
# prev_tag = ''
# prev_text = ''
# for item in iter :
# # print(item)
# text = item[0]
# tag = item[1]
# start_index = item.start()
# end_index = item.end()
# if index < start_index :
# word = chunk_tags[index:start_index].strip('()[]:.?!-/«»؟,،؛ ').strip()
# if word in ['که', 'و', 'از', 'تا', 'ولی', 'مگر', 'چنانچه', ''] :
# chunk_keywords.append({
# "text": word,
# "tag": ['PP']
# })
# elif word in ['است', 'شد', 'شود', 'گردد'] :
# if prev_tag in ['V', 'VP'] :
# ck = chunk_keywords[-1]
# ck['text'] += ' ' + word
# chunk_keywords[-1] = ck
# elif prev_tag in ['NOUN'] :
# ck = chunk_keywords[-1]
# ck['text'] += ' ' + word
# ck['tag'] = 'VP'
# chunk_keywords[-1] = ck
# elif word:
# print('id ', id, ' ', word)
# # chunk_keywords.append({
# # "text": word,
# # "tag": ['nnn']
# # })
# else :
# if text in ['است', 'شد', 'شود', 'گردد'] :
# pass
# else:
# pass
# chunk_keywords.append({
# "text": item[1],
# "tag": item[2]
# })
# index = item.end()
# # print(chunk_keywords)
#### ----------------------------------------
data = {}
data["pos_tags"]= pos_tags
data["chunk_tags"]= chunk_tags
if content_normal != content :
data["content_normal"]= content_normal
# data["chunk_keywords"]= chunk_keywords
update = True
eid = id
try:
resp = elasticHelper.update_index_doc(update, index_name_o, eid, data)
except Exception as e:
save_error(id, e)
except Exception as e:
save_error(id, e)
# print("Exception: " + str(e))
# print( e)
# print("%s -> %.2f " % (id , (counter / total) if total > 0 else 0))
# try:
# print('ts_date:'+ts_date)
# except:
# print('not definded')
file_error.close()
print("=" * 10, " fill_content_nlp finished")
+191
View File
@@ -0,0 +1,191 @@
import os
from dotenv import load_dotenv
from app.common.text_normalizer import TextNormalizer
# from general import *
from app.common.general_functions import *
from app.common.elastic_helper import ElasticHelper
body = {
# "query": {
# "bool": {
# "must_not": [
# {"exists": {"field": "nlp_parser.type"}},
# {"match": {"content_len": 0}},
# {"match": {"parse_state": 1}},
# {"match": {"parse_state": 2}}
# ]
# }
# }
}
def exportTokensMulti(elastic, index_name_i, prefixname, fields=['content'], body={}, path_out="./data/"):
counter = 0
total = 0
id = ""
dict_word_count = {}
dict_word_count2 = {}
try:
try:
list = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
count = 0
text_normal = TextNormalizer()
result = []
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
for field in fields :
content = entry.get(field, "")
# words = content.split()
words = text_normal.split_words(content)
for word in words:
if word in dict_word_count :
dict_word_count[word] += 1
else :
dict_word_count[word] = 1
content = text_normal.normalize_qanon_test(content)
words = text_normal.split_words(content)
for word in words:
if word in dict_word_count2 :
dict_word_count2[word] += 1
else :
dict_word_count2[word] = 1
if dict_word_count :
sorted_dict_words = dict(sorted(dict_word_count.items(), key=lambda x: x[1], reverse=True))
filtered_dict = {k:v for (k,v) in sorted_dict_words.items() if not re.match(r'[a-zA-Z\d]+', k) }
with open(path_out+prefixname+"1.txt", "w", encoding="utf-8") as f:
json.dump(filtered_dict, f, ensure_ascii=False, indent=4)
if dict_word_count2 :
sorted_dict_words = dict(sorted(dict_word_count2.items(), key=lambda x: x[1], reverse=True))
filtered_dict = {k:v for (k,v) in sorted_dict_words.items() if not re.match(r'[a-zA-Z\d]+', k) }
with open(path_out+prefixname+"2.txt", "w", encoding="utf-8") as f:
json.dump(filtered_dict, f, ensure_ascii=False, indent=4)
except Exception as e:
save_error(id, e)
def exportTokens(elastic, index_name_i, fields=['content'], body={}):
dict_word_count={}
counter = 0
total = 0
id = ""
try:
try:
list = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
count = 0
text_normal = TextNormalizer()
result = []
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
for field in fields :
content = entry.get(field, "")
# content = text_normal.replace_alphabets(content)
# words = content.split()
words = text_normal.split_words(content)
for word in words:
if word in dict_word_count :
dict_word_count[word] += 1
else :
dict_word_count[word] = 1
return dict(dict_word_count)
except Exception as e:
save_error(id, e)
def exportTokensToFile(elastic, index_name_i, filename, fields=['content'], body={}, path_out="./data/"):
dict_words = exportTokens(elastic, index_name_i, fields, body)
if dict_words :
sorted_dict_words = dict(sorted(dict_words.items(), key=lambda x: x[1], reverse=True))
filtered_dict = {k:v for (k,v) in sorted_dict_words.items() if not re.match(r'[a-zA-Z\d]+', k) }
with open(path_out+filename, "w", encoding="utf-8") as f:
json.dump(filtered_dict, f, ensure_ascii=False, indent=4)
def diff_files_to_file(file_dict1, file_dict2, filename, path_out="./data/"):
dict1 = json.loads(open(path_out+file_dict1, "r", encoding="utf-8").read())
dict2 = json.loads(open(path_out+file_dict2, "r", encoding="utf-8").read())
return diff_to_file(dict1, dict2, filename, False, path_out)
def diff_to_file(dict1, dict2, filename, by_diff_count=False, path_out="./data/"):
dict_no_exist = {}
dict_diff_count = {}
for item in dict1:
if item not in dict2 :
dict_no_exist[item] = dict1[item]
elif dict1[item] != dict2[item] :
dict_diff_count[item] = dict2[item] - dict1[item]
with open(path_out+filename, "w", encoding="utf-8") as f:
json.dump(dict_no_exist, f, ensure_ascii=False, indent=4)
if by_diff_count :
with open(path_out+filename, "a+", encoding="utf-8") as f:
json.dump(dict_diff_count, f, ensure_ascii=False, indent=4)
load_dotenv(dotenv_path='config.env')
host=os.getenv('HOST_160')
password=os.getenv('HOST_160_PASS')
# host=os.getenv('HOST_112')
# password=os.getenv('HOST_112_PASS')
# host=os.getenv('HOST_60')
# password=os.getenv('HOST_60_PASS')
print(host)
# print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
#exportTokensToFile(elastic,"mj_qa_section", "content_mj_qa_section_1.txt")
# exportTokensToFile(elastic,"test_qa_section", "content_test_qa_section_1.txt")
# exportTokensToFile(elastic,"test_qa_section", "content_test_qa_section_normal_1.txt", ["content_normal"])
# diff_files_to_file("content_mj_qa_section_1.txt", "content_test_qa_section_1.txt", "diff_prev_content.txt")
# diff_files_to_file("content_test_qa_section_1.txt", "content_mj_qa_section_1.txt", "diff_content_prev.txt")
# diff_files_to_file("content_test_qa_section_normal_1.txt", "content_test_qa_section_1.txt", "diff_normal_content.txt")
# diff_files_to_file("content_test_qa_section_1.txt", "content_test_qa_section_normal_1.txt", "diff_content_normal.txt")
# exportTokensToFile(elastic,"mj_qa_section", "content_mj_qa_section_1.txt")
#exportTokensMulti(elastic,"mj_qa_section", "mj_qa_section")
diff_files_to_file("mj_qa_section1.txt", "mj_qa_section2.txt", "diff_1_2.txt")
diff_files_to_file("mj_qa_section2.txt", "mj_qa_section1.txt", "diff_2_1.txt")
print("finished")
+144
View File
@@ -0,0 +1,144 @@
import re
import json
from app.common.text_normalizer import TextNormalizer
text_normal = TextNormalizer()
def tag_separation(text, default_tag):
parts = text.split("=")
title = parts[0].strip()
tag = parts[1].strip() if len(parts) > 1 else default_tag
return title, tag
def recursiveMatch(startIndex , i, tokens, dict, result):
end = -1
if i >= len(tokens):
return end
word = tokens[i]
if word in dict:
end = recursiveMatch(startIndex, i+1, tokens, dict[word], result)
if end and end != -1: # finded
return end
elif '=' in dict[word]:
end = i+1
result.append({
"begin": startIndex,
"end": i,
"text": " ".join(tokens[startIndex:end]),
"result_key": dict[word]['='],
})
return end
else:
return end
def find_entities(text, entity_dict):
words = text_normal.split_words(text)
results = []
i = 0
while i < len(words):
end = recursiveMatch(i, i, words, entity_dict, results)
if end and end != -1:
i = end
else:
i += 1
return results
def create_nested_dictionary(lines, nested_dict={}):
for line in lines:
line = text_normal.normalize_qanon(line)
title, tag = tag_separation(line, '')
words = text_normal.split_words(title)
dict_current_level = nested_dict
for word in words:
if word not in dict_current_level:
dict_current_level[word] = {}
dict_current_level = dict_current_level[word]
if '=' in dict_current_level and dict_current_level['='] != tag:
dict_current_level['='] += ',' + tag
else:
dict_current_level['='] = tag
return nested_dict
def create_title_tree(title_with_tag, tree):
title, tag = tag_separation(title_with_tag, "ref")
words = text_normal.split_words(title)
dict_current_level = tree
for word in words:
if word not in dict_current_level:
dict_current_level[word] = {}
dict_current_level = dict_current_level[word]
dict_current_level['='] = tag
def create_province_tree(data, tree):
for key, values in data.items():
province_name, province_tag = tag_separation(key, "loc")
words = text_normal.split_words(province_name)
dict_current_level = tree
for word in words:
if word not in dict_current_level:
dict_current_level[word] = {}
dict_current_level = dict_current_level[word]
dict_current_level['='] = province_tag
for value in values:
city_name, city_tag = tag_separation(value, "loc")
city_words = text_normal.split_words(city_name)
city_level = tree
for word in city_words:
if word not in city_level:
city_level[word] = {}
city_level = city_level[word]
city_level['='] = city_tag
try:
with open('./data/list_ORG.txt', 'r', encoding='utf-8') as f:
org_text = f.read()
except FileNotFoundError:
print("Error: list_ORG.txt file not found.")
exit()
org_lines = org_text.strip().split('\n')
organization_dict = create_nested_dictionary(org_lines)
try:
with open("./data/qanon_titles.json", "r", encoding="utf-8") as f:
title_data = json.load(f)
except FileNotFoundError:
print("Error: qanon_titles.json file not found.")
exit()
title_tree = {}
for item in title_data:
create_title_tree(item["title"], title_tree)
text = "تمامی وزارتخانه ها و سازمان‌های کشور از جمله وزارت فرهنگ و ارشاد اسلامی وزارت کشور با جمعی از کارکنان وزارت نیرو در محل سازمان حفظ محیط زیست دیدار و گفتگو کردند. همچنین ماده 5 قانون اساسی جمهوری اسلامی ایران بر این امر تأکید دارد. قانون الحاق یک ماده به قانون حمایت از خانواده و جوانی جمعیت در استان تهران تهران و قم جعفريه"
# #text = "وزارت فرهنگ و ارشاد اسلامی با جمعی از کارکنان وزارت نیرو در محل سازمان حفظ محیط زیست دیدار و گفتگو کردند"
# #text = "تمامی وزارتخانه‌ها و سازمانهای کشور از جمله وزارت فرهنگ و ارشاد اسلامی وزارت کشور با جمعی از کارکنان وزارت نیرو در محل سازمان حفظ محیط زیست دیدار و گفتگو کردند"
# #text = "تمامی وزارتخانه ها و سازمان‌های کشور از جمله وزارت فرهنگ و ارشاد اسلامی وزارت کشور با جمعی از کارکنان وزارت نیرو در محل سازمان حفظ محیط زیست دیدار و گفتگو کردند"
# #text = "تمامی ## و ## ## از جمله ## ## ## ## ## ## ## با جمعی از کارکنان ## ## در محل ## ## ## ## دیدار و گفتگو کردند"
# #text = "ماده 1 - براساس اصل 45 قانون اساسی جمهوری اسلامی ایران، آبهای دریاها و آبهای جاری در رودها و انهار طبیعی و دره‌ها و هر مسیر طبیعی ‌دیگر اعم از سطحی و زیر زمینی، سیلابها و فاضلابها و زه‌آبها و دریاچه‌ها و مردابها و برکه‌های طبیعی و چشمه‌ سارها و آبهای معدنی و منابع آبهای زیرزمینی از مشترکات بوده و در اختیار حکومت اسلامی است و طبق مصالح عامه از آنها بهره ‌برداری میشود. مسئولیت حفظ و اجازه و نظارت بر بهره‌ برداری از آنها به دولت محول میشود."
try:
with open("./data/province_tree.json", "r", encoding="utf-8") as f:
province_data = json.load(f)
except FileNotFoundError:
print("Error: province_tree.json file not found.")
exit()
province_tree = {}
create_province_tree(province_data, province_tree)
found_orgs = find_entities(text, organization_dict)
found_titles = find_entities(text, title_tree)
found_provinces = find_entities(text, province_tree)
# ترکیب نتایج
found_entities = found_orgs + found_titles + found_provinces
# ذخیره خروجی در فایل JSON
output_file = "./output/ner_found_entities.json"
with open(output_file, "w", encoding="utf-8") as f:
json.dump(found_entities, f, ensure_ascii=False, indent=4)
print(f"نتایج در فایل {output_file} ذخیره شد.")