refactor to auto import

This commit is contained in:
hsafaei
2025-01-13 10:50:00 +03:30
parent e991cc84cb
commit d819408715
35 changed files with 3832 additions and 1504 deletions
-135
View File
@@ -1,135 +0,0 @@
import requests
import json
from config_base import *
from general_functions import *
cursor, cnxn = create_cursor()
# -----------------------------------------------------------------
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,
"type": 3,
"item_state": 1,
"ispublic" : 1,
}
# requests.post(BASE_URL + 'list/' + ADD_LIST_ROUTE, data=ADD_LIST_QUERY, headers = HEADERS)
projectid = 1
EXAMPLE_ADD_ITEM_QUERY = {
"title": "",
"projectid": projectid,
"listtype": 0,
"parent": 0,
}
query = """select * from dbo.lwtopic"""
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 + '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
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_LWTopic.json", 'w') as file:
file.write(json.dumps(IDS_DICT))
-324
View File
@@ -1,324 +0,0 @@
import json
import requests
from config_base import *
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 config_base import *
from general_functions import *
cursor, cnxn = create_cursor()
#Does quasi the same things as json.loads from here: https://pypi.org/project/dynamodb-json/
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
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
'''
#####
# --,nestedSectionChanghed.APPROVEDATE as effect_Date,
# --nestedSectionChanghed.textEFFECTIVE as effect_text,
# --nestedSectionChanghed.textPrev as effect_prev_text,
# --nestedSectionChanghed.qanonEFFECTIVE as effect_qanon,
# --nestedSectionChanghed.F_LWLAWID_EFFECTIVE as effect_section_id,
# --nestedSectionChanghed.[F_LWSECTIONID_EFFECTIVE] as effect_qanon_id
#####
# left join (
# SELECT
# gl3.[SECTIONTEXT] as textEFFECTIVE,
# gl5.SECTIONTEXT as textPrev,
# gl4.APPROVEDATE,
# gl4.CAPTION as qanonEFFECTIVE,
# gl1.F_LWLAWID_EFFECTIVE,
# gl1.[F_LWSECTIONID_EFFECTIVE],
# gl1.[F_LWSECTIONID_EFFECTED]
# FROM [Qavanin].[dbo].[lwSectionChange] gl1
# 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 gl5 on gl1.[F_LWSECTIONLOGID_EFFECTED]=gl5.ID
# where
# gl4.ISLAW = 1
# and gl1.[F_LWSECTIONID_EFFECTED] is not null
# ) as nestedSectionChanghed ON s.id=nestedSectionChanghed.[F_LWSECTIONID_EFFECTED]
def isNeedHtml(html):
if "<TABLE" in html or "<table" in html or "</TR" in html or "</tr" in html :
return True
else:
return False
cursor.execute(query)
url = BASE_URL + "repo/majles/section/multi/add"
dict_topic = json.loads(open("list_LWTopic.json").read())
headers = HEADERS
bulk_count = 1
bulk_data = []
t1= datetime.datetime.now()
print(t1)
i = 1
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 = normalYehKe(text)
content_len = text.__len__()
qanon_title = normalYehKe( row.lawTitle )
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 = row.qanon_etebar
# 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)
# ref_state = {
# "qanon_id": efect_qanon_id,
# "qanon_date": row.effect_Date,
# "section_id": efect_section_id,
# "qanon_title" : normalYehKe(row.effect_qanon),
# # "section_text" : normalYehKe(row.effect_text), # نیاز نیست
# "prev_text" : normalYehKe(row.effect_prev_text)
# }
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,
'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 bulk_count > 100:
print('=' * 10 )
print(str(i)+ ', id=' + eid)
print(', lawid=' + lawId)
if bulk_count > 0:
print(', 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(response)
bulk_data = []
bulk_count = 0
# print(response.text)
#print(row.txt)
bulk_data.append(data)
bulk_count +=1
if bulk_count > 0:
print(bulk_count)
if bulk_count > 0:
print(', lawid_first=' + bulk_data[0]['qanon_id'])
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
cursor.close()
cnxn.close()
print('end success')
t2= datetime.datetime.now()
print(t2-t1)
-328
View File
@@ -1,328 +0,0 @@
import json
import requests
from config_base import *
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import re
import datetime
from config_base import *
from general_functions import *
'''
# این متد یک متن و ایندکس آغاز و پایان یک عبارت درون آن متن را دریافت می کند
# و شماره توکن آغازین و توکن پایانی مربوط به عبارت در متن را بر می گرداند
def token_state_finder(normalized_section_content, start_index, end_index):
before_substring = normalized_section_content[0:start_index].strip()
pattern_substring = normalized_section_content[start_index:end_index].strip()
before_substring_token_list = before_substring.strip().split()
pattern_token_list = pattern_substring.strip().split()
start_token_state = len(before_substring_token_list) + 1
end_token_state = len(before_substring_token_list) + (len(pattern_token_list))
pattern_tokens_state = [
{"start_token_state": start_token_state, "end_token_state": end_token_state}
]
return pattern_tokens_state
def find_number_indexes_in_string(normalized_string,recognized_numbers):
complete_recognized_numbers = []
for item in recognized_numbers:
number_start_index, number_end_index = find_token_indexes_in_string(normalized_string,item['start_token_index'],item['end_token_index'])
complete_recognized_numbers.append(
{
'number_value' : item['number_value'],
'number_token_list' : item['number_token_list'],
'start_token_index' : item['start_token_index'],
'end_token_index' : item['end_token_index'],
"start_number_state": number_start_index,
"end_number_state" : number_end_index
}
)
return complete_recognized_numbers
# این متد متن اصلی یک متن، توکن آغازین و توکن پایانی مربوط به یک عبارت را می گیرد
# و ایندکس آغاز و ایندکس پایان متن وارد شده را بر می گرداند
def find_token_indexes_in_string(normalized_string,start_token_index,end_token_index):
before_tokens = normalized_string.split()[0:start_token_index]
content_tokens = normalized_string.split()[start_token_index:end_token_index + 1]
content_start_index = 0
content_end_index = 0
# شمردن تعداد کاراکترهای هر توکن در لیست توکن قبل از عدد
for token in before_tokens:
content_start_index += len(token)
# اضافه کردن تعداد فاصله های خالی یا همان اسپیس به عدد ایندکس شروع عدد
content_start_index += len(before_tokens) + 1
# شمردن تعداد کاراکترهای هر توکن در لیست توکن مربوط به عدد
for token in content_tokens:
content_end_index += len(token)
# اضافه کردن تعداد فاصله های خالی یا همان اسپیس به عدد ایندکس پایان عدد
content_end_index += (content_start_index - 1) + (len(content_tokens) - 1)
return content_start_index, content_end_index
# این متد، متنی را دریافت می کند و الگوهای تعریف شده را در آن جستجو می کند و آرایه ای از عبارات مطابق با هر الگو،
# شماره ایندکس شروع و پایان هر عبارت، عنوان و محتوای الگو، و شماره توکن شروع و توکن پایانی هر عبارت
# پیدا شده را بر می گرداند
def regex_patterns_finder(sectoin_content):
regex_patterns = [
{
"asle N asasi": r"اصل\s*شماره\s*(\d+)\s*قانون\s*اساسی\s*جمهوری\s*اسلامی\s*ایران"
}, # اصل شماره فلان قانون اساسی جمهوری اسلامی ایران
{
"qanone asasi": r"(?<!^)\b\sقانون\sاساسی\sجمهوری\sاسلامی\sایران"
}, # قانون اساسی جمهوری اسلامی ایران که در اول پاراگراف نباشد
{"in qanon": r"\sاین\sقانون"}, # این قانون
{"qanone foq": r"\sقانون\sفوق"}, # قانون فوق
{"eslahe qanon": r"\sقانون\sاصلاح"}, # اصلاح قانون
{"tabsare foq": r"\sتبصره\sفوق"}, # تبصره فوق
{"made foq": r"\ماده\sفوق"}, # ماده فوق
{"made vahed": r"\sماده\sواحده"}, # ماده واحده
{
"tabsare N": r"^\bتبصره\s*شماره\s*(\d+)\s*"
}, # تبصره شماره فلان که فقط اول پاراگراف باشد
{
"f tabsare N": r"(?<!^)\bتبصره\sشماره\s(\d+)\s"
}, # تبصره شماره فلان که همه جا غیر از اول پاراگراف باشد
{
"tabsare N": r"(?<!^)\bتبصره\s(\d+)\s"
}, # تبصره شماره فلان که همه جا غیر از اول پاراگراف باشد
{
"made N": r"ماده ?\(? ?\d+? ?\)?[ :.]"
}, # *** ماده فلان که هرجای پاراگراف غیر از اول آن باشد
{
"f made N": r"^\bماده\s*[(]?\s*(\d+)\s*[)]?\s*"
}, # ماده فلان که فقط اول پاراگراف باشد با یا بدون ترکیب عدد با پرانتز
]
matched_array = []
for pattern in enumerate(regex_patterns):
current_pattern = pattern[1]
keys = current_pattern.keys()
values = current_pattern.values()
value = []
key = []
for k_items in keys:
key.append(k_items)
for v_items in values:
value.append(v_items)
current_pattern_key = key[0]
current_pattern_value = value[0]
regex = re.compile(current_pattern_value)
matches = regex.finditer(sectoin_content)
for match in matches:
# انجام عملیات مرتبط با هر الگو در اینجا
founded_item = match.group()
start_index = match.start()
end_index = match.end() - 1
pattern_tokens_state = token_state_finder(
sectoin_content, start_index, end_index
)
matched_array.append(
{
"founded_item": founded_item,
"start_index": start_index,
"end_index": end_index,
"pattern_key": current_pattern_key,
"pattern_value": current_pattern_value,
"start_token_state": pattern_tokens_state[0]["start_token_state"],
"end_token_state": pattern_tokens_state[0]["end_token_state"],
}
)
# convertedText = regex.sub(' wwwwwwwww ',convertedText)
return matched_array
'''
section_content = """
مبلغ آن شش هزار و سيصد و سي و دو ميليون و پانصد هزار (- /۶۳۳۲۵۰۰۰۰۰) ين
مبلغ هفت ميليون و نهصد و ده هزار (000 / 910 / 7) ريال جهت
مبلغ شانزده ميليون و ششصد و بيست و نه هزار و ششصد و پنجاه و هفت (657 / 629 / 16) ريال
‌قانون اجازه بر اساس ماده (4) قانون مالیات ، پرداخت دودوازدهم هزینه کل کشور بابت دوماهه تیر و مرداد 1323 ‌مصوب 27 تیر ماه 1323‌ ماده واحده - قانون مصوب 31 فروردین ماه 1323 برای پرداخت هزینه‌های کشور دردوماهه تیر و مرداد 1323 به قوت خود باقی و به وزارت‌دارایی اجازه داده می‌شود هزینه ماههای مذکور را بر طبق قانون مصوب 31 فروردین ماه 1323 بپردازد.‌ تبصره دو - دولت مکلف است بودجه‌های جزء وزارتخانه‌ها و ادارات را که تاکنون به مجلستسلیم نشده تا 15 مرداد و بودجه‌های بازرگانی و کارخانجات و‌مؤسسات اقتصادی راحداکثر تا 15 شهریور به مجلس شورای ملی تقدیم دارد.
"""
cursor, cnxn = create_cursor()
# Does quasi the same things as json.loads from here: https://pypi.org/project/dynamodb-json/
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
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(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)
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
bulk_count = 1
bulk_data = []
t1 = datetime.datetime.now()
print(t1)
i = 1
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 = normalYehKe(text)
content_len = text.__len__()
title = normalYehKe(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_year = ""
if row.ts_date:
items = row.ts_date.split("/")
if items.__len__() > 0:
ts_year = items[0]
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(row.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": row.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 bulk_count > 10:
# print('=' * 10 )
print(str(i) + ", id=" + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
print(response)
bulk_data = []
bulk_count = 1
# print(response.text)
# print(row.txt)
bulk_data.append(data)
bulk_count += 1
if bulk_count > 0:
print(bulk_count)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
cursor.close()
cnxn.close()
print("end success")
t2 = datetime.datetime.now()
print(t2 - t1)
-276
View File
@@ -1,276 +0,0 @@
import json
import requests
from config_base import *
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 config_base import *
from general_functions import *
cursor, cnxn = create_cursor()
#Does quasi the same things as json.loads from here: https://pypi.org/project/dynamodb-json/
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
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)
url = BASE_URL + "repo/majles/rgsection/multi/add"
dict_topic = json.loads(open("list_LWTopic.json").read())
headers = HEADERS
bulk_count = 1
bulk_data = []
t1= datetime.datetime.now()
print(t1)
i = 1
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 = normalYehKe(text)
content_len = text.__len__()
qanon_title = normalYehKe( row.lawTitle )
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 = 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,
'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 bulk_count > 100:
print('=' * 10 )
print(str(i)+ ', id=' + eid)
print(', lawid=' + lawId)
if bulk_count > 0:
print(', 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(response)
bulk_data = []
bulk_count = 0
# print(response.text)
#print(row.txt)
bulk_data.append(data)
bulk_count +=1
if bulk_count > 0:
print(bulk_count)
if bulk_count > 0:
print(', lawid_first=' + bulk_data[0]['qanon_id'])
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
cursor.close()
cnxn.close()
print('end success')
t2= datetime.datetime.now()
print(t2-t1)
-211
View File
@@ -1,211 +0,0 @@
import json
import requests
from config_base import *
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 config_base import *
from general_functions import *
# ضرورتا
# این برنامه ضرورت دارد اجرا شود
cursor, cnxn = create_cursor()
#Does quasi the same things as json.loads from here: https://pypi.org/project/dynamodb-json/
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
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
'''
# ar = []
# for i,item in enumerate(str):
# if item == ' ':
# print(i)
# ar.append(i)
# print(len(str.strip().split()))
cursor.execute(query)
url = BASE_URL + "repo/majles/section/multi/update"
dict_topic = json.loads(open("list_LWTopic.json").read())
headers = HEADERS
bulk_count = 1
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" : normalYehKe(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" : normalYehKe(row.effect_text),
"prev_text" : normalYehKe(row.effect_prev_text),
"description" : normalYehKe(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)
bulk_count +=1
ref_state_array = []
previd = eid
prev_efect_section_id = efect_section_id
prev_effect_type = effect_type
ref_state_array.append(ref_state)
if bulk_data.__len__() > 100:
print('=' * 10 )
print(str(i)+ ', id=' + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
print(response)
bulk_data = []
bulk_count = 1
# 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 bulk_data.__len__() > 0:
print(bulk_count)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
# print(response.text)
cursor.close()
cnxn.close()
print('end success')
t2= datetime.datetime.now()
print(t2-t1)
-211
View File
@@ -1,211 +0,0 @@
import json
import requests
from config_base import *
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 config_base import *
from general_functions import *
# ضرورتا
# این برنامه ضرورت دارد اجرا شود
cursor, cnxn = create_cursor()
#Does quasi the same things as json.loads from here: https://pypi.org/project/dynamodb-json/
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
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
'''
# ar = []
# for i,item in enumerate(str):
# if item == ' ':
# print(i)
# ar.append(i)
# print(len(str.strip().split()))
cursor.execute(query)
url = BASE_URL + "repo/majles/rgsection/multi/update"
dict_topic = json.loads(open("list_LWTopic.json").read())
headers = HEADERS
bulk_count = 1
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" : normalYehKe(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" : normalYehKe(row.effect_text),
"prev_text" : normalYehKe(row.effect_prev_text),
"description" : normalYehKe(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)
bulk_count +=1
ref_state_array = []
previd = eid
prev_efect_section_id = efect_section_id
prev_effect_type = effect_type
ref_state_array.append(ref_state)
if bulk_data.__len__() > 100:
print('=' * 10 )
print(str(i)+ ', id=' + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
print(response)
bulk_data = []
bulk_count = 1
# 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 bulk_data.__len__() > 0:
print(bulk_count)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
# print(response.text)
cursor.close()
cnxn.close()
print('end success')
t2= datetime.datetime.now()
print(t2-t1)
+52
View File
@@ -0,0 +1,52 @@
import requests
import json
from decimal import Decimal
from config_base import *
from 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 *
# -----------------------------------------------------------------
## ابتدا دستورات زیر را به ترتیب در دیتابیس فهرست اجرا شود
# 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_opinion_to_elastic(cursor)
import_regulation_section_to_elastic(cursor)
import_law_section_update_ref_state(cursor)
cursor.close()
cnxn.close()
+6 -2
View File
@@ -4,12 +4,16 @@ import pyodbc
# این توکن بسیار مهم است. چون هر از گاهی این توکن منقضی می شود # این توکن بسیار مهم است. چون هر از گاهی این توکن منقضی می شود
# و باید توکن معتبر جدید از سایت قوانین درحالت لاگین شده، # و باید توکن معتبر جدید از سایت قوانین درحالت لاگین شده،
# دریافت شود و به جای توکن زیر جایگزین شود # دریافت شود و به جای توکن زیر جایگزین شود
TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MjU5ODAwODQsImp0aSI6IllWR2N3V2UrTGltTVFhbVwvS0wrd1NvVDRlVk1ZdjhaYSIsImlzcyI6bnVsbCwiZXhwIjoxNzI3MjgwMDgzLCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjIsImZpcnN0X25hbWUiOiJcdTA2MmRcdTA2NDVcdTA2Y2NcdTA2MmYiLCJsYXN0X25hbWUiOiJcdTA2MzVcdTA2NDFcdTA2MjdcdTA2Y2NcdTA2Y2MiLCJlbWFpbCI6InNhZmFlaS5oYW1pZEBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImhzYWZhZWkiLCJ1c2VyX2xldmVsIjoyfX0.bKLh7J_PYpcTy9sZ1VqMF0Vd2GvCHNXWX130ny8WZRY'
#TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MzM2Njk2NjIsImp0aSI6Ik5zRDJpNDZrcDFsNHdKRU9KR2x2Vnl0ejBNenlpMmFMIiwiaXNzIjpudWxsLCJleHAiOjE3MzQ5Njk2NjEsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDYyOFx1MDYzMVx1MDY0Nlx1MDYyN1x1MDY0NVx1MDY0NyBcdTA2NDZcdTA2NDhcdTA2Y2NcdTA2MzMiLCJsYXN0X25hbWUiOiJcdTA2NDFcdTA2NDZcdTA2Y2MiLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.K5Z4150USK2WvdC7eo1v8koiR2wRN1--XY7Xf9LhMEA'
TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3MzY3MDAxNjksImp0aSI6IlwvYkhhWktHNmlMR0YxWTBwdk5OM3YzZ2dycUpNWHRmQyIsImlzcyI6bnVsbCwiZXhwIjoxNzM4MDAwMTY4LCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjEsImZpcnN0X25hbWUiOiJcdTA2NDVcdTA2MmZcdTA2Y2NcdTA2MzEgXHUwNjQxXHUwNjQ2XHUwNmNjIiwibGFzdF9uYW1lIjoiXHUwNjMzXHUwNjI3XHUwNjQ1XHUwNjI3XHUwNjQ2XHUwNjQ3IiwiZW1haWwiOiJkZXZAZ21haWwuY29tIiwidXNlcm5hbWUiOiJkZXYiLCJ1c2VyX2xldmVsIjoyfX0.lH9X9ACG2rzTWPyrYdxZFzmAUBr2qG0KQJoCZ7wN-rs'
ACCEPT = "application/json" ACCEPT = "application/json"
HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT} HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT}
# BASE_URL = "https://api.tavasi.ir/" # BASE_URL = "https://api.tavasi.ir/"
BASE_URL = "http://192.168.23.160:8080/" #BASE_URL = "https://hamfahmi.ir/api/"
BASE_URL = "http://192.168.23.160/api/"
# BASE_URL = "http://192.168.23.60/api/"
# endregion # endregion
+8
View File
@@ -6,6 +6,8 @@ from re import sub
import textwrap import textwrap
from html import escape from html import escape
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
import json
from decimal import Decimal
# from lxml import etree # from lxml import etree
import datetime import datetime
@@ -29,6 +31,12 @@ for tag in tableTag:
regTable = r'<(?P<slash>\/)*(?P<tag>'+strTable+')(?P<class>[^>]+)*>' regTable = r'<(?P<slash>\/)*(?P<tag>'+strTable+')(?P<class>[^>]+)*>'
regTableReplace = r'#[#\g<slash>\g<tag>\g<class>#]#' regTableReplace = r'#[#\g<slash>\g<tag>\g<class>#]#'
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
def isNeedHtml(html): def isNeedHtml(html):
if "<TABLE" in html or "<table" in html or "</TR" in html or "</tr" in html : if "<TABLE" in html or "<table" in html or "</TR" in html or "</tr" in html :
+3
View File
@@ -0,0 +1,3 @@
:: G:\Project2\NLP\SqlToElasticMajles\import_all.bat >> import_all.txt 2>&1
python .\1_LWTopic.py > output1.txt
+15
View File
@@ -0,0 +1,15 @@
:: G:\Project2\NLP\SqlToElasticMajles\import_all.bat >> import_all.txt 2>&1
:: python .\1_LWTopic.py > output1.txt
:: python .\2_LawSection_ToElastic.py > output2.txt
:: python .\3_opinion_ToElastic.py > output3.txt
:: python .\4_RegulationSection_ToElastic.py > output4.txt
:: python .\5_LawSection_update_ref_state.py > output5.txt
:: python .\6_RegulationSection_update_ref_state.py > output6.txt
:: python .\7_LawReg_qanon_ToElastic.py > output7.txt
python .\8_Relations_qanon_LWReg.py > output8.txt
python .\9_Relations_qanon_opinion.py > output9.txt
:: python .\10_LawReg_lwphase_Info.py > output10.txt
+1 -1
View File
File diff suppressed because one or more lines are too long
+94
View File
@@ -0,0 +1,94 @@
import requests
import json
import os
from config_base import *
from general_functions import *
cursor, cnxn = create_cursor()
# -----------------------------------------------------------------
ADD_LIST_ROUTE = "project/add"
ADD_ITEM_ROUTE = "subject/add"
TITLE = "استانها و شهرهای ایران"
TYPE = 2
ADD_LIST_QUERY = {
"title": TITLE,
"type": 2,
"item_state": 0,
"ispublic" : 1,
"tags": "province",
}
# result= requests.post(BASE_URL + 'list/' + ADD_LIST_ROUTE, data=ADD_LIST_QUERY, headers = HEADERS)
# print(result)
# print(result.text)
# projectid = json.loads(result.text)["data"]["id"]
# exit()
projectid = 1000
# EXAMPLE_ADD_ITEM_QUERY = {
# "title": "",
# "projectid": projectid,
# "listtype": 0,
# "parent": 0,
# }
file_path = os.getcwd() + '/ostan.txt'
lines = []
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
print(len(lines))
ostan_dic={}
ostan_order = 0
shahr_order = 0
number = 0
for line in lines:
items = line.strip('\n').split('\t')
# print(items)
number +=1
if len(items) != 2 :
continue
ostan=items[0]
shahr=items[1]
if ostan not in ostan_dic:
ostan_order= ostan_order+1
payload = {
"title": ostan,
"projectid": projectid,
"childorder": ostan_order,
"listtype": 2,
"parent": 0,
}
result = requests.post(BASE_URL + 'list/' + ADD_ITEM_ROUTE, data=payload, headers=HEADERS)
# print(result.text)
id = json.loads(result.text)["data"][0]["id"]
ostan_dic[ostan]=id
ostan_id=ostan_dic[ostan]
shahr_order = shahr_order + 1
payload = {
"title": shahr,
"projectid": projectid,
"childorder": shahr_order,
"listtype": 2,
"parent": ostan_id,
}
result = requests.post(BASE_URL + 'list/' + ADD_ITEM_ROUTE, data=payload, headers=HEADERS)
id = json.loads(result.text)["data"][0]["id"]
print('-'*10, id, ' ', shahr_order )
+1132
View File
File diff suppressed because it is too large Load Diff
+217
View File
@@ -0,0 +1,217 @@
import json
import requests
from config_base import *
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
from config_base import *
from general_functions import *
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
rr = {"id" : int(row.ID), 'title': row.CAPTION}
ORG_DICT[str(int(row.ID))] = {"id" : row.ID, 'title': row.CAPTION}
#نکته : برای مقررات هیچ موردی نبود که جدولی باشد
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)
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(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 == 500 :
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 ')
+127
View File
@@ -0,0 +1,127 @@
import requests
import json
from text_normalizer import TextNormalizer
from config_base import *
from 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 ')
+278
View File
@@ -0,0 +1,278 @@
import json
import requests
from config_base import *
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import time
from config_base import *
from general_functions import *
from 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)
+200
View File
@@ -0,0 +1,200 @@
import json
import requests
from config_base import *
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import re
import datetime
from config_base import *
from general_functions import *
from 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)
+276
View File
@@ -0,0 +1,276 @@
import json
import requests
from config_base import *
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 config_base import *
from general_functions import *
from 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)
+210
View File
@@ -0,0 +1,210 @@
import json
import requests
from config_base import *
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 config_base import *
from general_functions import *
from 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)
+210
View File
@@ -0,0 +1,210 @@
import json
import requests
from config_base import *
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 config_base import *
from general_functions import *
from 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)
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" : normalYehKe(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" : normalYehKe(row.effect_text),
"prev_text" : normalYehKe(row.effect_prev_text),
"description" : normalYehKe(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)
+186
View File
@@ -0,0 +1,186 @@
import json
import requests
from config_base import *
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
from config_base import *
from general_functions import *
from 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)
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 = normalYehKe( 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 = 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)
+214
View File
@@ -0,0 +1,214 @@
import json
import requests
from config_base import *
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
from config_base import *
from general_functions import *
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)
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 = row.from_section_title
to_title = normalYehKe( 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 == 500 :
print(bulk_data)
print(response.text)
bulk_data = []
bulk_data = pops_data
t2= datetime.datetime.now()
print("finished time: " + str(t2))
print("process time: " + str(t2-t1))
print(' end success relations_qanon_lwreg ')
+211
View File
@@ -0,0 +1,211 @@
import json
import requests
from config_base import *
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
from config_base import *
from general_functions import *
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)
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 = row.from_section_title
to_title = normalYehKe( 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 == 500 :
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,
'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(response.text)
bulk_data = []
bulk_data = pops_data
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')
+10
View File
@@ -0,0 +1,10 @@
python.exe .\6_RegulationSection_update_ref_state.py
python.exe .\8_Tanghih_plan_move.py
python.exe .\20_LawReg_qanon_ToElastic.py
python.exe .\21_Relations_qanon_LWReg.py
python.exe .\22_Relations_qanon_opinion.py
@@ -17,6 +17,8 @@ from general_functions import *
# این برنامه یک بار فقط جهت انتقال کدهای دیتابیس آقای شاهنوش به دیتابیس نهایی قوانین انجام شد # این برنامه یک بار فقط جهت انتقال کدهای دیتابیس آقای شاهنوش به دیتابیس نهایی قوانین انجام شد
# تکرار لازم نیست # تکرار لازم نیست
# در بقیه حالات اگر کدها تغییر نکرده باشد در خود الاستیک بروز رسانی می شود
cursor, cnxn = create_cursor('db4minaei') cursor, cnxn = create_cursor('db4minaei')
@@ -75,7 +77,7 @@ dict_topic = json.loads(open("list_LWTopic.json").read())
headers = HEADERS headers = HEADERS
bulk_count = 1 total_count = 0
bulk_data = [] bulk_data = []
previd = '' previd = ''
@@ -150,25 +152,36 @@ while 1:
# print(eid) # print(eid)
bulk_data.append(data) bulk_data.append(data)
bulk_count +=1
prev_sectionid = sectionid prev_sectionid = sectionid
tcode_main_old = [] tcode_main_old = []
tcode_sub_old = [] tcode_sub_old = []
tcode_main = [] tcode_main = []
tcode_sub = [] tcode_sub = []
if bulk_data.__len__() > 100: if len(bulk_data) >= 100:
print('=' * 10 ) total_count += len(bulk_data)
print(str(i)+ ', id=' + eid) print('=' * 10, ', total='+str(total_count) , str(i)+ ', id=' + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works! payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload)
# print(response.text)
bulk_data = []
bulk_count = 1
# print(payload)
# 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 == 500 :
print(response.text)
bulk_data = []
break
bulk_data = pops_data
# print(response)
# print(response.text) # print(response.text)
#print(row.txt) # print(row.txt)
# ///////////////// # /////////////////
prev2_sectionid = prev_sectionid prev2_sectionid = prev_sectionid
@@ -208,10 +221,10 @@ data={
} }
bulk_data.append(data) bulk_data.append(data)
bulk_count +=1
if bulk_data.__len__() > 0: if len(bulk_data) > 0:
print(' *** end bulk count ' , bulk_count) total_count += len(bulk_data)
print('=' * 10, ', total='+str(total_count) , str(i)+ ', id=' + eid)
payload = json.dumps(bulk_data, cls=JSONEncoder) #Works! payload = json.dumps(bulk_data, cls=JSONEncoder) #Works!
response = requests.request("POST", url, headers=headers, data=payload) response = requests.request("POST", url, headers=headers, data=payload)
+113
View File
@@ -0,0 +1,113 @@
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import sys
import json
from decimal import Decimal
from general_functions import *
cursor = create_cursor()
#Does quasi the same things as json.loads from here: https://pypi.org/project/dynamodb-json/
class JSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Decimal):
return float(obj)
return json.JSONEncoder.default(self, obj)
query = ''' SELECT l1.[ID] as F_LWSECTIONID1
,l1.[F_LWLAWID] as F_LWLAWID1
,l1.F_LWPHASEID as F_LWPHASEID1
,l1.[F_LWSECTIONID_REPLACED] as F_LWSECTIONID2
,l3.SECTIONTEXT
,l4.F_LWLAWID_EFFECTIVE as F_LWLAWID2
,l4.F_LWPHASEID_EFFECTIVE as F_LWPHASEID2
FROM [AIPLawDCIT].[dbo].[lwsection] l1
left join [AIPLawDCIT].[dbo].[lwsection] l2 on l1.F_LWSECTIONID_REPLACED = l2.id
left join lwsectionlog l3 on l1.id=l3.F_LWSECTIONID
left join lwlawchange l4 on l1.[F_LWLAWCHANGEID]=l4.id
left join lwphase l6 on l4.F_LWLAWID_EFFECTIVE = l6.id
where l1.[F_LWSECTIONID_REPLACED] is not null
order by l1.F_LWLAWID'''
cursor.execute(query)
url = "https://api.tavasi.ir/repo/majles/section/add"
url_relation = "https://api.tavasi.ir/relation/main/add"
headers = HEADERS
headers2 = {
"Accept": ACCEPT,
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": TOKEN,
}
rel_id_replaced = 100
rel_id_effective = 102
i = 1
while 1:
row = cursor.fetchone()
if not row:
break
print(str(i)+ ', qanonid='+str(row.F_LWLAWID1) + ', id=' + str(row.F_LWSECTIONID1))
i=i+1
if row.F_LWLAWID2 is not None and str(row.F_LWLAWID2) != '' :
payload = {
"check_exist": 1,
"service_id1": 'repo',
"entity_type1": 'mqanon',
"entity_id1": 'mj_mtaghnin_'+ str(row.F_LWLAWID2),
"relation_id": rel_id_effective,
"service_id2": 'repo',
"entity_type2": 'mqanon',
"entity_id2": 'mj_mtaghnin_'+ str(row.F_LWLAWID1),
}
response = requests.request("POST", url_relation, headers=headers2, data=payload)
print(response)
payload = {
"check_exist": 0,
"service_id1": 'repo',
"entity_type1": 'mqsection',
"entity_id1": 'mj_mq_section_'+ str(row.F_LWSECTIONID2),
"relation_id": rel_id_replaced,
"service_id2": 'repo',
"entity_type2": 'mqsection',
"entity_id2": 'mj_mq_section_'+ str(row.F_LWSECTIONID1),
}
response = requests.request("POST", url_relation, headers=headers2, data=payload)
print(response)
# if row.SECTIONTEXT is not None and str(row.SECTIONTEXT) != '' :
# eid = 'mj_mq_section_'+ str(row.F_LWSECTIONID2)
# new_content = row.SECTIONTEXT
# soup = BeautifulSoup(new_content, "html.parser")
# text = soup.get_text("\n", strip=True)
# content_len = text.__len__()
# data={
# 'id':eid,
# 'content': new_content,
# 'content_len': content_len,
# 'ref_content':escape(new_content)
# }
# payload = json.dumps(data, cls=JSONEncoder) #Works!
# response = requests.request("POST", url, headers=headers, data=payload)
# result = json.loads( response )
# # result["meta"][0]["1"]
cursor.close()
cnxn.close()
print('end success')
Binary file not shown.
+26
View File
@@ -0,0 +1,26 @@
import pyodbc
TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2OTM5MDgzMDksImp0aSI6IjZDREM2UjB4ZFh2Y0hMUzBmdTVUQnpjZ1lLZHNMOXdEIiwiaXNzIjoiaHR0cHM6XC9cL2NwLmhhbWZhaG1pLmlyIiwiZXhwIjoxNjk1MjA4MzA4LCJhdWQiOiJodHRwczpcL1wvY3AuaGFtZmFobWkuaXIiLCJkYXRhIjp7ImlkIjoyLCJmaXJzdF9uYW1lIjoiXHUwNjJkXHUwNjQ1XHUwNmNjXHUwNjJmIiwibGFzdF9uYW1lIjoiXHUwNjM1XHUwNjQxXHUwNjI3XHUwNmNjXHUwNmNjIiwiZW1haWwiOiJzYWZhZWkuaGFtaWRAZ21haWwuY29tIiwidXNlcm5hbWUiOiJoc2FmYWVpIiwidXNlcl9sZXZlbCI6Mn19.soDo9t8FtinMamONlivJFGEVRLHOtjBOg5gzt55QVzg"
ACCEPT = "application/json"
HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT}
def create_cursor():
server = "DESKTOP-ENVCI85"
database = "AIPLawDCIT"
username = "Mofid3"
password = "12345"
# ENCRYPT defaults to yes starting in ODBC Driver SQL Server. It's good to always specify ENCRYPT=yes on the client side to avoid MITM attacks.
cnxn = pyodbc.connect(
"DRIVER={SQL Server};SERVER="
+ server
+ ";DATABASE="
+ database
+ ";Trusted_Connection=yes;UID="
+ username
+ ";PWD="
+ password
)
# cnxn = pyodbc.connect('DSN=sqldsn;')
cursor = cnxn.cursor()
return cursor
+214
View File
@@ -0,0 +1,214 @@
import re
class TextNormalizer:
def __init__(self, options=None):
self.options = options if options else {
"charArNormal": True,
"errorLine": True,
"alphabetsNormal": False,
"emptylinesNormal": False,
"hamzehNormal": False,
"spaceCorrection": False,
"trimLine": False
}
def split_words(self, text) :
words = re.split(r"[\t\n\r\.\"«»\)\(\]\[,;،؛ \-!?:]+", text)
return words
def normalize_qanon(self, text):
text = text.strip()
# اصلاح خطاهای متن در کد خط
text = text.replace("\\n", "\n")
text = text.replace("\\r", "\r")
text = re.sub(r"(\r\n)+", "\n", text)
text = text.replace("\r", "\n")
# یکسان سازی اختلاف حروف کیبوردهای مختلف - کدهای مختلف ولی نمایش یکسان
text = self.replace_alphabets(text)
#فاصله های تکراری و خطوط خالی تکراری را یکی می کند
text = re.sub(r"( )+", " ", text)
text = re.sub(r"(\n)+", "\n", text)
# اعداد چسبیده به کلمات را با یک فاصله جدا می کند
text = self.word_digit_correction(text)
# نرمال کردن حروف اختلافی عربی و فارسی
text = text.replace("ي", "ی")
text = text.replace("ك", "ک")
return text
def normalize_qanon_test(self, text):
text = self.space_correction(text)
text = self.heha_correction(text)
return text
def normalize_text(self, text):
text = text.strip()
# اصلاح خطاهای متن در کد خط
if self.options.get("errorLine", False):
text = text.replace("\\n", "\n")
text = text.replace("\\r", "\r")
text = re.sub(r"(\r\n)+", "\n", text)
text = text.replace("\r", "\n")
# یکسان سازی اختلاف حروف کیبوردهای مختلف - کدهای مختلف ولی نمایش یکسان
if self.options.get("alphabetsNormal", False):
text = self.replace_alphabets(text)
# حذف خطوط و فاصله‌های خالی
if self.options.get("emptylinesNormal", False):
text = re.sub(r"( )+", " ", text)
text = re.sub(r"(\n)+", "\n", text)
# نرمال کردن حروف اختلافی عربی و فارسی
if self.options.get("charArNormal", True):
text = text.replace("ي", "ی")
text = text.replace("ك", "ک")
# پرش از اختلافات همزه‌ا
if self.options.get("hamzehNormal", False):
text = re.sub(r"ئ|ﺋ", "ی", text)
text = re.sub(r"ؤ|ﺅ", "و", text)
text = re.sub(r"ﺔ|ۀ|ة", "ه", text)
text = re.sub(r"إ|أ", "ا", text)
# اصلاح فاصله‌ها در ترکیب کلمات
if self.options.get("spaceCorrection", False):
text = self.space_correction(text)
# حذف خطوط اضافی اول و انتهای متن
if self.options.get("trimLine", False):
text = text.strip()
return text
def replace_alphabets(self, text):
text = re.sub(r"\u00AD|\u00AC", "\u200C", text) # نیم اسپیس خاص
text = re.sub(r"(\u002C)+", "\u200C", text) # نیم اسپیس تکراری
text = re.sub(r"ﺁ|آ", "آ", text)
text = re.sub(r"ﺎ|ٱ|ﺍ", "ا", text)
text = re.sub(r"ٲ|أ|ﺄ|ﺃ", "أ", text)
text = re.sub(r"ﺈ|ﺇ", "إ", text)
text = re.sub(r"ﺐ|ﺏ|ﺑ|ﺒ", "ب", text)
text = re.sub(r"ﭖ|ﭗ|ﭙ|ﭘ", "پ", text)
text = re.sub(r"ﭡ|ٺ|ٹ|ﭞ|ٿ|ټ|ﺕ|ﺗ|ﺖ|ﺘ", "ت", text)
text = re.sub(r"ﺙ|ﺛ|ﺚ|ﺜ", "ث", text)
text = re.sub(r"ﺝ|ڃ|ﺠ|ﺟ", "ج", text)
text = re.sub(r"ڃ|ﭽ|ﭼ", "چ", text)
text = re.sub(r"ﺢ|ﺤ|څ|ځ|ﺣ", "ح", text)
text = re.sub(r"ﺥ|ﺦ|ﺨ|ﺧ", "خ", text)
text = re.sub(r"ڏ|ډ|ﺪ|ﺩ", "د", text)
text = re.sub(r"ﺫ|ﺬ|ذ", "ذ", text)
text = re.sub(r"ڙ|ڗ|ڒ|ڑ|ڕ|ﺭ|ﺮ", "ر", text)
text = re.sub(r"ﺰ|ﺯ", "ز", text)
text = re.sub(r"ﮊ", "ژ", text)
text = re.sub(r"ݭ|ݜ|ﺱ|ﺲ|ښ|ﺴ|ﺳ", "س", text)
text = re.sub(r"ﺵ|ﺶ|ﺸ|ﺷ", "ش", text)
text = re.sub(r"ﺺ|ﺼ|ﺻ|ﺹ", "ص", text)
text = re.sub(r"ﺽ|ﺾ|ﺿ|ﻀ", "ض", text)
text = re.sub(r"ﻁ|ﻂ|ﻃ|ﻄ", "ط", text)
text = re.sub(r"ﻆ|ﻇ|ﻈ", "ظ", text)
text = re.sub(r"ڠ|ﻉ|ﻊ|ﻋ|ﻌ", "ع", text)
text = re.sub(r"ﻎ|ۼ|ﻍ|ﻐ|ﻏ", "غ", text)
text = re.sub(r"ﻒ|ﻑ|ﻔ|ﻓ", "ف", text)
text = re.sub(r"ﻕ|ڤ|ﻖ|ﻗ|ﻘ", "ق", text)
text = re.sub(r"ڭ|ﻚ|ﮎ|ﻜ|ﮏ|ګ|ﻛ|ﮑ|ﮐ|ڪ|ك", "ک", text)
text = re.sub(r"ﮚ|ﮒ|ﮓ|ﮕ|ﮔ", "گ", text)
text = re.sub(r"ﻝ|ﻞ|ﻠ|ڵ|ﻟ", "ل", text)
text = re.sub(r"ﻵ|ﻶ|ﻷ|ﻸ|ﻹ|ﻺ|ﻻ|ﻼ", "لا", text)
text = re.sub(r"ﻡ|ﻤ|ﻢ|ﻣ", "م", text)
text = re.sub(r"ڼ|ﻦ|ﻥ|ﻨ|ﻧ", "ن", text)
text = re.sub(r"ވ|ﯙ|ۈ|ۋ|ﺆ|ۊ|ۇ|ۏ|ۅ|ۉ|ﻭ|ﻮ|ؤ", "و", text)
text = re.sub(r"ﻬ|ھ|ﻩ|ﻫ|ﻪ|ە|ہ", "ه", text)
text = re.sub(r"ﭛ|ﻯ|ۍ|ﻰ|ﻱ|ﻲ|ں|ﻳ|ﻴ|ﯼ|ې|ﯽ|ﯾ|ﯿ|ێ|ے|ى|ي", "ی", text)
text = re.sub(r"¬", "‌", text)
text = re.sub(r"•|·|●|·|・|∙|。|ⴰ", ".", text)
text = re.sub(r",|٬|٫|‚|،", "،", text)
text = re.sub(r"ʕ", "؟", text)
text = re.sub(r"”|“", "\"", text)
text = re.sub(r"۰|٠", "0", text)
text = re.sub(r"۱|١", "1", text)
text = re.sub(r"۲|٢", "2", text)
text = re.sub(r"۳|٣", "3", text)
text = re.sub(r"۴|٤", "4", text)
text = re.sub(r"۵", "5", text)
text = re.sub(r"۶|٦", "6", text)
text = re.sub(r"۷|٧", "7", text)
text = re.sub(r"۸|٨", "8", text)
text = re.sub(r"۹|٩", "9", text)
text = re.sub(r"²", "2", text)
text = re.sub(r"|ِ|ُ|َ|ٍ|ٌ|ً|", "", text)
text = re.sub(r"ـ", "", text) # حذف حروف کشیده
return text
def space_correction(self, text):
text = re.sub(r"^(بی|می|نمی)( )", r"\1‌", text)
text = re.sub(r"( )(می|نمی|بی)( )", r"\1\2‌", text)
text = re.sub(
r"( )(هایی|ها|های|ایی|هایم|هایت|هایش|هایمان|هایتان|هایشان|ات|ان|ین|انی|بان|ام|ای|یم|ید|اید|اند|بودم|بودی|بود|بودیم|بودید|بودند|ست)( )",
r"‌\2\3",
text,
)
# text = re.sub(r"( )(شده|نشده)( )", r"‌\2‌", text)
text = re.sub(
r"( )(طلبان|طلب|گرایی|گرایان|شناس|شناسی|گذاری|گذار|گذاران|شناسان|گیری|پذیری|بندی|آوری|سازی|بندی|کننده|کنندگان|گیری|پرداز|پردازی|پردازان|آمیز|سنجی|ریزی|داری|دهنده|آمیز|پذیری|پذیر|پذیران|گر|ریز|ریزی|رسانی|یاب|یابی|گانه|گانه‌ای|انگاری|گا|بند|رسانی|دهندگان|دار)( )",
r"‌\2\3",
text,
)
return text
# اعداد چسبیده به کلمات را با یک فاصله جدا می کند
def word_digit_correction(self, text):
text = re.sub(r"(\200C)(\d+)", r" \2", text)
text = re.sub(r"(\d+)(\200C)", r"\1 ", text)
# text = re.sub(r"(\w+)(\d+)", r"\1 \2", text)
# text = re.sub(r"(\d+)(\w+)", r"\1 \2", text)
# words = re.split(r"[\t\n\r\.\"«»\)\(\]\[,;،؛ \-!?:]+", text)
text = re.sub(r"([^\d \/\\]+?)(\d)", r"\1 \2", text)
text = re.sub(r"(\d+)([^\d \/\\]+?)", r"\1 \2", text)
#ر5ر135
# text = re.sub(r"((\d+)ر)+\d", r"\1 \2", text)
return text
def heha_correction(self, text):
text = re.sub(r"(ه)(ها )", r"\1‌\2", text)
text = re.sub(r"(ه)(های )", r"\1‌\2", text)
text = re.sub(r"(ی)(ها )", r"\1‌\2", text)
text = re.sub(r"(ی)(های )", r"\1‌\2", text)
return text
# # تست برنامه
# options = {
# "charArNormal": True, # نرمال کردن حروف عربی و فارسی
# "errorLine": True, # اصلاح خطاهای مربوط به خطوط و کاراکترها
# "alphabetsNormal": True, # نرمال‌سازی حروف
# "emptylinesNormal": True, # حذف فاصله‌های اضافی
# "hamzehNormal": True, # اصلاح همزه‌ها
# "spaceCorrection": True, # اصلاح فاصله‌ها در ترکیب کلمات
# "trimLine": True # حذف فضای خالی اضافی در ابتدا و انتهای متن
# }
# normalizer = TextNormalizer(options)
# text = """
# سلام -- ـ ـ خوبی
# دادی ییی بی داد
# آیا ١٢۳۴۴۵۶۷٨ ، دادی یا ندادی؟
# ـ تغییرات جدید ٠۹۸٧٦٥٤٣٢١
# درباره‌ی ﻻ|ﻻ یا مثلا ﻷ صحبت کنیم.
# """
# normalized_text = normalizer.normalize_text(text)
# print(normalized_text)