refactor 2

This commit is contained in:
hsafaei
2025-09-02 12:15:47 +03:30
parent cfe3cff77c
commit 5a6647bbf2
62 changed files with 151 additions and 160 deletions
+2
View File
@@ -0,0 +1,2 @@
+219
View File
@@ -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 common.config_base import *
from common.general_functions import *
from 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 ')
+374
View File
@@ -0,0 +1,374 @@
import json
import requests
import requests
from html import escape
import json
from decimal import Decimal
import datetime
from common.config_base import *
from common.general_functions import *
from 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 common.config_base import *
from common.general_functions import *
from common.text_normalizer import TextNormalizer
from common.elastic_helper import ElasticHelper
from 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 common.text_normalizer import TextNormalizer
from common.config_base import *
from 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 ')
+277
View File
@@ -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 common.config_base import *
from common.general_functions import *
from 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 common.config_base import *
from common.general_functions import *
from 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 common.config_base import *
from common.general_functions import *
from 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 common.config_base import *
from common.general_functions import *
from 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 common.config_base import *
from common.general_functions import *
from 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 common.config_base import *
from common.general_functions import *
from 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)
+215
View File
@@ -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 common.config_base import *
from common.general_functions import *
from 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 common.config_base import *
from common.general_functions import *
from 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')