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 @@
+594
View File
@@ -0,0 +1,594 @@
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 saveEmbedingContent()
##----- مرحله اول -----------------
## پردازش و پرکردن فیلدهای متنوع کمکی
def fill_nlp_tags(elasticHelper, index_name_o = "mj_qa_section_ai", 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"}}
]
}
useful_ids = {}
# useful_titles_al = []
# useful_finded = []
# خواندن کلمات موجود در فایل
with open( path_resource+"qanon_usefull.txt", 'r', encoding='utf-8') as f:
for line in f :
id = line.strip().split('=')[0]
if id not in useful_ids :
useful_ids[id] = 1
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')
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
#qanon_etebar = entry.get("qanon_etebar", "")
state_etebar = entry.get("state_etebar", "")
title_type = entry.get("title_type", "")
qanon_title = entry.get("qanon_title", "")
qanon_id = entry.get("qanon_id", "0")
other_info = entry.get("other_info", {})
parent_id = entry.get("parent_id", "0")
content = entry.get("content", "")
full_path = other_info["full_path"]
nlp_tags = []
#"full_path": "ماده واحده>فصل ششم>بخش سوم>قسمت چهارم>فصل هشتم>ماده 153>بند ب>جزء 4",
paths = full_path.split('>')
last_path = ''
if paths :
last_path = paths[-1]
level_2 = len(paths)
###--------------------شناسایی بزرگی کوچکی متن -------------------
word_len = len(split_words(content))
###--------------------شناسایی بزرگی کوچکی متن -------------------
if word_len > 100 :
nlp_tags.append("words_big")
elif word_len > 50 :
nlp_tags.append("words_medium")
else :
nlp_tags.append("words_small")
###--------------------شناسایی هدینگ بودن -------------------
prefix, title, content_type = normalHeadingTitle(content, last_path)
if not parent_id or parent_id == '0' or parent_id==0 :
path_heading = []
level_parent = 0
###--------------------شناسایی قوانین پرکاربرد -------------------
if qanon_id in useful_ids:
nlp_tags.append("qanon_usefull")
###-------------------- تعیین مسیر هدینگ -------------------
## هرچند با پرنت آی دی این خالی می شود ولی برای مطمئن کاری این شرط اضافه شد
elif full_path=='عنوان' or full_path=='موخره' or full_path=='امضاء' :
path_heading = []
level_parent = 0
elif level_2 < level_parent :
diff = level_parent - level_2
while diff > 0 and path_heading :
path_heading.pop()
diff = diff - 1
level_parent = level_2
# print('id :', id , ' --diff ', diff, path_heading )
if level_2 >= level_parent :
# برای اجزاء بعدی شناسایی و ذخیره می شود نه جزء جاری
if prefix != '' and title != '':
if level_2 == level_parent and path_heading :
path_heading.pop()
if len(title) < 256 :
path_heading.append(title)
nlp_tags.append("heading")
level_parent = level_2
###--------------------------------------------------------
full_path_prev = full_path
full_path = title_type + ' :: ' + full_path
heading_in_content = ''
if "heading" in nlp_tags :
nlp_tags.append("concept_no")
elif 'تفسیر' in state_etebar or 'تفسیر' in last_path :
nlp_tags.append("concept_side")
elif 'عنوان' in last_path or 'موخره' in last_path or 'امضاء' in last_path or 'سربرگ' in last_path or 'فهرست' in last_path or 'منشور' in last_path :
nlp_tags.append("concept_no")
elif 'ماده' in last_path or 'اصل' in last_path or 'متن' in last_path or 'مقدمه' in last_path or 'نامه' in last_path or 'کلیات' in last_path or 'قسمت' in last_path or 'توضیح' in last_path or 'سوال' in last_path or 'استفساریه' in last_path :
nlp_tags.append("concept_base")
elif 'بند' in last_path or 'جزء' in last_path or 'زیرجزء' in last_path or 'شماره' in last_path or 'ردیف' in last_path or 'پاورقی' in last_path or 'اشاره' in last_path or 'تنبیه' in last_path or 'بخش' in last_path or 'جواب' in last_path or 'مقرره' in last_path :
nlp_tags.append("concept_week")
elif 'تبصره' in last_path or 'بخش' in last_path or 'تذکر' in last_path or 'توصیه' in last_path or 'توجه' in last_path :
nlp_tags.append("concept_middle")
elif 'الحاقی' in state_etebar or 'الحاقی' in last_path :
nlp_tags.append("concept_week")
elif 'جدول' in last_path :
nlp_tags.append("concept_bad")
elif content_type in ['تبصره','بخش','تذکر'] :
nlp_tags.append("concept_middle")
elif content_type in ['ماده'] :
nlp_tags.append("concept_base")
# elif qanon_etebar == 'منسوخه' :
# pass
elif 'پروتکل' in full_path or 'موافقتنامه' in full_path or 'قطعنامه' in full_path or 'پیوست' in full_path or 'عهدنامه' in full_path or 'توافقنامه' in full_path or 'معاهده' in full_path or 'کنوانسیون' in full_path or 'قرارداد' in full_path :
if not title :
nlp_tags.append("concept_bad")
elif len(title) < 50 :
if prefix :
nlp_tags.append("concept_head")
heading_in_content = title
else :
nlp_tags.append("concept_week")
else :
nlp_tags.append("concept_base")
elif prefix :
if title and len(title) < 50 :
file_error.write('---***---- data id=' + id + ' full_path : ' + full_path + ' prefix : '+ prefix +' --- '+ title + '\n')
print('---***---- data id=', id, ' full_path : ', full_path , ' prefix : ', prefix ,' --- ', title)
else :
if title and len(title) < 50:
if 'فصل' in last_path or 'مبحث' in last_path :
nlp_tags.append("concept_head")
heading_in_content = title
if full_path_prev == '' :
nlp_tags.append("concept_bad")
else :
file_error.write('------- data id='+ id + ' full_path : '+ full_path + ' prefix : '+ prefix +' --- '+ title + '\n')
print('------- data id=', id, ' full_path : ', full_path , ' prefix : ', prefix ,' --- ', title)
elif len(title) >= 50 :
if full_path_prev == '' :
nlp_tags.append("concept_bad")
else :
file_error.write('### ####### error data id='+ id + ' full_path : '+ full_path + ' prefix : '+ prefix +' --- '+ title + '\n')
print('### ####### error data id=', id, ' full_path : ', full_path , ' prefix : ', prefix ,' --- ', title)
###--------------------------------------------------------
## فقط در همین جزء ثبت شود
path_heading2 = path_heading
if heading_in_content :
path_heading2.append(heading_in_content)
## ----------------------------------------
data = {}
data["nlp_tags"]= nlp_tags
data["path_headings"]= path_heading2
data["word_len"] = word_len
data["level"]= level_2
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")
##----- مرحله دوم -----------------
## شناسایی فرزندان اجزاء اصلی
def extract_nlp_childs(elasticHelper, index_name_i = "mj_qa_section", index_name_o = "") :
counter = 0
total = 0
id = ""
body={
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "desc"}}
]
}
if not index_name_o :
index_name_o = index_name_i
dicParents = {}
try:
try:
list = elasticHelper.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
count = 0
qanon_id_prev = ""
parent_id_prev = "0"
count_normal = 0
count_un_normal = 0
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
content = entry.get("content", "")
path_headings = entry.get("path_headings", [])
word_len = entry.get("word_len", [])
qanon_id = entry.get("qanon_id", "0")
parent_id = entry.get("parent_id", "0")
nlp_tags = entry.get("nlp_tags", [])
## ثبت اطلاعات
if qanon_id != qanon_id_prev and dicParents:
list = []
for key, value in dicParents.items():
list.append({
'_id': key,
'_source': {
"nlp_childs" : value
}
})
word_len = 0
for child in value :
word_len += child["word_len"]
if word_len > 512 :
count_un_normal +=1
print('--- id', key , ' child_count:', len(value), ' words:', word_len, ' count_normal:', count_normal, ' count_un_normal:', count_un_normal)
else :
count_normal +=1
elasticHelper.updateBulkList(list, index_name_o)
dicParents = {}
qanon_id_prev = qanon_id
### نیازی به بردار سازی و جستجوی معنایی یا ارتباط یابی نیست
if 'concept_no' in nlp_tags or 'concept_bad' in nlp_tags or 'concept_base' in nlp_tags :
continue
### تا حد امکان با محتوای اصلی قبل، بردار شود و همانجا ذخیره شود
elif 'concept_week' in nlp_tags or 'concept_middle' in nlp_tags or 'concept_side' in nlp_tags :
if parent_id and parent_id != '0' and parent_id != 0 :
#if 'words_small' in nlp_tags or 'words_small' in nlp_tags :
if parent_id not in dicParents :
dicParents[parent_id] = []
dicParents[parent_id].append({
"word_len": word_len,
"id": id ,
# "content" : content
})
continue
except Exception as e:
# save_error(id, e)
print("Exception: " + e)
print( e)
print("%s -> %.2f " % (id , (counter / total) if total > 0 else 0))
print("=" * 10, "import_data_embeding finished")
##----- مرحله سوم -----------------
## تولید بردار برای اجزاء به همراه اطلاعات کناری و کمکی
def import_data_embeding(elasticHelper, ai_url_vec, index_name_i = "mj_qa_section", index_name_o = "mj_qa_section_ai", field_content="content") :
id = ""
body={
# "query": {
# "bool": {
# "must_not": [
# {
# "terms": {
# "nlp_tags": ["concept_no","concept_bad"]
# }
# }
# ]
# }
# },
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "asc"}}
]
}
dicParents = {}
try:
try:
list = elasticHelper.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
count = 0
qanon_id_prev = ""
parent_state = {}
parent_entry = {}
prev_entry_child = {}
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
content = entry.get(field_content, "")
path_headings = entry.get("path_headings", [])
qanon_title = entry.get("qanon_title", [])
word_len = entry.get("word_len", [])
qanon_id = entry.get("qanon_id", "0")
parent_id = entry.get("parent_id", "0")
nlp_tags = entry.get("nlp_tags", [])
nlp_childs = entry.get("nlp_childs", [])
qanon_id_prev = qanon_id
### نیازی به بردار سازی و جستجوی معنایی یا ارتباط یابی نیست
if 'concept_no' in nlp_tags or 'concept_bad' in nlp_tags or not content:
continue
content_emb = ''
content_offset = ' '
data = entry
word_len_childs = 0
if nlp_childs and len(nlp_childs) :
## اگر پدر و فرزندهای قبلی چیزی هنوز مونده ، بردارسازی باید شود
if prev_entry_child :
eid = prev_entry_child.get("id", "")
content = prev_entry_child.get(field_content, "")
data = prev_entry_child
content_offset = parent_state["content_offset"]
content_emb = parent_state["content"] + "\n" + content + "\n"+ parent_state["content_emb"]
data["content_emb"] = content_emb
prev_entry_child = {}
# word_len_childs = 0
# for item in nlp_childs :
# word_len_childs += item["word_len"]
#word_len_total = word_len + word_len_childs
content_offset = 'در ' + qanon_title + ' درباره '
for hed in path_headings :
content_offset += ' ' + hed.strip()
word_len_offset = len(split_words(content_offset))
parent_state = {
"id" : id,
"word_len" : word_len,
"word_len_offset" : word_len_offset,
"nlp_childs" : nlp_childs,
"content" : content,
"content_offset" : content_offset,
"word_len_childs" : 0,
"content_emb" : "",
"is_parent_embedded" : 0
}
parent_entry = entry
### تا حد امکان با محتوای اصلی قبل، بردار شود و همانجا ذخیره شود
elif 'concept_week' in nlp_tags or 'concept_middle' in nlp_tags or 'concept_side' in nlp_tags :
if parent_state and parent_state["id"] == parent_id :
wl = parent_state["word_len"]
wl_of = parent_state["word_len_offset"]
wl_em = parent_state["word_len_childs"]
len_total = wl + wl_of + wl_em + word_len
## اگر جا داره که با محتوای ماده اصلی=، بردار سازی باشد
if len_total < 512 :
parent_state["word_len_childs"] += word_len
parent_state["content_emb"] = parent_state["content_emb"] + "\n" + content
## محتوای اصلی با بخشی از محتوای بندها و زیرجزءها، بردارسازی و ذخیره شود و مابقی در ادامه
else :
if parent_state["is_parent_embedded"] == 1: ## قبلا محتوای پدر با فرزندان در حد طول 512 بردارسازی شده و ذخیره شده است
## حالا محتوای فرزندهای باقیمانده با کمک محتوای پدرا باید تا طول 512 بردارسازی شوند
if prev_entry_child :
eid = prev_entry_child.get("id", "")
content = prev_entry_child.get(field_content, "")
data = prev_entry_child
content_offset = parent_state["content_offset"]
content_emb = parent_state["content"] + "\n" + content + "\n"+ parent_state["content_emb"]
data["content_emb"] = content_emb
else : ## تست شد : پیش نمی آید
print('------ no prev entry for child ####### error data id=', id, ' wl_em : ', wl_em, ' parent_id : ', parent_id , ' parent_state : ', parent_state["id"] )
prev_entry_child = entry
parent_state["word_len_childs"] = 0
parent_state["content_emb"] = ''
elif parent_entry :
parent_state["is_parent_embedded"] = 1
eid = parent_state["id"]
data = parent_entry
content_offset = parent_state["content_offset"]
content_emb = parent_state["content"] + "\n" + parent_state["content_emb"]
data["content_emb"] = content_emb
prev_entry_child = entry
parent_entry={}
parent_state["word_len_childs"] = 0
parent_state["content_emb"] = ''
else : ## تست شد : پیش نمی آید
print('### no parent for child ####### error data id=', id, ' parent_id : ', parent_id , ' parent_state : ', parent_state["id"] )
else :
#if parent_id != 0 :
## مواردی هستند که با پدر خود فاصله ایجاد شده است مثل qs918484
## فعلا کمک محتوایی براشون نمی کنیم
#print('### child withuot parent ####### error data id=', id, ' parent_id : ', parent_id , ' parent_state : ', parent_state["id"] )
eid = id
content_offset = 'در ' + qanon_title + ' درباره '
for hed in path_headings :
content_offset += ' ' + hed.strip()
content_emb = content
else :
eid = id
content_offset = 'در ' + qanon_title + ' درباره '
for hed in path_headings :
content_offset += ' ' + hed.strip()
content_emb = content
if content_emb :
payload={
'text': content_offset + ' ' + content_emb
}
response = requests.request("POST", ai_url_vec, headers=HEADERS, json=payload)
if response.status_code == 500 :
print(response.text)
bulk_data = []
continue
resp = json.loads(response.text)
data["embeddings"]=resp['result']
update = False
try:
if "pos_tags" in data:
del data["pos_tags"]
if "chunk_tags" in data:
del data["chunk_tags"]
resp = elasticHelper.update_index_doc(update, index_name_o, eid, data)
except Exception as e:
save_error(eid, e)
except Exception as e:
save_error(id, e)
print("=" * 10, "import_data_embeding finished")
def import_classification(elasticHelper, ai_url_class, index_name_o = "mj_qa_section_ai") :
id = ""
body={
"query": {
"bool": {
"must_not": [
{
"exists": {
"field": "code-ai"
}
}
]
}
}
}
dicIds = {}
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)
for mentry in list:
count += 1
entry = mentry["source"]
id = entry.get("id", "")
content = entry.get("content", "")
data = {}
if content :
payload={
'text':content
}
response = requests.request("POST", ai_url_class, headers=HEADERS, json=payload)
if response.status_code == 500 :
print(response.text)
continue
resp = json.loads(response.text)
data["code-ai"]=resp['result']
update = True
eid = id
try:
resp = elasticHelper.update_index_doc(update, 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)
# 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')
print("=" * 10, " finished")
def isMomSection(other_info, content):
if not other_info["full_path"] :
return True
paths = other_info["full_path"].split('>')
last_item = paths[len(paths)-1]
print(paths)
print(last_item)
if "ماده" in last_item :
return True
content = content.strip()
if re.match(r"^((ضمیمه)|(جدول))\s*\d*$", content):
return True
#isMomSection({"full_path":"باب اول>فصل اول>ماده 8"})
+107
View File
@@ -0,0 +1,107 @@
import requests
import json
import os
from dotenv import load_dotenv
from decimal import Decimal
from app.common.config_base import *
from app.common.general_functions import *
from app.common.elastic_helper import ElasticHelper
from app.common.create_ai_index import *
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)
## 0 ##--------------------------------------------------
##----- تولید داده های جدید از اس کیو ال با مجموعه دستورات موجود در فایل زیر
##----- import_from_sql.all_sql_steps.py
##-- و تولید ایندکسهای جدید
##-- mj_qa_qanon_temp
##-- mj_rg_section_temp
##-- mj_qa_section_temp
##-- mj_qa_opinion_temp
## 1 ##-----------------------------------------------------------------
##----- انتقال اطلاعات قبلی به اینجا
#elastic.moveCustomFileds("mj_qa_section", "mj_qa_section_temp", ["ners_v1", "nlp_parser", "code-ai"])
## 2 ##-----------------------------------------------------------------
## ----- تغییر ایندکسهای موقت به ایندکسهای اصلی
# elastic.deleteIndex("mj_qa_opinion")
# elastic.renameElasticIndex("mj_qa_opinion_temp", "mj_qa_opinion", "majles", "mj_qa_opinion")
# elastic.deleteIndex("mj_qa_qanon")
# elastic.renameElasticIndex("mj_qa_qanon_temp", "mj_qa_qanon", "majles", "mj_qa_qanon")
# elastic.deleteIndex("mj_qa_section")
# elastic.renameElasticIndex("mj_qa_section_temp", "mj_qa_section", "majles", "mj_qa_section")
# elastic.deleteIndex("mj_rg_section")
# elastic.renameElasticIndex("mj_rg_section_temp", "mj_rg_section", "majles", "mj_qa_section")
## 3 ##-----------------------------------------------------------------
## محاسبات پردازش داده ای واجب و پیچیده که پایه تمیزی داده در فاز2 و 3 هست اینجا انجام می شود
#fill_nlp_tags(elastic, "mj_qa_section")
#extract_nlp_childs(elastic,"mj_qa_section")
## 4 ## --------------------------------------------------------------
## پرکردن فیلدهای هوش مصنوعی برای اجزاء یا قانونهای جدید
##///////////////////////////////////////////////////////////
## 4.1 ## -----------------------------------------------------------------
# تولید بردار برای اجزائی که لازم هست
# elastic.createIndex("mj_qa_section_ai", 'majles/', "mj_qa_section" )
# ai_url_vec=os.getenv("ai_url_vec")
# import_data_embeding(elastic, ai_url_vec ,"mj_qa_section", "mj_qa_section_ai", "content" )
## 4.2 ## -----------------------------------------------------------------
# برچسبهای هوشمند
# import_classification(elastic, ai_url_class, "mj_qa_section_temp")
## 5 ## --------------------------------------------------------------
## پشتیبان گیری از داده جدید تکمیلی
##///////////////////////////////////////////////////////////
## پشتیبان گیری
# path_back = os.getcwd() + '/data_back'
path_back = 'G:/Project2/111'
# if not os.path.exists(path_back) :
# os.makedirs(path_back)
# print('---> path_back = ' + path_back)
#elastic.backupIndexToZipfile(path_back, "mj_qa_qanon")
# elastic.backupIndexToZipfile(path_back, "mj_qa_section")
#elastic.backupIndexToZipfile(path_back, "mj_qa_section", '', {}, True, [], ["pos_tags", "chunk_tags", "version_info"])
#elastic.backupIndexToZipfile(path_back, "mj_qa_section_ai")
#elastic.backupIndexToZipfile(path_back, "mj_rg_section")
#elastic.backupIndexToZipfile(path_back, "mj_qa_opinion")
## کد نمونه بازیابی از فایل
#path_back = 'G:/Project2/_back/back_data/data_majles/elastic/v1.0/full'
# path_back = 'G:/Project2/111'
# elastic.restorFileToElastic(path_back, 'mj_qa_section_ai', 'majles', True, 'mj_qa_section')
+75
View File
@@ -0,0 +1,75 @@
import requests
import json
from decimal import Decimal
from app.common.config_base import *
from app.common.general_functions import *
from s1_LWTopic import *
from s2_LawSection_ToElastic import *
from s3_opinion_ToElastic import *
from s4_RegulationSection_ToElastic import *
from s5_LawSection_update_ref_state import *
from s6_RegulationSection_update_ref_state import *
from s7_LawReg_qanon_ToElastic import *
from s8_Relations_qanon_LWReg import *
from s9_Relations_qanon_opinion import *
from s10_LawReg_lwphase_Info import *
from s11_Tanghih_plan_move import *
# -----------------------------------------------------------------
## ابتدا دستورات زیر را به ترتیب در دیتابیس فهرست اجرا شود
# SELECT id from tl_projects where title='موضوعات درختی قانون'
# DELETE from tl_subjects where project_id= (SELECT id from tl_projects where title='موضوعات درختی قانون')
# -----------------------------------------------------------------
# اجرای دستورات زیر در الاستیک
# DELETE mj_qa_qanon_temp
# DELETE mj_rg_section_temp
# DELETE mj_qa_section_temp
# DELETE mj_qa_opinion_temp
# -----------------------------------------------------------------
# cursor, cnxn = create_cursor()
## ایجاد فهرست موضوعات قانون
#projectid = insertProejct()
#insertProjectItems(cursor, projectid)
# 2
#import_law_section_to_elastic(cursor)
# import_regulation_section_to_elastic(cursor)
# import_opinion_to_elastic(cursor)
### از ابتدا تا اینجا حدودا 24 ساعت کشید
# import_law_section_update_ref_state(cursor)
# import_regulation_section_update_ref_state(cursor)
# import_law_reg_qanon_to_elastic(cursor)
# ## تا اینجا رسید و خطا داد
# import_relations_qanon_lwreg(cursor)
# ## اینجا خطا داد
# import_relations_qanon_opinion(cursor)
# import_lawreg_lwphase_info(cursor)
# cursor.close()
# cnxn.close()
cursor, cnxn = create_cursor('db4minaei')
# #####import_tangih_tree_to_list(cursor)
import_tanghih_plan_codes(cursor)
cursor.close()
cnxn.close()
File diff suppressed because one or more lines are too long
@@ -0,0 +1,219 @@
import json
import requests
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
def import_lawreg_lwphase_info(cursor):
query='SELECT ID,CAPTION FROM [Qavanin].[dbo].[cmOrganization]'
cursor.execute(query)
ORG_DICT = {}
while True:
row = cursor.fetchone()
if not row:
break
text = text_normal.normalize_qanon(row.CAPTION)
rr = {"id" : int(row.ID), 'title': text}
ORG_DICT[str(int(row.ID))] = {"id" : row.ID, 'title': text}
query = '''
SELECT
F_LWLAWID as F_LWLAWID,
p.ID as Phase_ID,
isnull(COMMANDDATE,'') as COMMANDDATE ,
isnull(COMMANDNO,'') as COMMANDNO,
isnull(NEWSPAPERDATE,'') as NEWSPAPERDATE,
isnull(NEWSPAPERNO,'') as NEWSPAPERNO,
isnull(o.CAPTION,'') as organization_title
,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),F_CMORGANIZATIONID), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM [lwReceiver] where F_LWLAWID=p.[F_LWLAWID]) as receiver
,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),F_CMORGANIZATIONID), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM [lwExecutor] where F_LWLAWID=p.[F_LWLAWID]) as exceuter
,(SELECT top (1) [EXECUTIONDATE] FROM [lwExecuteCondition] where [F_PHASEID]=p.id) as EXECUTIONDATE
FROM [Qavanin].[dbo].[lwPhase] p
left join cmOrganization o on p.F_CMORGANIZATIONID = o.ID
left join lwLaw l1 on p.F_LWLAWID= l1.ID
-- order by F_LWLAWID --بعضی موارد تکرار شده اند
'''
cursor.execute(query)
text_normal = TextNormalizer()
url = BASE_URL + "repo/majles/qaqanon/multi/update"
headers = HEADERS
total_count = 0
bulk_data = []
previd = ''
ref_state_array = []
t1= datetime.datetime.now()
print("start time: " + str(t1))
i = 0
all_data = []
repeat_data = []
while 1:
i += 1
row = cursor.fetchone()
if not row:
break
phase_id = str(int(row.Phase_ID.real))
law_id = str(int(row.F_LWLAWID.real))
eb_number = row.COMMANDNO.strip() if row.COMMANDNO else ''
eb_date = row.COMMANDDATE.strip() if row.COMMANDDATE else ''
eb_ref = row.organization_title.strip() if row.organization_title else '' # نرمالایز میخواد؟
rrk_number = row.NEWSPAPERNO.strip() if row.NEWSPAPERNO else ''
rrk_date = row.NEWSPAPERDATE.strip() if row.NEWSPAPERDATE else ''
exec_date = row.EXECUTIONDATE.strip() if row.EXECUTIONDATE else ''
receiver_ids = row.receiver
exceuter_ids = row.exceuter
if eb_date == '0000/00/00' :
eb_date = ''
if rrk_date == '0000/00/00' :
rrk_date = ''
if exec_date == '0000/00/00' :
exec_date = ''
if eb_number == 'نامعلوم' or eb_number == 'ندارد':
eb_number = ''
if rrk_number == 'نامعلوم' or rrk_number == 'ندارد':
rrk_number = ''
# # جایگذاری مقدار خالی به جای نامعلوم
# if eb_number.__contains__("معلوم"):
# eb_number = ""
# if eb_date.__contains__("معلوم"):
# eb_date = ""
# if eb_ref.__contains__("معلوم"):
# eb_ref = ""
# if rrk_number.__contains__("معلوم"):
# rrk_number = ""
# if rrk_date.__contains__("معلوم"):
# rrk_date = ""
# کمتر از 10 مورد تکرار داشتند، ظاهرا چند بار در روزنامه رسمی منتشر شده و هر بار بخشی از آن ، لذا اولین اطلاعات پر آن برداشته شد
if law_id == '178971':
eb_number = "7644 ج"
if law_id == '244878':
eb_number = ""
if law_id == '83695':
eb_number = "3923"
if law_id == '115887':
eb_number = ""
if law_id == '113211':
eb_number = ""
if law_id == '83452':
eb_number = "70445"
if law_id == '111876':
eb_number = "7848"
if law_id == '198907':
eb_number = "36094"
if law_id == '87694':
eb_number = "36341/ 1"
if law_id in all_data:
repeat_data.append(law_id)
continue
all_data.append(law_id)
# print("row: %s" % str(i))
receiver_organs = []
if receiver_ids :
for id in receiver_ids.split(',') :
if id in ORG_DICT :
receiver_organs.append({ "id": id, "title":ORG_DICT[id]["title"]})
exceuter_organs = []
if exceuter_ids :
for id in exceuter_ids.split(',') :
if id in ORG_DICT :
exceuter_organs.append({ "id": id, "title":ORG_DICT[id]["title"]})
eid= 'qq' + law_id
eblagh = {
'number' : eb_number,
'date' : eb_date,
'from' : eb_ref,
}
rrk = {
'number' : rrk_number,
'date' : rrk_date,
}
data={
'id' : eid,
'eblagh' : eblagh,
'rrk': rrk,
'exec_date' : exec_date,
'receiver_organs' : receiver_organs,
'exceuter_organs' : exceuter_organs,
}
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print('=' * 10, ' lawreg_lwphase_info , total='+str(total_count) , str(i)+ ', id=' + eid )
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
# limit POST Content-Length 8388608
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(bulk_data)
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text)
# print(row.txt)
bulk_data.append(data)
# print(bulk_count)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 10, ' lawreg_lwphase_info , total='+str(total_count) )
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(bulk_data)
print(response.text)
bulk_data = []
# print(response.text )
t2= datetime.datetime.now()
print("update rows count: " + str(len(all_data)))
print("finished time: " + str(t2))
print("process time: " + str(t2-t1))
print(' end success lawreg_lwphase_info ')
@@ -0,0 +1,374 @@
import json
import requests
import requests
from html import escape
import json
from decimal import Decimal
import datetime
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
# این برنامه یک بار فقط جهت انتقال کدهای دیتابیس آقای شاهنوش به دیتابیس نهایی قوانین انجام شد
# تکرار لازم نیست
# در بقیه حالات اگر کدها تغییر نکرده باشد در خود الاستیک بروز رسانی می شود
#cursor, cnxn = create_cursor('db4minaei')
def import_tanghih_plan_codes(cursor):
plan1 = {}
query = """select * from dbo.[lwplan] where [f_parentid]=766 order by [ordno] """
cursor.execute(query)
i = 0
while 1:
i=i+1
row = cursor.fetchone()
if not row:
break
plan1[row.ID] = normalYehKe(row.caption)
# print(plan1)
plan2 = {}
query = """select * from dbo.[lwplan] where [f_parentid]=21185 order by [ordno] """
cursor.execute(query)
i = 0
while 1:
i=i+1
row = cursor.fetchone()
if not row:
break
plan2[row.ID] = normalYehKe(row.caption)
# print(plan2)
# #########################################################
query = '''
SELECT [f_lwplanid]
,[f_lwlawsecid]
,[planstate]
,[ID]
FROM [db4minaei].[dbo].[lwlawplan]
where f_lwlawsecid is not null and f_lwlawsecid > 0
order by f_lwlawsecid, planstate, f_lwplanid
'''
cursor.execute(query)
text_normal = TextNormalizer()
url = BASE_URL + "repo/majles/section/multi/update"
headers = HEADERS
total_count = 0
bulk_data = []
previd = ''
tcode_main_old = []
tcode_sub_old = []
tcode_main = []
tcode_sub = []
prev_sectionid = 0
prev_planid = 0
prev_planstate = 0
prev2_sectionid = 0
prev2_planid = 0
prev2_planstate = 0
t1= datetime.datetime.now()
print(t1)
i = 0
while 1:
# print(i)
i=i+1
row = cursor.fetchone()
if not row:
break
# if i > 3:
# break
# print(row.sectionId)
sectionid = row.f_lwlawsecid
planid = row.f_lwplanid
planstate = row.planstate
if prev_sectionid == 0 :
prev_sectionid = sectionid
prev_planid = planid
prev_planstate = planstate
continue
if sectionid == prev_sectionid and planid == prev_planid and planstate == prev_planstate :
continue
if sectionid == prev_sectionid :
if prev_planid in plan1 :
if prev_planstate == 1 :
tcode_main_old.append(plan1[prev_planid])
else :
tcode_sub_old.append(plan1[prev_planid])
elif prev_planid in plan2 :
if prev_planstate == 1 :
tcode_main.append(plan2[prev_planid])
else :
tcode_sub.append(plan2[prev_planid])
prev_planid = planid
prev_planstate = planstate
continue
eid='qs'+ str(prev_sectionid)
# data={
# 'id' : eid,
# 'tcode_main' : tcode_main,
# 'tcode_sub' : tcode_sub,
# 'tcode_main_old' : tcode_main_old,
# 'tcode_sub_old' : tcode_sub_old,
# }
data={
'id' : eid,
'tcode':{
'mains' : tcode_main,
'subs' : tcode_sub,
'mains_old' : tcode_main_old,
'subs_old' : tcode_sub_old,
}
}
# print(eid)
bulk_data.append(data)
prev_sectionid = sectionid
tcode_main_old = []
tcode_sub_old = []
tcode_main = []
tcode_sub = []
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print('=' * 10, ', total='+str(total_count) , str(i)+ ', id=' + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
# limit POST Content-Length 8388608
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text)
# print(row.txt)
# /////////////////
prev2_sectionid = prev_sectionid
prev2_planid = prev_planid
prev2_planstate = prev_planstate
prev_sectionid = sectionid
prev_planid = planid
prev_planstate = planstate
# if prev2_sectionid == prev_sectionid :
if prev_planid in plan1 :
if prev_planstate == 1 :
tcode_main_old.append(plan1[prev_planid])
else :
tcode_sub_old.append(plan1[prev_planid])
elif prev_planid in plan2 :
if prev_planstate == 1 :
tcode_main.append(plan2[prev_planid])
else :
tcode_sub.append(plan2[prev_planid])
# else :
eid='qs'+ str(prev_sectionid)
data={
'id' : eid,
'tcode':{
'mains' : tcode_main,
'subs' : tcode_sub,
'mains_old' : tcode_main_old,
'subs_old' : tcode_sub_old,
}
}
# data={
# 'id' : eid,
# 'tcode_main' : tcode_main,
# 'tcode_sub' : tcode_sub,
# 'tcode_main_old' : tcode_main_old,
# 'tcode_sub_old' : tcode_sub_old,
# }
bulk_data.append(data)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 10, ', total='+str(total_count) , str(i)+ ', id=' + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
# print(response.text)
t2= datetime.datetime.now()
print("finished time: " + str(t2))
print("process time: " + str(t2-t1))
print(' end success lawreg_lwphase_info ')
def import_tangih_tree_to_list(cursor):
# -----------------------------------------------------------------
# BASE_URL = "https://api.tavasi.ir/list/"
# ADD_LIST_ROUTE = "project/add"
# ADD_ITEM_ROUTE = "subject/add"
# TITLE = "فهرست موضوعات قانون"
# TYPE = 3
# ADD_LIST_QUERY = {"title": TITLE, "type": TYPE, "item_state": 1}
GET_H = lambda x: x["HIERARCHY"]
GET_F = lambda x: x["F_PARENTID"]
# ADD_LIST_QUERY = {
# "title": TITLE,
# "listtype": 3,
# "item_state": 1,
# "ispublic" : 1,
# }
# requests.post(BASE_URL + ADD_LIST_ROUTE, data=ADD_LIST_QUERY, headers = HEADERS)
projectid = 3
EXAMPLE_ADD_ITEM_QUERY = {
"title": "",
"projectid": projectid,
"listtype": 0,
"parent": 0,
}
query = """select * from dbo.[lwplan]"""
cursor.execute(query)
result = []
while True:
row = cursor.fetchone()
if not row:
break
HIERARCHY = row.hierarchy
HIERARCHY = HIERARCHY.split(".")[-2]
HIERARCHY = HIERARCHY.rjust(3, "0")
result.append(
{
"ID": int(row.ID),
"CODE": row.CODE,
"CAPTION": row.CAPTION,
"F_PARENTID": int(row.F_PARENTID) if row.F_PARENTID else 0,
"HIERARCHY": HIERARCHY,
}
)
# result = sorted(result, key=GET_F)
result = sorted(result, key=GET_H)
childs = {}
IDS_DICT = {}
def insert(rows):
remains =[]
for row in rows:
number = 1
try:
F_PARENTID = row["F_PARENTID"]
except KeyError:
F_PARENTID = -1
print('*'*20)
print(row)
print('#'*20)
continue
# try:
if F_PARENTID == 0:
parent = 0
elif str(F_PARENTID) in IDS_DICT:
parent = IDS_DICT[str(F_PARENTID)]['id']
else:
print(F_PARENTID)
print(IDS_DICT)
print(row)
break
remains.append(row)
continue
# except KeyError:
# print('error')
# print(row)
# continue
if parent in childs:
number = childs[parent] + 1
childs[parent] = number
ADD_ITEM_QUERY = {
"title": row["CAPTION"],
"projectid": projectid,
"otherid": row["ID"],
"meta": row["CODE"],
"childorder": number,
"listtype": 0,
"parent": parent,
}
# result = requests.post(BASE_URL + ADD_ITEM_ROUTE, data=ADD_ITEM_QUERY, headers=HEADERS)
New_ID = json.loads(result.text)["data"][0]["id"]
print(str(row["ID"]) + '=' + str(New_ID))
IDS_DICT[str(row["ID"])] = {"id" : int(New_ID), 'title': row["CAPTION"]}
return remains
remains = insert(result)
# print(IDS_DICT)
count = 1
while remains.__len__() > 0 and count < 2:
print('##################' + str(count))
print( remains.__len__() )
remains = insert(remains)
# print(IDS_DICT)
count = count + 1
with open("list_Tanghih.json", 'w') as file:
file.write(json.dumps(IDS_DICT))
@@ -0,0 +1,207 @@
import json
import os
from html import escape
import json
import datetime
from dotenv import load_dotenv
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper
from app.common.qanon_functions import *
# ضرورتا
# این برنامه ضرورت دارد اجرا شود
# بسیاری از اجزاء قانون دارای وضعیت مثل منسوخه و جایگزین شده بودند که اطلاعات اثرگذ اری شون پر نشده بود
# مشخص شد اینها با کلیت یک قانون اثرگذ ار ثبت شده نه بخش مشخص از قانون
# لذا این ناقصی با این برنامه تکمیل شد
def check_duplicate_ref_state(list):
dict_index={}
res = []
for item in list :
if item["id"] in dict_index :
index = dict_index[item["id"]]
if res[index]["qanon_id"] == item["qanon_id"] and res[index]["section_id"] == item["section_id"]:
continue # duplicate
dict_index[item["id"]] = len(res)
res.append(item)
return res
def import_law_section_repair_ref_state(cursor, elastic, index_name_o, file_log):
query = '''
SELECT l1.[ID] as sectionId
,l1.F_CMBASETABLEID_SECTIONSTATUS
,l1.[F_LWLAWCHANGEID] as id
,l2.F_LWLAWID_EFFECTED
,l2.F_LWLAWID_EFFECTIVE as effect_qanon_id
,l3.CAPTION as effect_qanon
,l3.APPROVEDATE as effect_Date
,ls1.CAPTION as effect_section_type
-- ,l4.ID as id_1
FROM [Qavanin].[dbo].[lwSection] l1
left join [Qavanin].[dbo].[lwLawSectionStatus] ls1 on ls1.ID=l1.[F_CMBASETABLEID_SECTIONSTATUS]
left join [Qavanin].[dbo].lwLawChange l2 on l1.F_LWLAWCHANGEID=l2.id
left join [Qavanin].[dbo].lwLaw l3 on l2.F_LWLAWID_EFFECTIVE=l3.id
left join [Qavanin].[dbo].lwSectionChange l4 on l1.id=l4.F_LWSECTIONID_EFFECTED
where
l3.ISLAW = 1
and l4.ID is null --یعنی قبلا از طریق دیگر این اطلاعات برایش پر نشده باشد
and l2.F_LWLAWID_EFFECTED is not null -- یعنی اطلاعات جدید اثرگذاری وجود داشته باشد
'''
cursor.execute(query)
text_normal = TextNormalizer()
total_count = 0
bulk_data = []
file = open(file_log, 'a+', encoding='utf8')
t1= datetime.datetime.now()
print(t1)
i = 0
while 1:
# print(i)
i=i+1
row = cursor.fetchone()
if not row:
break
# if i > 3:
# break
# print(row.sectionId)
eid='qs'+ str(row.sectionId)
# lawId='qq'+ str(row.lawId)
effect_type = ''
# effect_type = text_normal.normalize_qanon(row.effect_section_type)
if row.effect_section_type == 'معتبر' :
effect_type = ''
elif row.effect_section_type == 'ساختار الحاقي' or row.effect_section_type == 'ساختار الحاقي مكرر' :
effect_type = 'الحاقی'
elif row.effect_section_type == 'اصلاحي' or row.effect_section_type == 'نامه اصلاحي':
effect_type = 'اصلاحی'
elif row.effect_section_type == 'منسوخه' :
effect_type = 'نسخی'
elif row.effect_section_type == 'احياء' or row.effect_section_type == 'تنفيذ' or row.effect_section_type == 'تمديد':
effect_type = 'تمدیدی'
elif row.effect_section_type == 'تفسير' :
effect_type = 'تفسیری'
elif row.effect_section_type == 'ساختار جايگزين' or row.effect_section_type == 'جايگزين شده':
effect_type = 'جایگزین'
elif row.effect_section_type == 'آزمايشي' :
effect_type = ''
elif row.effect_section_type == 'موقت' :
effect_type = ''
elif row.effect_section_type == 'موقوف الاجراء' :
effect_type = ''
elif row.effect_section_type == 'بااجرامنتفي مي شود' :
effect_type = ''
# if row.ISIMPLICIT :
# effect_type += ' ضمنی'
# if i == 1 : # اولین بار
# prev_effect_type = effect_type
prev_ref_state = []
item = {}
try:
item = elastic.get_doctument(index_name_o, eid)
if 'ref_state' in item['_source'] :
if len(item['_source']['ref_state']) > 0:
prev_ref_state = item['_source']['ref_state']
prev_ref_state1 = check_duplicate_ref_state(prev_ref_state)
if len(prev_ref_state) != len(prev_ref_state1):
print(' ==========> check_duplicate_ref_state OK : ', eid)
file.write('==========> check_duplicate_ref_state OK : '+ eid + '\n')
prev_ref_state = prev_ref_state1
# continue
except Exception as e:
# print(type(e).__name__)
continue
ref_state = {}
if row.effect_qanon_id :
result = [item for item in prev_ref_state if item['id'] == str(row.id)]
if result : # این مورد قبلا در الاستیک اضافه شده است
continue
efect_qanon_id= 'qq'+ str(row.effect_qanon_id)
ref_state = {
"id" : str(row.id),
"qanon_id": efect_qanon_id,
"qanon_title" : text_normal.normalize_qanon(row.effect_qanon),
"qanon_date": row.effect_Date,
"section_id": '',
"section_title": "",
"ref_key": "qavanin",
"effect_type" : effect_type,
"new_text" : "",
"prev_text" : "",
"description" : ""
}
prev_ref_state.insert(0 , ref_state)
data={
'_id' : eid,
'_source' : {
'ref_state' : prev_ref_state
}
}
bulk_data.append(data)
# print("-"*10, " bulk_data.append ", eid)
prev_ref_state = []
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print('=' * 10, ' law_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 10, ' law_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
elastic.updateBulkList(bulk_data, index_name_o)
file.close()
print('end success import_law_section_update_ref_state')
t2= datetime.datetime.now()
print(t2-t1)
cursor, cnxn = create_cursor()
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')
# print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
import_law_section_repair_ref_state(cursor, elastic, "mj_qa_section", "./output/log_s12.txt")
cursor.close()
cnxn.close()
+127
View File
@@ -0,0 +1,127 @@
import requests
import json
from app.common.text_normalizer import TextNormalizer
from app.common.config_base import *
from app.common.general_functions import *
# cursor, cnxn = create_cursor()
ADD_LIST_ROUTE = "project/add"
ADD_ITEM_ROUTE = "subject/add"
TITLE = "موضوعات درختی قانون"
GET_H = lambda x: x["HIERARCHY"]
def insertProejct():
# ایجاد فهرست جدید
ADD_LIST_QUERY = {
"title": TITLE,
"type": 3,
"item_state": 1,
"ispublic" : 1,
}
# requests.post(BASE_URL + 'list/' + ADD_LIST_ROUTE, data=ADD_LIST_QUERY, headers = HEADERS)
projectid = 6
return projectid
#----------------------------------------------------------------
def insert(rows, projectid, IDS_DICT, childs ):
remains =[]
for row in rows:
number = 1
try:
F_PARENTID = row["F_PARENTID"]
except KeyError:
F_PARENTID = -1
print('*'*20)
print(row)
print('#'*20)
continue
# try:
if F_PARENTID == 0:
parent = 0
elif str(F_PARENTID) in IDS_DICT:
parent = IDS_DICT[str(F_PARENTID)]['id']
else:
print(F_PARENTID)
print(IDS_DICT)
print(row)
break
remains.append(row)
continue
# except KeyError:
# print('error')
# print(row)
# continue
if parent in childs:
number = childs[parent] + 1
childs[parent] = number
ADD_ITEM_QUERY = {
"title": row["CAPTION"],
"projectid": projectid,
"otherid": row["ID"],
"meta": row["CODE"],
"childorder": number,
"listtype": 0,
"parent": parent,
}
result = requests.post(BASE_URL + 'list/' + ADD_ITEM_ROUTE, data=ADD_ITEM_QUERY, headers=HEADERS)
New_ID = json.loads(result.text)["data"][0]["id"]
print(str(row["ID"]) + '=' + str(New_ID))
IDS_DICT[str(row["ID"])] = {"id" : int(New_ID), 'title': row["CAPTION"]}
return remains
def insertProjectItems(cursor, projectid):
childs = {}
IDS_DICT = {}
query = """select * from dbo.lwtopic"""
cursor.execute(query)
text_normal = TextNormalizer()
result = []
while True:
row = cursor.fetchone()
if not row:
break
HIERARCHY = row.HIERARCHY
HIERARCHY = HIERARCHY.split(".")[-2]
HIERARCHY = HIERARCHY.rjust(3, "0")
result.append(
{
"ID": int(row.ID),
"CODE": row.CODE,
"CAPTION": text_normal.normalize_qanon(row.CAPTION),
"F_PARENTID": int(row.F_PARENTID) if row.F_PARENTID else 0,
"HIERARCHY": HIERARCHY,
}
)
result = sorted(result, key=GET_H)
remains = insert(result, projectid, IDS_DICT, childs )
# print(IDS_DICT)
count = 1
while remains.__len__() > 0 and count < 2:
print('##################' + str(count))
print( remains.__len__() )
remains = insert(remains, projectid, IDS_DICT, childs )
# print(IDS_DICT)
count = count + 1
with open("list_LWTopic.json", 'w') as file:
file.write(json.dumps(IDS_DICT))
print('** write list_LWTopic.json ')
@@ -0,0 +1,277 @@
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import time
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
# cursor, cnxn = create_cursor()
def import_law_section_to_elastic(cursor) :
query = '''
select
s.ID as sectionId
,isnull(s.CAPTION,'') as title -- عنوان بخش: مثلا ماده 5
,isnull(s.F_PARENTID,0) as parentId
,isnull(lss.CAPTION,'') as sectionStatus -- lwLawSectionStatus_table: ... منسوخه، معتبر، اصلاحی، موقت و
,isnull(lss2.CAPTION,'') as qanon_etebar -- برای کل قانون نه جزء یا ماده خاص : ... منسوخه، معتبر، اصلاحی، موقت و
,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره
,isnull(s.SECTIONLEVEL,0) as sectionLevel -- نسبت به عنوان قانون نامرتب و دارای مقدار تکراری هم هست ؟؟؟
,isnull(nestedLawType.CAPTION,'') as lawType
--,isnull(nestedLawStatus.CAPTION,'') as lawStatus
,isnull(s.TEXTORDER,0) as textOrder -- ترتیب نمایش مواد و تبصره ها
,s.STATENO as stateNo -- ???
,isnull(s.SECTIONTYPENO,0) as sectionTypeNumber -- دوهزار رکورد با مقدار صفر دارد اما مقادیر دیگری نیز پذیرفته است ؟؟؟
-- بیش از پنج هزار رکورد با مقدار بالاتر از 1500 دارد که چنین مقادیری در جدول سکشن_تایپ وجود ندارد پس با این جدول رابطه ندارد
,isnull(l.CAPTION,'') as lawTitle -- عنوان قانون
,isnull(l.ID,0) as lawId -- شناسه قانون
,isnull(l.APPROVEDATE,'') as aproveDate -- تاریخ تصویب
,isnull(l.EXPIREDATE,'') as expireDate -- تاریخ انقضا
--,isnull(s.F_LWPHASEID,0) as phaseId -- شناسه فاز
,s.FULLPATH as sectionFullPath -- عنوان ماده یا تبصره
,isnull(s.SECTIONTYPENOTEXT,'') as sectionType -- ??? استفساریه، کنوانسیون، موافقت نامه، اساسنامه، تفسیر، دوم ، سوم ، چهارم، دوازدهم، خالی، 1، 2، 3، 4
,isnull(s.FIRSTSATENO,0) as firstStateNo -- ??? بازه 0 تا 169
,isnull(s.LASTSTATENO,0) as lastStateNo -- ??? بازه 0 تا 112
,isnull(s.HIERARCHY,'') as hierarchy
,isnull(s.DISPLAYINCONTENTS,0) as displayInContents -- ??? صد و پنجاه و سه رکورد دارای مقدار یک و بقیه یک میلیون رکورد مقدار 0 دارد
,isnull(s.ISINTERPRETATION,0) as isInterpretation -- ??? چهارصد و پنجاه و سه رکورد با مقدار یک دارد و بقیه مقادیر نال است
,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),F_TOPICID), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM lwsectiontopic where [F_SECTIONID]=s.id) as topics
,l.[ISLAW] -- قانون
,l.[ISREGULATION] -- مقرره
,l.[ISCORRECTIONLETTER] -- اصلاحیه
,(
SELECT top (1) p3.CAPTION
FROM [lwPhase] p1
left join [lwApprover] p2 on p1.ID=p2.F_LWPHASEID
left join cmOrganization p3 on p2.F_CMORGANIZATIONID = p3.id
where l.ID = p1.F_LWLAWID
order by p2.APPROVEDATE asc
) as ts_ref -- مرجع تصویب
,(
SELECT cbt.CAPTION
FROM lwLaw l2
left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID
where l.ID = l2.id
) as regulationType
from lwSection s
left join lwLawSectionStatus lss on s.F_CMBASETABLEID_SECTIONSTATUS = lss.ID
left join lwLaw l on s.F_LWLAWID = l.ID
left join lwLawSectionStatus lss2 on lss2.id= l.[F_CMBASETABLEID_LASTSTATUS]
left JOIN (
SELECT l2.F_LWBASETABLEID_LAWTYPE,l2.ID,cbt.CAPTION
FROM lwLaw l2
left JOIN cmBasetable cbt ON l2.F_LWBASETABLEID_LAWTYPE = cbt.ID
) AS nestedLawType ON s.F_LWLAWID = nestedLawType.ID
left JOIN (
SELECT l2.[F_LWBASETABLEID_REGULATIONTYPE],l2.ID,cbt.CAPTION
FROM lwLaw l2
left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID
) AS nestedRegulationType ON s.F_LWLAWID = nestedRegulationType.ID
where l.ISLAW = 1
order by s.F_LWLAWID,textOrder
'''
cursor.execute(query)
text_normal = TextNormalizer()
url = BASE_URL + "repo/majles/section/multi/add"
dict_topic = json.loads(open("list_LWTopic.json").read())
headers = HEADERS
total_count = 0
bulk_data = []
t1= datetime.datetime.now()
print(t1)
i = 0
while 1:
# print(i)
i=i+1
row = cursor.fetchone()
if not row:
break
# if i > 1000:
# break
# print(row.sectionId)
html = ''
if isNeedHtml(row.sectionText) :
html = row.sectionText
try:
soup = BeautifulSoup(row.sectionText, "html.parser")
text = soup.get_text("\n", strip=True)
# text = removeHtmlNoTableTag(row.sectionText) # خطا داره
except Exception as e:
text = row.sectionText
text = text_normal.normalize_qanon(text)
content_len = text.__len__()
qanon_title = text_normal.normalize_qanon( row.lawTitle )
title_type = getTitleType(qanon_title)
eid='qs'+ str(row.sectionId)
parentId = '0'
if row.parentId != 0 :
parentId = 'qs'+ str(row.parentId)
lawId='qq'+ str(row.lawId)
main_type = ''
if(row.ISLAW == 1):
main_type = 'قانون'
elif(row.ISREGULATION == 1):
main_type = 'مقرره'
sub_type = ''
if(row.ISLAW == 1):
sub_type = row.lawType
elif(row.ISREGULATION == 1):
sub_type = row.regulationType
sub_type = normalYehKe(sub_type)
# other_type = 'اصلی'
# if(row.ISCORRECTIONLETTER == 1):
# other_type = 'اصلاحی'
ts_year = ''
if row.aproveDate :
items = row.aproveDate.split("/")
if items.__len__() > 0:
ts_year = items[0]
tt = time.time()
tt = int( round(tt) * 1000)
version_ifo = {
"timestamp": tt,
"operation": "create",
"number" : 1
}
other_info = {
"level": row.sectionLevel,
"full_path": normalYehKe( row.sectionFullPath ),
"number_text":row.sectionType ,
"hierarchy" : row.hierarchy
}
topics = []
if row.topics:
topic_ids = row.topics.split(",")
topic_list = list(set(topic_ids))
for item in topic_ids:
if str(item) in dict_topic:
topics.append(
{'id': dict_topic[str(item)]['id'], 'title': normalYehKe(dict_topic[str(item)]['title'])}
)
ts_ref = normalYehKe(row.ts_ref)
if ts_ref == 'مقام معظم رهبری ( فرماندهی کل قوا )' :
ts_ref = 'مقام معظم رهبری'
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
try:
sort_date_timestamp = getSortTimestamp(row.aproveDate)
except Exception as e:
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
expire_date = row.expireDate.strip()
# state_etebar = normalYehKe(row.lawStatus)
state_etebar = normalYehKe(row.sectionStatus)
qanon_etebar = ''
if row.qanon_etebar :
qanon_etebar = normalYehKe(row.qanon_etebar)
data={
'id':eid,
'ref_id':row.sectionId,
'ref_key':'m_qavanin',
'main_type': main_type,
'sub_type': sub_type,
'content': text,
'html' : html,
# 'version_info': version_ifo,
'qanon_title': qanon_title,
'title_type': title_type,
'expire_date': expire_date,
'ts_date': row.aproveDate,
'ts_year': ts_year,
'ts_ref': ts_ref,
'state_etebar': state_etebar,
'qanon_id': lawId,
'parent_id': parentId,
'child_order': row.textOrder,
'other_info': other_info,
'content_len': content_len,
'topics': topics,
'qanon_etebar' : qanon_etebar,
# 'ref_state' : ref_state,
#'categories': row.oooo,
#'tags': row.oooo,
#'keywords': row.oooo,
'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp
}
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid , ' , lawid_current =' + lawId , ', lawid_first=' + bulk_data[0]['qanon_id'])
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
# limit POST Content-Length 8388608
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text)
# print(row.txt)
bulk_data.append(data)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid , ' , lawid_current =' + lawId , ', lawid_first=' + bulk_data[0]['qanon_id'])
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
print('end success import_law_section_to_elastic')
t2= datetime.datetime.now()
print(t2-t1)
+199
View File
@@ -0,0 +1,199 @@
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import re
import datetime
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
def import_opinion_to_elastic(cursor) :
query = """
SELECT
isnull(o.[ID],0) as ref_id
,isnull(l.CAPTION,'') as title
,isnull([SUBJECT],'') as title_popular
,isnull([OPINIONDATE],'') as ts_date
,isnull(l.APPROVEDATE,'') as ts_date2
,isnull(op_r.CAPTION,'') as sub_type
,isnull(op_r.[F_CMBASETABLEID_OPINIONGROUP],0) as mainType -- 1419 : رای 1418:نظر
--,isnull(F_OPOPINIONGIVERID,0) as ts_ref -- ts_ref
--,isnull(bt.CAPTION,'') as classification -- عادی، ندارد مهم نیست
,isnull(o.[F_LWLAWID],0) as qanon_id
,isnull([DISTRIBUTENO],'') as eblagh_number -- ???????? شماره ابلاغ؟
,isnull([DISTRIBUTEDATE],'') as eblagh_date -- ???????? تاریخ ابلاغ
,isnull(d.DOCTEXT,'') as content -- !!!!!!!!!!!!!!!!!!!!!! داده های این فیلد حجم زیادی دارد
,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),[F_LWTOPICID]), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM opOpinionTopic where [F_OPOPINIONID]=o.id) as topics
FROM [Qavanin].[dbo].[opOpinion] o
left join opOpiniongiver op_r on o.F_OPOPINIONGIVERID = op_r.id
left join [cmBasetable] bt on o.F_CMBASETABLEID_CLASSIFICATION = bt.ID
left join lwLaw l on o.F_LWLAWID = l.ID
left join prDoc d on o.F_PRDOCID = d.ID
"""
cursor.execute(query)
text_normal = TextNormalizer()
url = BASE_URL + "repo/majles/opinion/multi/add" # POST /repo/majles/opinion/multi/add
dict_topic = json.loads(open("list_LWTopic.json").read())
headers = HEADERS
total_count = 0
bulk_data = []
t1 = datetime.datetime.now()
print(t1)
i = 0
while 1:
# print(i)
i = i + 1
row = cursor.fetchone()
if not row:
break
# if i > 1000:
# break
# print(row.sectionId)
try:
soup = BeautifulSoup(row.content, "html.parser")
text = soup.get_text("\n", strip=True)
except Exception as e:
text = row.content
text = text_normal.normalize_qanon(text)
content_len = text.__len__()
title = text_normal.normalize_qanon(row.title)
eid = "qo" + str(row.ref_id)
qanon_id = "qq" + str(row.qanon_id)
main_type = ""
if row.mainType == 1418:
main_type = "نظر"
elif row.mainType == 1419:
main_type = "رای"
ts_date = row.ts_date
ts_date = ts_date.strip()
if not ts_date :
ts_date = row.ts_date2
ts_date = ts_date.strip()
ts_year = ""
if ts_date:
items = ts_date.split("/")
if items.__len__() > 1:
ts_year = int(items[0].strip())
version_ifo = {
"timestamp": datetime.datetime.now().timestamp(),
"operation": "create",
"number": 1,
}
topics = []
if row.topics:
topic_ids = row.topics.split(",")
topic_list = list(set(topic_ids))
for item in topic_ids:
if str(item) in dict_topic:
topics.append(
{
"id": dict_topic[str(item)]["id"],
"title": normalYehKe(dict_topic[str(item)]["title"]),
}
)
ts_ref = normalYehKe(row.sub_type)
ts_ref = ts_ref.replace("رای وحدت رویه", "")
ts_ref = ts_ref.replace("رای", "")
ts_ref = ts_ref.replace("نظر", "")
ts_ref = ts_ref.replace("- اصول 85 و 138", "")
ts_ref = ts_ref.strip()
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
try:
sort_date_timestamp = getSortTimestamp(ts_date)
except Exception as e:
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
sub_type = normalYehKe(row.sub_type)
title_popular = normalYehKe(row.title_popular)
eblagh_number = normalYehKe(row.eblagh_number)
eblagh_date = normalYehKe(row.eblagh_date)
# print(len(text.split()))
# normalized_section_content, recognized_dates, recognized_numbers = normalizerDate2(text.strip())
# print(len(normalized_section_content.split()))
# recognized_numbers = find_number_indexes_in_string(normalized_section_content,recognized_numbers)
# normalized_section_content = normalized_section_content.strip()
# founded_patterns_array = regex_patterns_finder(normalized_section_content)
data = {
"id": eid,
"title": title,
"ref_id": row.ref_id,
"ref_key": "m_qavanin",
"main_type": main_type,
"sub_type": sub_type,
"html": row.content,
"content": text,
# "version_info": version_ifo,
"ts_date": ts_date,
"ts_year": ts_year,
"ts_ref": ts_ref,
"qanon_id": qanon_id,
"eblagh_number": eblagh_number,
"eblagh_date": eblagh_date,
"content_len": content_len,
"title_popular": title_popular,
"sort_date_timestamp": sort_date_timestamp,
}
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print('=' * 10, 'opinion_to_elastic , total='+str(total_count) , str(i)+ ', id=' + eid )
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
# limit POST Content-Length 8388608
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text)
# print(row.txt)
bulk_data.append(data)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 10, ' opinion_to_elastic , total='+str(total_count) )
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
print("end success import_opinion_to_elastic")
t2 = datetime.datetime.now()
print(t2 - t1)
@@ -0,0 +1,275 @@
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import time
import sys
import traceback
import re
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
def import_regulation_section_to_elastic(cursor):
query = '''
select
s.ID as sectionId
,isnull(s.CAPTION,'') as title -- عنوان بخش: مثلا ماده 5
,isnull(s.F_PARENTID,0) as parentId
,isnull(lss.CAPTION,'') as sectionStatus -- lwLawSectionStatus_table: ... منسوخه، معتبر، اصلاحی، موقت و
,isnull(lss2.CAPTION,'') as qanon_etebar -- برای کل قانون نه جزء یا ماده خاص : ... منسوخه، معتبر، اصلاحی، موقت و
,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره
,isnull(s.SECTIONLEVEL,0) as sectionLevel -- نسبت به عنوان قانون نامرتب و دارای مقدار تکراری هم هست ؟؟؟
,isnull(nestedLawType.CAPTION,'') as lawType
--,isnull(nestedLawStatus.CAPTION,'') as lawStatus
,isnull(s.TEXTORDER,0) as textOrder -- ترتیب نمایش مواد و تبصره ها
,s.STATENO as stateNo -- ???
,isnull(s.SECTIONTYPENO,0) as sectionTypeNumber -- دوهزار رکورد با مقدار صفر دارد اما مقادیر دیگری نیز پذیرفته است ؟؟؟
-- بیش از پنج هزار رکورد با مقدار بالاتر از 1500 دارد که چنین مقادیری در جدول سکشن_تایپ وجود ندارد پس با این جدول رابطه ندارد
,isnull(l.CAPTION,'') as lawTitle -- عنوان قانون
,isnull(l.ID,0) as lawId -- شناسه قانون
,isnull(l.APPROVEDATE,'') as aproveDate -- تاریخ تصویب
,isnull(l.EXPIREDATE,'') as expireDate -- تاریخ انقضا
--,isnull(s.F_LWPHASEID,0) as phaseId -- شناسه فاز
,s.FULLPATH as sectionFullPath -- عنوان ماده یا تبصره
,isnull(s.SECTIONTYPENOTEXT,'') as sectionType -- ??? استفساریه، کنوانسیون، موافقت نامه، اساسنامه، تفسیر، دوم ، سوم ، چهارم، دوازدهم، خالی، 1، 2، 3، 4
,isnull(s.FIRSTSATENO,0) as firstStateNo -- ??? بازه 0 تا 169
,isnull(s.LASTSTATENO,0) as lastStateNo -- ??? بازه 0 تا 112
,isnull(s.HIERARCHY,'') as hierarchy
,isnull(s.DISPLAYINCONTENTS,0) as displayInContents -- ??? صد و پنجاه و سه رکورد دارای مقدار یک و بقیه یک میلیون رکورد مقدار 0 دارد
,isnull(s.ISINTERPRETATION,0) as isInterpretation -- ??? چهارصد و پنجاه و سه رکورد با مقدار یک دارد و بقیه مقادیر نال است
,(SELECT STRING_AGG(CONVERT(NVARCHAR(max),F_TOPICID), ',') WITHIN GROUP (ORDER BY ID) AS AggregatedResult FROM lwsectiontopic where [F_SECTIONID]=s.id) as topics
,l.[ISLAW] -- قانون
,l.[ISREGULATION] -- مقرره
,l.[ISCORRECTIONLETTER] -- اصلاحیه
,(
SELECT top (1) p3.CAPTION
FROM [lwPhase] p1
left join [lwApprover] p2 on p1.ID=p2.F_LWPHASEID
left join cmOrganization p3 on p2.F_CMORGANIZATIONID = p3.id
where l.ID = p1.F_LWLAWID
order by p2.APPROVEDATE asc
) as ts_ref -- مرجع تصویب
,(
SELECT cbt.CAPTION
FROM lwLaw l2
left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID
where l.ID = l2.id
) as regulationType
from lwSection s
left join lwLawSectionStatus lss on s.F_CMBASETABLEID_SECTIONSTATUS = lss.ID
left join lwLaw l on s.F_LWLAWID = l.ID
left join lwLawSectionStatus lss2 on lss2.id= l.[F_CMBASETABLEID_LASTSTATUS]
left JOIN (
SELECT l2.F_LWBASETABLEID_LAWTYPE,l2.ID,cbt.CAPTION
FROM lwLaw l2
left JOIN cmBasetable cbt ON l2.F_LWBASETABLEID_LAWTYPE = cbt.ID
) AS nestedLawType ON s.F_LWLAWID = nestedLawType.ID
left JOIN (
SELECT l2.[F_LWBASETABLEID_REGULATIONTYPE],l2.ID,cbt.CAPTION
FROM lwLaw l2
left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID
) AS nestedRegulationType ON s.F_LWLAWID = nestedRegulationType.ID
where l.[ISREGULATION] = 1
order by s.F_LWLAWID,textOrder
'''
cursor.execute(query)
text_normal = TextNormalizer()
url = BASE_URL + "repo/majles/rgsection/multi/add"
dict_topic = json.loads(open("list_LWTopic.json").read())
headers = HEADERS
total_count = 0
bulk_data = []
t1= datetime.datetime.now()
print(t1)
i = 0
while 1:
# print(i)
i=i+1
row = cursor.fetchone()
if not row:
break
# if i > 1000:
# break
# print(row.sectionId)
html = ''
if isNeedHtml(row.sectionText) :
html = row.sectionText
try:
soup = BeautifulSoup(row.sectionText, "html.parser")
text = soup.get_text("\n", strip=True)
# text = removeHtmlNoTableTag(row.sectionText) # خطا داره
except Exception as e:
text = row.sectionText
text = text_normal.normalize_qanon(text)
content_len = text.__len__()
qanon_title = text_normal.normalize_qanon( row.lawTitle )
title_type = getTitleType(qanon_title)
eid='qs'+ str(row.sectionId)
parentId = '0'
if row.parentId != 0 :
parentId = 'qs'+ str(row.parentId)
lawId='qq'+ str(row.lawId)
main_type = ''
if(row.ISLAW == 1):
main_type = 'قانون'
elif(row.ISREGULATION == 1):
main_type = 'مقرره'
sub_type = ''
if(row.ISLAW == 1):
sub_type = row.lawType
elif(row.ISREGULATION == 1):
sub_type = row.regulationType
sub_type = normalYehKe(sub_type)
# other_type = 'اصلی'
# if(row.ISCORRECTIONLETTER == 1):
# other_type = 'اصلاحی'
ts_year = ''
if row.aproveDate :
items = row.aproveDate.split("/")
if items.__len__() > 0:
ts_year = items[0]
tt = time.time()
tt = int( round(tt) * 1000)
version_ifo = {
"timestamp": tt,
"operation": "create",
"number" : 1
}
other_info = {
"level": row.sectionLevel,
"full_path": normalYehKe( row.sectionFullPath ),
"number_text":row.sectionType ,
"hierarchy" : row.hierarchy
}
topics = []
if row.topics:
topic_ids = row.topics.split(",")
topic_list = list(set(topic_ids))
for item in topic_ids:
if str(item) in dict_topic:
topics.append(
{'id': dict_topic[str(item)]['id'], 'title': normalYehKe(dict_topic[str(item)]['title'])}
)
ts_ref = ''
if(row.ts_ref):
ts_ref = normalYehKe(row.ts_ref)
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
try:
sort_date_timestamp = getSortTimestamp(row.aproveDate)
except Exception as e:
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
expire_date = row.expireDate.strip()
# state_etebar = normalYehKe(row.lawStatus)
state_etebar = normalYehKe(row.sectionStatus)
qanon_etebar = ''
if row.qanon_etebar :
qanon_etebar = normalYehKe(row.qanon_etebar)
data={
'id':eid,
'ref_id':row.sectionId,
'ref_key':'m_qavanin',
'main_type': main_type,
'sub_type': sub_type,
'content': text,
'html' : html,
# 'version_info': version_ifo,
'qanon_title': qanon_title,
'title_type': title_type,
'expire_date': expire_date,
'ts_date': row.aproveDate,
'ts_year': ts_year,
'ts_ref': ts_ref,
'state_etebar': state_etebar,
'qanon_id': lawId,
'parent_id': parentId,
'child_order': row.textOrder,
'other_info': other_info,
'content_len': content_len,
'topics': topics,
'qanon_etebar' : qanon_etebar,
#'categories': row.oooo,
#'tags': row.oooo,
#'keywords': row.oooo,
'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp
}
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 10, ' regulation_section , total='+str(total_count) , str(i)+ ', id=' + eid , ' , lawid_current =' + lawId , ', lawid_first=' + bulk_data[0]['qanon_id'])
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
# limit POST Content-Length 8388608
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text)
# print(row.txt)
bulk_data.append(data)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 10, ' regulation_section , total='+str(total_count) , str(i)+ ', id=' + eid , ' , lawid_current =' + lawId , ', lawid_first=' + bulk_data[0]['qanon_id'])
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
print('end success import_regulation_section_to_elastic')
t2= datetime.datetime.now()
print(t2-t1)
@@ -0,0 +1,209 @@
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import sys
import traceback
import re
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
# ضرورتا
# این برنامه ضرورت دارد اجرا شود
def import_law_section_update_ref_state(cursor):
query = '''
SELECT
gl1.ID as id,
gl4.APPROVEDATE as effect_Date,
gl3.[SECTIONTEXT] as effect_text,
gl3.FULLPATH as effect_section_title,
ls2.SECTIONTEXT as effect_prev_text,
gl4.CAPTION as effect_qanon,
gl1.F_LWLAWID_EFFECTIVE as effect_qanon_id,
gl1.[F_LWSECTIONID_EFFECTIVE] as effect_section_id,
gl1.[F_LWSECTIONID_EFFECTED] as sectionId,
gl2.[SECTIONTEXT],
ls1.CAPTION as effect_section_type,
gl1.DESCRIPTION as description,
gl1.ISIMPLICIT -- تاثیر ضمنی
FROM [Qavanin].[dbo].[lwSectionChange] gl1
left join [lwLawSectionStatus] ls1 on ls1.ID=gl1.[F_CMBASETABLEID_SECTIONSTATUS]
left join lwSection gl2 on gl2.ID=gl1.[F_LWSECTIONID_EFFECTED]
left join lwSection gl3 on gl3.ID=gl1.[F_LWSECTIONID_EFFECTIVE]
left join lwLaw gl4 on gl1.F_LWLAWID_EFFECTIVE=gl4.ID
left join lwSectionLog ls2 on ls2.ID=gl1.[F_LWSECTIONLOGID_EFFECTED]
where
gl4.ISLAW = 1
and gl1.[F_LWSECTIONID_EFFECTED] is not null
order by gl1.[F_LWSECTIONID_EFFECTED], gl4.APPROVEDATE
'''
cursor.execute(query)
text_normal = TextNormalizer()
url = BASE_URL + "repo/majles/section/multi/update"
dict_topic = json.loads(open("list_LWTopic.json").read())
headers = HEADERS
total_count = 0
bulk_data = []
previd = ''
prev_effect_type = ''
prev_efect_section_id = ''
ref_state_array = []
t1= datetime.datetime.now()
print(t1)
i = 0
while 1:
# print(i)
i=i+1
row = cursor.fetchone()
if not row:
break
# if i > 3:
# break
# print(row.sectionId)
eid='qs'+ str(row.sectionId)
# lawId='qq'+ str(row.lawId)
if previd == '':
previd = eid
effect_type = ''
if row.effect_section_type == 'معتبر' :
effect_type = ''
elif row.effect_section_type == 'ساختار الحاقي' or row.effect_section_type == 'ساختار الحاقي مكرر' :
effect_type = 'الحاقی'
elif row.effect_section_type == 'اصلاحي' or row.effect_section_type == 'نامه اصلاحي':
effect_type = 'اصلاحی'
elif row.effect_section_type == 'منسوخه' :
effect_type = 'نسخی'
elif row.effect_section_type == 'احياء' or row.effect_section_type == 'تنفيذ' or row.effect_section_type == 'تمديد':
effect_type = 'تمدیدی'
elif row.effect_section_type == 'تفسير' :
effect_type = 'تفسیری'
elif row.effect_section_type == 'ساختار جايگزين' or row.effect_section_type == 'جايگزين شده':
effect_type = 'جایگزین'
elif row.effect_section_type == 'آزمايشي' :
effect_type = ''
elif row.effect_section_type == 'موقت' :
effect_type = ''
elif row.effect_section_type == 'موقوف الاجراء' :
effect_type = ''
elif row.effect_section_type == 'بااجرامنتفي مي شود' :
effect_type = ''
if row.ISIMPLICIT :
effect_type += ' ضمنی'
# if i == 1 : # اولین بار
# prev_effect_type = effect_type
ref_state = {}
if row.effect_qanon_id :
efect_section_id='qs'+ str(row.effect_section_id)
efect_qanon_id= 'qq'+ str(row.effect_qanon_id)
if prev_efect_section_id == '' :
prev_efect_section_id = efect_section_id
ref_state = {
"id" : row.id,
"qanon_id": efect_qanon_id,
"qanon_title" : text_normal.normalize_qanon(row.effect_qanon),
"qanon_date": row.effect_Date,
"section_id": efect_section_id,
"section_title": normalYehKe(row.effect_section_title),
"ref_key": "qavanin",
"effect_type" : effect_type,
"new_text" : text_normal.normalize_qanon(row.effect_text),
"prev_text" : text_normal.normalize_qanon(row.effect_prev_text),
"description" : text_normal.normalize_qanon(row.description)
}
if previd == eid :
# موارد کاملا تکراری افزوده نشود
if efect_section_id != prev_efect_section_id or prev_effect_type != effect_type:
ref_state_array.append(ref_state)
prev_efect_section_id = efect_section_id
prev_effect_type = effect_type
ref_state={}
continue
data={
'id' : previd,
'ref_state' : ref_state_array
}
bulk_data.append(data)
ref_state_array = []
previd = eid
prev_efect_section_id = efect_section_id
prev_effect_type = effect_type
ref_state_array.append(ref_state)
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print('=' * 10, ' law_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
# limit POST Content-Length 8388608
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text)
# print(row.txt)
if ref_state_array.__len__() > 0 :
data={
'id' : previd,
'ref_state' : ref_state_array
}
bulk_data.append(data)
# print(bulk_data)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 10, ' law_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
# print(response.text)
print('end success import_law_section_update_ref_state')
t2= datetime.datetime.now()
print(t2-t1)
@@ -0,0 +1,209 @@
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import sys
import traceback
import re
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
# ضرورتا
# این برنامه ضرورت دارد اجرا شود
def import_regulation_section_update_ref_state(cursor):
query = '''
SELECT
gl1.ID as id,
gl4.APPROVEDATE as effect_Date,
gl3.[SECTIONTEXT] as effect_text,
gl3.FULLPATH as effect_section_title,
ls2.SECTIONTEXT as effect_prev_text,
gl4.CAPTION as effect_qanon,
gl1.F_LWLAWID_EFFECTIVE as effect_qanon_id,
gl1.[F_LWSECTIONID_EFFECTIVE] as effect_section_id,
gl1.[F_LWSECTIONID_EFFECTED] as sectionId,
gl2.[SECTIONTEXT],
ls1.CAPTION as effect_section_type,
gl1.DESCRIPTION as description,
gl1.ISIMPLICIT -- تاثیر ضمنی
FROM [Qavanin].[dbo].[lwSectionChange] gl1
left join [lwLawSectionStatus] ls1 on ls1.ID=gl1.[F_CMBASETABLEID_SECTIONSTATUS]
left join lwSection gl2 on gl2.ID=gl1.[F_LWSECTIONID_EFFECTED]
left join lwSection gl3 on gl3.ID=gl1.[F_LWSECTIONID_EFFECTIVE]
left join lwLaw gl4 on gl1.F_LWLAWID_EFFECTIVE=gl4.ID
left join lwSectionLog ls2 on ls2.ID=gl1.[F_LWSECTIONLOGID_EFFECTED]
where
gl4.[ISREGULATION] = 1
and gl1.[F_LWSECTIONID_EFFECTED] is not null
order by gl1.[F_LWSECTIONID_EFFECTED], gl4.APPROVEDATE
'''
cursor.execute(query)
text_normal = TextNormalizer()
url = BASE_URL + "repo/majles/rgsection/multi/update"
dict_topic = json.loads(open("list_LWTopic.json").read())
headers = HEADERS
total_count = 0
bulk_data = []
previd = ''
prev_effect_type = ''
prev_efect_section_id = ''
ref_state_array = []
t1= datetime.datetime.now()
print(t1)
i = 0
while 1:
# print(i)
i=i+1
row = cursor.fetchone()
if not row:
break
# if i > 3:
# break
# print(row.sectionId)
eid='qs'+ str(row.sectionId)
# lawId='qq'+ str(row.lawId)
if previd == '':
previd = eid
effect_type = ''
if row.effect_section_type == 'معتبر' :
effect_type = ''
elif row.effect_section_type == 'ساختار الحاقي' or row.effect_section_type == 'ساختار الحاقي مكرر' :
effect_type = 'الحاقی'
elif row.effect_section_type == 'اصلاحي' or row.effect_section_type == 'نامه اصلاحي':
effect_type = 'اصلاحی'
elif row.effect_section_type == 'منسوخه' :
effect_type = 'نسخی'
elif row.effect_section_type == 'احياء' or row.effect_section_type == 'تنفيذ' or row.effect_section_type == 'تمديد':
effect_type = 'تمدیدی'
elif row.effect_section_type == 'تفسير' :
effect_type = 'تفسیری'
elif row.effect_section_type == 'ساختار جايگزين' or row.effect_section_type == 'جايگزين شده':
effect_type = 'جایگزین'
elif row.effect_section_type == 'آزمايشي' :
effect_type = ''
elif row.effect_section_type == 'موقت' :
effect_type = ''
elif row.effect_section_type == 'موقوف الاجراء' :
effect_type = ''
elif row.effect_section_type == 'بااجرامنتفي مي شود' :
effect_type = ''
if row.ISIMPLICIT :
effect_type += ' ضمنی'
# if i == 1 : # اولین بار
# prev_effect_type = effect_type
ref_state = {}
if row.effect_qanon_id :
efect_section_id='qs'+ str(row.effect_section_id)
efect_qanon_id= 'qq'+ str(row.effect_qanon_id)
if prev_efect_section_id == '' :
prev_efect_section_id = efect_section_id
ref_state = {
"id" : row.id,
"qanon_id": efect_qanon_id,
"qanon_title" : text_normal.normalize_qanon(row.effect_qanon),
"qanon_date": row.effect_Date,
"section_id": efect_section_id,
"section_title": normalYehKe(row.effect_section_title),
"ref_key": "qavanin",
"effect_type" : effect_type,
"new_text" : text_normal.normalize_qanon(row.effect_text),
"prev_text" : text_normal.normalize_qanon(row.effect_prev_text),
"description" : text_normal.normalize_qanon(row.description) }
if previd == eid :
# موارد کاملا تکراری افزوده نشود
if efect_section_id != prev_efect_section_id or prev_effect_type != effect_type:
ref_state_array.append(ref_state)
prev_efect_section_id = efect_section_id
prev_effect_type = effect_type
ref_state={}
continue
data={
'id' : previd,
'ref_state' : ref_state_array
}
bulk_data.append(data)
ref_state_array = []
previd = eid
prev_efect_section_id = efect_section_id
prev_effect_type = effect_type
ref_state_array.append(ref_state)
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print('=' * 10, ' regulation_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
# limit POST Content-Length 8388608
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text)
# print(row.txt)
if ref_state_array.__len__() > 0 :
data={
'id' : previd,
'ref_state' : ref_state_array
}
bulk_data.append(data)
# print(bulk_data)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 10, ' regulation_section_update_ref_state , total='+str(total_count) , str(i)+ ', id=' + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
# print(response.text)
print('end success import_regulation_section_update_ref_state')
t2= datetime.datetime.now()
print(t2-t1)
@@ -0,0 +1,186 @@
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
def import_law_reg_qanon_to_elastic(cursor):
query = '''
SELECT
l1.[ID] as Id
,l1.[CAPTION] as title
--,[F_LWBASETABLEID_LAWTYPE]
,l1.[ISLAW] -- قانون
,l1.[ISREGULATION] -- مقرره
,isnull(l1.APPROVEDATE,'') as aproveDate -- تاریخ تصویب
,isnull(l1.EXPIREDATE,'') as expireDate -- تاریخ انقضا
--,[F_LWBASETABLEID_CLASSIFICATION]
,[RULENO]
,[LAWNO]
--,[F_CMBASETABLEID_LASTSTATUS]
,lss.CAPTION as qanon_etebar
,cbt.CAPTION as lawType
,(
SELECT top (1) p3.CAPTION
FROM [lwPhase] p1
left join [lwApprover] p2 on p1.ID=p2.F_LWPHASEID
left join cmOrganization p3 on p2.F_CMORGANIZATIONID = p3.id
where l1.ID = p1.F_LWLAWID
order by p2.APPROVEDATE asc
) as ts_ref -- مرجع تصویب
,(
SELECT cbt.CAPTION
FROM lwLaw l2
left JOIN cmBasetable cbt ON l2.[F_LWBASETABLEID_REGULATIONTYPE] = cbt.ID
where l1.ID = l2.id
) as regulationType
FROM [Qavanin].[dbo].[lwLaw] l1
left JOIN cmBasetable cbt ON l1.F_LWBASETABLEID_LAWTYPE = cbt.ID
left join lwLawSectionStatus lss on lss.id= l1.[F_CMBASETABLEID_LASTSTATUS]
where ( l1.ISLAW = 1 or l1.ISREGULATION = 1 )
'''
cursor.execute(query)
text_normal = TextNormalizer()
url = BASE_URL + "repo/majles/qaqanon/multi/add"
headers = HEADERS
total_count = 0
bulk_data = []
t1= datetime.datetime.now()
print(t1)
i = 0
while 1:
# print(i)
i=i+1
row = cursor.fetchone()
if not row:
break
# if i > 1000:
# break
# print(row.sectionId)
title = text_normal.normalize_qanon( row.title )
title_type = getTitleType(title)
eid='qq'+ str(row.Id)
main_type = ''
if(row.ISLAW == 1):
main_type = 'قانون'
elif(row.ISREGULATION == 1):
main_type = 'مقرره'
sub_type = ''
if(row.ISLAW == 1):
sub_type = row.lawType
elif(row.ISREGULATION == 1):
sub_type = row.regulationType
sub_type = normalYehKe(sub_type)
qanon_number = ''
if(row.ISLAW == 1):
qanon_number = row.LAWNO
elif(row.ISREGULATION == 1):
qanon_number = row.RULENO
# other_type = 'اصلی' اصلاحی....
# action_type ...
ts_year = ''
if row.aproveDate :
items = row.aproveDate.split("/")
if items.__len__() > 0:
ts_year = items[0]
ts_ref = normalYehKe(row.ts_ref)
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
try:
sort_date_timestamp = getSortTimestamp(row.aproveDate)
except Exception as e:
sort_date_timestamp = -15000000000 # 9/2/1494, 12:45:44 AM # خطا یا خالی
expire_date = row.expireDate.strip()
qanon_etebar = ''
if row.qanon_etebar :
qanon_etebar = normalYehKe(row.qanon_etebar)
data={
'id':eid,
'ref_id':row.Id,
'main_type': main_type,
'sub_type': sub_type,
'title': title,
'title_type': title_type,
'expire_date': expire_date,
'ts_date': row.aproveDate,
'ts_year': ts_year,
'ts_ref': ts_ref,
'qanon_etebar' : qanon_etebar,
'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp
}
if len(bulk_data) >= 100:
total_count += len(bulk_data)
print('=' * 10, ' law_reg_qanon_to_elastic , total='+str(total_count) , str(i)+ ', id=' + eid )
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
# limit POST Content-Length 8388608
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text)
# print(row.txt)
bulk_data.append(data)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 10, ' law_reg_qanon_to_elastic , total='+str(total_count) , str(i)+ ', id=' + eid )
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
print('end success law_reg_qanon_to_elastic ')
t2= datetime.datetime.now()
print(t2-t1)
@@ -0,0 +1,215 @@
import json
import requests
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
def import_relations_qanon_lwreg(cursor):
# اجرای کوئری SQL و خواندن داده‌ها به یک DataFrame
query = """
SELECT
l1.F_LWLAWID_LAW as id
, l1.F_LWSECTIONID as section_id
--, l2.CAPTION as from_title
-- ,(select top(1) tt1.id from lwSection tt1 where tt1.F_LWLAWID=l1.F_LWLAWID_LAW and tt1.FULLPATH = 'عنوان') as section_id2
, l3.[FULLPATH] as from_section_title
, l1.ISREFERENCE
, l1.F_LWLAWID_REGULATION as to_id
, l4.CAPTION as to_title
, 'مقرره' as to_type
FROM [Qavanin].[dbo].[lwLawRegulation] l1
left join lwLaw l2 on l1.F_LWLAWID_LAW=l2.id
left join lwsection l3 on l1.F_LWSECTIONID=l3.id
left join lwLaw l4 on l1.F_LWLAWID_REGULATION=l4.id
order by l1.F_lwlawid_law, l1.F_LWLAWID_REGULATION , l1.F_LWSECTIONID
"""
cursor.execute(query)
text_normal = TextNormalizer()
url = BASE_URL + "repo/majles/qaqanon/multi/update"
headers = HEADERS
total_count = 0
bulk_data = []
previd = ''
ref_state_array = []
t1= datetime.datetime.now()
print("start time: " + str(t1))
i = 0
all_data = []
repeat_data = []
relations = []
prev_eid = ''
prev_sectionid = ''
prev_to_id = ''
# rows = cursor.fetchall()
# for row in rows:
while 1:
i += 1
row = cursor.fetchone()
if not row:
break
eid='qq'+ str(row.id)
to_id = 'qq'+ str(row.to_id)
sectionid = str(row.section_id)
if sectionid != 'None' :
sectionid = 'qs'+ str(row.section_id)
else :
sectionid = ''
if (i%100) == 0 :
print('^' * 10, ' id=', eid, ' i=',i)
# ارتباط با خودش بی معنی است
# چند مورد در دیتابیس بود
if row.id == row.to_id :
continue
if eid == prev_eid and to_id == prev_to_id :
if prev_sectionid == sectionid :
continue
prev_to_id = to_id
prev_sectionid = sectionid
rel_type = 'عادی'
if int(row.ISREFERENCE) == 1:
rel_type = 'استناد'
from_type = "کل قانون"
if row.section_id :
from_type = "جزء قانون"
from_section_title = ''
if row.from_section_title :
from_section_title = text_normal.normalize_qanon(row.from_section_title)
to_title = text_normal.normalize_qanon( row.to_title )
to_type = row.to_type
relation = {
"from_type": from_type,
"from_section_id" : sectionid,
"from_section_title" : from_section_title,
"rel_type" : rel_type,
"to_type" : to_type,
"to_id" : to_id ,
"to_title" : to_title,
"wait" : 1,
"rel_key" : 'qavanin',
}
#print('%'*20, 'eid= ', eid, ' , ... prev_eid= ', prev_eid)
#print('--------- relations' , len(relations) )
#print(relation )
if prev_eid == '':
prev_eid = eid
continue
elif prev_eid == eid :
relations.append(relation)
continue
else :
data={
'id' : prev_eid,
'qanon_relations' : relations
}
total_count = total_count+1
# if total_count < 2560 :
# continue
bulk_data.append(data)
prev_eid = eid
relations=[]
relations.append(relation)
if len(bulk_data) >= 10:
total_count += len(bulk_data)
print('=' * 10, ' relations_qanon_lwreg , total='+str(total_count) , str(i)+ ', id=' + eid )
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
# limit POST Content-Length 8388608
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text)
# print(row.txt)
if len(relations) :
data={
'id' : prev_eid,
'qanon_relations' : relations
}
bulk_data.append(data)
while len(bulk_data) > 0 :
total_count += len(bulk_data)
print('=' * 10, ' relations_qanon_lwreg , total='+str(total_count))
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(bulk_data)
print(response.text)
bulk_data = []
bulk_data = pops_data
if not bulk_data :
break
t2= datetime.datetime.now()
print("finished time: " + str(t2))
print("process time: " + str(t2-t1))
print(' end success relations_qanon_lwreg ')
@@ -0,0 +1,214 @@
import json
import requests
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
def import_relations_qanon_opinion(cursor):
# اجرای کوئری SQL و خواندن داده‌ها به یک DataFrame
query = """
SELECT
l1.[F_LWLAWID] as id
,[F_LWSECTIONID] as section_id
, ls.[FULLPATH] as from_section_title
,[ISRELATED]
--,[F_CMBASETABLEID_OPBASEDOCTYPE]
--,l4.CAPTION
,[F_OPOPINIONID] as to_id
,og.CAPTION as to_type
,l3.CAPTION as to_title
FROM [Qavanin].[dbo].[opOpinionLaw] l1
left join [opOpinion] l2 on l1.[F_OPOPINIONID] = l2.id
left join opOpiniongiver og on l2.F_OPOPINIONGIVERID = og.id
left join lwLaw l3 on l2.[F_LWLAWID] = l3.id
left join lwsection ls on l1.F_LWSECTIONID=ls.id
--left join lwLaw l4 on l1.[F_LWLAWID] = l4.id
order by l1.[F_LWLAWID], [F_OPOPINIONID], [F_LWSECTIONID]
"""
cursor.execute(query)
text_normal = TextNormalizer()
url = BASE_URL + "repo/majles/qaqanon/multi/update"
headers = HEADERS
total_count = 0
bulk_data = []
previd = ''
ref_state_array = []
t1= datetime.datetime.now()
print("start time: " + str(t1))
i = 0
all_data = []
repeat_data = []
relations = []
prev_eid = ''
prev_section_id = ''
prev_to_id = ''
while 1:
i += 1
row = cursor.fetchone()
if not row:
break
eid='qq'+ str(row.id)
to_id = 'qo'+ str(row.to_id)
section_id = str(row.section_id)
if section_id != 'None' :
section_id = 'qs'+ str(row.section_id)
else :
section_id = ''
if eid == prev_eid and to_id == prev_to_id :
if prev_section_id == section_id :
continue
prev_to_id = to_id
prev_section_id = section_id
rel_type = 'عادی'
if int(row.ISRELATED) == 1:
rel_type = 'استناد'
from_type = "کل قانون"
if section_id :
from_type = "جزء قانون"
from_section_title = ''
if row.from_section_title :
from_section_title = text_normal.normalize_qanon(row.from_section_title)
to_title = text_normal.normalize_qanon( row.to_title )
to_type = ''
if row.to_type :
to_type = row.to_type.strip()
if to_type == 'راي هيات عمومي ديوان عدالت اداري' :
to_type = 'رای دیوان عدالت اداری'
if to_type == 'راي وحدت رويه ديوان عالي كشور' :
to_type = 'رای وحدت رویه'
if to_type == 'اداره کل حقوقی قوه قضائیه' :
to_type = 'نشست قضایی'
if to_type == 'نظر رياست مجلس - اصول 85 و 138' :
to_type = 'نظر ریاست مجلس'
relation = {
"from_type": from_type,
"from_section_id" : section_id,
"from_section_title" : from_section_title,
"rel_type" : rel_type,
"to_type" : to_type,
"to_id" : to_id ,
"to_title" : to_title,
"wait" : 1,
"rel_key" : 'qavanin',
}
#print('%'*20, 'eid= ', eid, ' , ... prev_eid= ', prev_eid)
#print('--------- relations' , len(relations) )
#print(relation )
if (i%100) == 0 :
print('^' * 10, ' id=', eid, ' i=',i)
if prev_eid == '':
prev_eid = eid
continue
elif prev_eid == eid :
relations.append(relation)
continue
else :
data={
'id' : prev_eid,
'opinion_relations' : relations
}
bulk_data.append(data)
prev_eid = eid
relations=[]
relations.append(relation)
if len(bulk_data) >= 10:
total_count += len(bulk_data)
print('=' * 10, ' relations_qanon_opinion , total='+str(total_count) , str(i)+ ', id=' + eid )
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
# limit POST Content-Length 8388608
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(bulk_data)
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text)
# print(row.txt)
if len(relations) > 0 :
data={
'id' : prev_eid,
'opinion_relations' : relations
}
bulk_data.append(data)
while len(bulk_data) > 0 :
total_count += len(bulk_data)
print('=' * 10, ' relations_qanon_opinion , total='+str(total_count))
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
pops_data = []
while len(payload) > 8388608 :
el = bulk_data.pop()
total_count -= 1
pops_data.append(el)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
if response.status_code != 200 :
print(bulk_data)
print(response.text)
bulk_data = []
bulk_data = pops_data
if not bulk_data :
break
t2= datetime.datetime.now()
print("update rows count: " + str(len(all_data)))
print("finished time: " + str(t2))
print("process time: " + str(t2-t1))
print(' end success relations_qanon_opinion')