329 lines
14 KiB
Python
329 lines
14 KiB
Python
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)
|