common -> app.common.

This commit is contained in:
hsafaei
2025-09-18 14:32:19 +03:30
parent a507fff651
commit b4d5671809
83 changed files with 192 additions and 163 deletions
+2
View File
@@ -0,0 +1,2 @@
+94
View File
@@ -0,0 +1,94 @@
import requests
import json
import os
from app.common.config_base import *
from app.common.general_functions import *
cursor, cnxn = create_cursor()
# -----------------------------------------------------------------
ADD_LIST_ROUTE = "project/add"
ADD_ITEM_ROUTE = "subject/add"
TITLE = "استانها و شهرهای ایران"
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 = './data/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 )
+71
View File
@@ -0,0 +1,71 @@
import os
import re
import random
from dotenv import load_dotenv
from app.common.text_normalizer import TextNormalizer
# from general import *
from app.common.general_functions import *
from app.common.elastic_helper import ElasticHelper
from create_relation_tags import *
from temp_refactor_gn_dataset import *
load_dotenv(dotenv_path='config.env')
host=os.getenv('HOST_160')
password=os.getenv('HOST_160_PASS')
print(host)
# print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
def import_synonym_virstaran_min(elastic, file_input, index_name_o):
lines = []
with open(file_input, 'r', encoding='utf-8') as file:
# نوشتن خطا در فایل
lines = file.readlines()
row = 0
for item in lines :
item = item.strip()
if not item :
continue
words = []
for w in item.split(','):
w = re.sub(r"\uFEFF|\u00AD|\u00AC", "\u200C", w)
w = w.strip("\u200C").strip()
words.append(w)
if len(words) == 0 :
continue
row = row + 1
if ( row % 10 ) == 0 :
print( 'row = ', row, '/', len(lines))
#eid = 'syn_vr_' + random.randrange(10000)
eid = 'syn_vr_' + str(10000+row)
data = {
'id' : eid,
"main_type": "synonym",
"ref_key": "virastaran",
'words' : words
}
try:
resp = elastic.update_index_doc(False, index_name_o, eid, data)
except Exception as e:
save_error(id, e)
elastic.createIndex("gn_synonym", '', "gn_synonym" )
file_excel = './data/fa_virastarn_min.txt'
import_synonym_virstaran_min(elastic, file_excel, "gn_synonym" )
+402
View File
@@ -0,0 +1,402 @@
[
{
"title": "آب",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 1,
"listtype": 0,
"id": 8007
},
{
"title": "آمار، برنامه و بودجه",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 2,
"listtype": 0,
"id": 8008
},
{
"title": "آموزش و پرورش",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 3,
"listtype": 0,
"id": 8009
},
{
"title": "آموزش عالی، پژوهش و فناوری",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 4,
"listtype": 0,
"id": 8010
},
{
"title": "آیین دادرسی مدنی",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 5,
"listtype": 0,
"id": 8011
},
{
"title": "آیین دادرسی اداری",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 6,
"listtype": 0,
"id": 8012
},
{
"title": "آیین دادرسی کیفری",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 7,
"listtype": 0,
"id": 8013
},
{
"title": "اداری و استخدامی",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 8,
"listtype": 0,
"id": 8014
},
{
"title": "اموال و معاملات دولتی",
"projectid": 8,
"meta": "{\"description\":\"(با زیرفصل اجرای سیاستهای کلی اصل44)\"}",
"otherid": 9,
"listtype": 0,
"id": 8015
},
{
"title": "اطلاعات، امنیت و نظامی، انتظامی",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 10,
"listtype": 0,
"id": 8016
},
{
"title": "امور زیربنایی",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 11,
"listtype": 0,
"id": 8017
},
{
"title": "انتخابات",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 12,
"listtype": 0,
"id": 8018
},
{
"title": "اوقاف، اماکن دینی و امور مذهبی",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 13,
"listtype": 0,
"id": 8019
},
{
"title": "ایثارگران",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 14,
"listtype": 0,
"id": 8020
},
{
"title": "بانکداری",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 15,
"listtype": 0,
"id": 8021
},
{
"title": "برق و انرژی‌های نوین",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 16,
"listtype": 0,
"id": 8022
},
{
"title": "بیمه",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 17,
"listtype": 0,
"id": 8023
},
{
"title": "پولی و مالی",
"projectid": 8,
"meta": "{\"description\":\" (با زیرفصل‌های سرمایه گذاری داخلی وخارجی ـ بازار سرمایه)\"}",
"otherid": 18,
"listtype": 0,
"id": 8024
},
{
"title": "تأمین اجتماعی",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 19,
"listtype": 0,
"id": 8025
},
{
"title": "تجارت",
"projectid": 8,
"meta": "{\"description\":\"(اعم از تجارت داخلی و خارجی)\"}",
"otherid": 20,
"listtype": 0,
"id": 8026
},
{
"title": "تشکل‌های مدنی و احزاب",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 21,
"listtype": 0,
"id": 8027
},
{
"title": "تشکیلات و امور اداری قوه قضائیه",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 22,
"listtype": 0,
"id": 8028
},
{
"title": "تعاون",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 23,
"listtype": 0,
"id": 8029
},
{
"title": "تعزیرات حکومتی",
"projectid": 8,
"meta": "{\"description\":\"(مجازات‌های غیرقضایی)\"}",
"otherid": 24,
"listtype": 0,
"id": 8030
},
{
"title": "تقسیمات کشوری و مدیریت محلی",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 25,
"listtype": 0,
"id": 8031
},
{
"title": "ثبت اسناد و املاک",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 26,
"listtype": 0,
"id": 8032
},
{
"title": "حمل و نقل",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 27,
"listtype": 0,
"id": 8033
},
{
"title": "خانواده",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 28,
"listtype": 0,
"id": 8034
},
{
"title": "رسانه",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 29,
"listtype": 0,
"id": 8035
},
{
"title": "سلامت",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 30,
"listtype": 0,
"id": 8036
},
{
"title": "صنعت",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 31,
"listtype": 0,
"id": 8037
},
{
"title": "ارتباطات و فناوری اطلاعات",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 32,
"listtype": 0,
"id": 8038
},
{
"title": "فرهنگ و هنر",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 33,
"listtype": 0,
"id": 8039
},
{
"title": "کار",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 34,
"listtype": 0,
"id": 8040
},
{
"title": "کشاورزی و دامپروری",
"projectid": 8,
"meta": "{\"description\":\"(منابع طبیعی)\"}",
"otherid": 35,
"listtype": 0,
"id": 8041
},
{
"title": "کیفری",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 36,
"listtype": 0,
"id": 8042
},
{
"title": "مالکیت فکری",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 37,
"listtype": 0,
"id": 8043
},
{
"title": "مالیات",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 38,
"listtype": 0,
"id": 8044
},
{
"title": "محاسبات عمومی",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 39,
"listtype": 0,
"id": 8045
},
{
"title": "محیط زیست",
"projectid": 8,
"meta": "{\"description\":\"(اراضی مربوط به محیط زیست (خاک) زیر این کد قرار میگیرد)\"}",
"otherid": 40,
"listtype": 0,
"id": 8046
},
{
"title": "مدنی و امور حسبی",
"projectid": 8,
"meta": "{\"description\":\" (ثبت احوال،تابعیت واتباع خارجی از سرفصل‌های این کد است)\"}",
"otherid": 41,
"listtype": 0,
"id": 8047
},
{
"title": "مسکن و شهرسازی",
"projectid": 8,
"meta": "{\"description\":\" (اراضی مربوط به مسکن و شهرسازی زیر این کد قرار میگیرد)\"}",
"otherid": 42,
"listtype": 0,
"id": 8048
},
{
"title": "مصرف",
"projectid": 8,
"meta": "{\"description\":\" (با زیرفصل قانون سازمان ملی استاندارد، سایر قوانین و مقررات استاندارد در زیر هر یک از کدهای مربوطه قرار می گیرد)\"}",
"otherid": 43,
"listtype": 0,
"id": 8049
},
{
"title": "معدن",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 44,
"listtype": 0,
"id": 8050
},
{
"title": "مناطق آزاد و ویژه اقتصادی",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 45,
"listtype": 0,
"id": 8051
},
{
"title": "میراث فرهنگی، گردشگری و صنایع دستی",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 46,
"listtype": 0,
"id": 8052
},
{
"title": "نظام قانونگذاری",
"projectid": 8,
"meta": "{\"description\":\" (که شامل سه سرفصل مجلس شورای اسلامی متشکل از (تقنین و نظارت)، شورای نگهبان، مجمع تشخیص مصلحت نظام)\"}",
"otherid": 47,
"listtype": 0,
"id": 8053
},
{
"title": "نظامهای صنفی و حرفهای",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 48,
"listtype": 0,
"id": 8054
},
{
"title": "نفت و گاز",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 49,
"listtype": 0,
"id": 8055
},
{
"title": "ورزش",
"projectid": 8,
"meta": "{\"description\":\"\"}",
"otherid": 50,
"listtype": 0,
"id": 8056
}
]
+161
View File
@@ -0,0 +1,161 @@
لایحه قانونی راجع به آئین نامه اجرائی دفتر معاملات مسکن و تغییرنام=qq118694
منتفی بودن لایحه قانونی تشکیل انجمنهای ده و اصلاح امور اجتماعی و عمرانی دهات=qq120753
خریداری کلیه اراضی گودهای کوره پزخانه های سابق و فعلی واقع در جنوب تهران بین خیابانهای شوش و حد جنوبی جدید تهران و جاده آرامگاه و خیابان سپهبد رزم آرا توسط شهرداری تهرات برای رفع نیازمندی های عمومی شهر=0
قانون راجع باجازه تحصیل مبلغ هفتاد و دو میلیون دلار وام از بانک بین‌المللی ترمیم و توسعه=qq113980
قانون راجع به احداث و توسعه معابر و خیابان ها=qq112239
قانون بودجه 1385 کل کشور=qq87759
قانون بودجه سال 1369کل کشور=qq84519
قانون اصلاح مواد 4 و 6 قانون تغییر نام وزارت آبادانی و مسکن بوزارت مسکن و شهرسازی و تعیین وظایف آن=qq86848
ائین‌نامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28ر12ر1345=qq115135
قانون اعطای امتیاز نفط بشرکت نفط انگیس[انگلیس] و ایران محدود=qq85083
آئین نامه اجرائی لایحه قانونی اصلاح لایحه قانونی واگذاری و احیاء اراضی در حکومت جمهوری اسلامی ایران مصوب 21/1/59=qq83760
لایحه قانونی ملی کردن سهام شرکت سهامی انبارهای عمومی=qq83938
لایحه قانونی الحاق سه تبصره به مواد 7 و 11 و 14 قانون تشکیل دادگاههای عمومی و یک تبصره بماده 17 قانون اصلاح قانون منع کشت خشخاش مصوب سال 1338 و اصلاح ماده 46 قانون اصول تشکیلات دادگستری=qq87062
لایحه قانونی مالکیت و بهره برداری از اراضی واقع در آبخورسد دز و الغاء قردادهای کشت و صنعت=qq87024
لایحه قانونی اصلاح قانون مربوط بسرسید سفته ها وتضمین نامه ها وبروات و چکها=qq86971
تصمیم قانونی راجع به آئین نامه جلوگیری از آلودگی هوا=0
قانون قراداد تشویق وحمایت متقابل سرمایه گذاری بین دولت ایران وجمهوری فدرال آلمان=qq85065
قانون اجازه تحصیل مبلغ بیست و پنج میلیون دلار وام از صندوق وامهای عمرانی امریکا=qq85231
رد لایحه راجع به تشکیل اداره دعاوی وزارت دارائی که در کمیسیون مشترک مجلسین رد شده است=qq114031
آئین نامه اجرائی ماده 18 قانون اصلاح قانون مالیات بر درآمد=qq113975
قانون مربوط بالحاق یک تبصره بماده 370 قانون امور حسبی و یک تبصره بماده 56 قانون شریع(تسریع) محاکمات=qq113534
لایحه قانونی تصویب قرارداد بین المللی ارتباطات دوره منعقده در بوئنوس آیرس در سال 1331=qq113460
قانون مربوط بموافقت‌نامه راجع به سرویسهای حمل و نقل بازرگانی منعقده بین دولت شاهنشاهی ایران و دولت هلند=qq114554
تصمیم متخذه کمیسیون مشترک در مورد هزینه های دادگستری و ثبت و حق تمبر پروانه=qq113344
قانون تصویب عهدنامه تسویه مسالمت آمیز اختلافات بین دولت شاهنشاهی ایران و دولت پادشاهی عراق=qq85019
قانون راجع برشد متعاملین=qq112444
قانون اصلاح مواد 13ر 41ر 43ر70ر111ر117قانون ثبت اسناد و املاک=qq112144
قانون اجازه مبادله عهدنامه مودت منعقده بین دولتین ایران و افغانستان=qq84876
قانون اصلاح جداول شماره (4) و (8) قانون برنامه چهارم توسعه اقتصادی، اجتماعی و فرهنگی جمهوری اسلامی ایران و قانون بودجه سال 1386 کل کشور به منظور تآمین کسری اعتبار گاز رسانی به روستاهای کشور=qq36662
قانون الحاق دولت جمهوری اسلامی ایران به پروتکل 1992جهت اصلاح کنوانسیون بین المللی مسوولیت مدنی ناشی ازخسارت آلودگی نفتی ( 1969 ) و پروتکل 1992 جهت اصلاح کنوانسیون تاسیس یک صندوق بین المللی برای جبران خسارت آلودگی نفتی (1971)=qq116450
قانون مربوط بقرداد فروش و خرید گاز طبیعی بین شرکت ملی ایران وشرکت متالیمکس (METALIMEX)چکسلواکی=qq86609
قانون مربوط بقرداد فروش و خریدگازطبیعی بین شرکت ملی گاز ایران و شرکتهای روهرگاز Ruhrgaz گاز دوفرانس (Gaz de France)و نفت معدنی اطریش Oesterreichische Mineraloel Verwaltung Aktiengesellschaft=qq86601
اجازه اعمال تغییرات در بودجه به وزارت دارائی به منظور تأمین کسری اعتبار بعضی از هزینه ها=qq235140
اجازه پرداخت ده میلیون ریال جهت مبارزه با بیماری وبا در اختیار وزارت بهداری=qq289936
اجازه پرداخت مبلغ یک میلیون و یکصد و بیست و پنج هزار ریال به وزارت کشاورزی جهت تأمین حقوق و هزینه های ضروری خرداد ماه سال 1341 سازمان اصلاحات ارضی=qq184583
اجازه پرداخت نود و پنج میلیون ریال در حدود وصولی های درآمد کشور=qq289936
اصلاح آئین نامه طرز تشخیص و وصول مالیات کسبه و پیشه‌وران=qq164518
اصلاح بودجه تفضیلی سال 1340 و کسر مبلغ چهل میلیون ریال از بعضی مواد و افزودن به مواد دیگر=qq188606
اصلاح بودجه سال 2536 (1356) شهربانی کشور=qq87031
اصلاحیه قانون بودجه سال 1397 کل کشور=qq260944
اصلاحیه قانون حداکثر استفاده از توان تولیدی و خدماتی در تأمین نیازهای کشور و تقویت آنها در امر صادرات و اصلاح ماده (104) قانون مالیاتهای مستقیم=qq192211
اصلاحیه ماده 25 آیین نامه معاملات دولتی=qq118088
الزام دولت به تقدیم لایحه توسط مجلس شورای اسلامی در خصوص برنامه زمان بندی ممنوعیت تدریجی کشت توتون، تولید و توزیع انواع سیگار و طرح انحلال شورای عالی پزشکی اعزام بیماران به خارج از کشور=0
ائین‌نامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28 ر12 ر1345=qq115135
آیین نامه اجرای[اجرایی] استفاده از اتومبیل های دولتی موضوع تبصره 68 قانون بودجه سال 1344 کل کشور=qq114484
آئین نامه اجرائی لایحه قانونی اصلاح لایحه قانونی واگذاری و احیاء اراضی در حکومت جمهوری اسلامی ایران مصوب 21/1/59=qq83760
آئین نامه اجرائی ماده 18 قانون اصلاح قانون مالیات بر درآمد=qq113975
بودجه سازمان غله کشور در ششماهه دوم سال 1348 از محل درامد عمومی=qq289088
بودجه سال 1332 سازمان برنامه (مصوب کمیسیون برنامه)=qq113255
تصمیم قانونی راجع به آئین نامه جلوگیری از آلودگی هوا=qq120748
تصمیم کمیسیون بودجه در خصوص اجازه پرداخت حق بیمه اشیاء عتیقه موزه ایران باستان=qq289520
تصمیم کمیسیون بودجه درخصوص اصلاح اعتبار برنامه ها و اعتبار مواد هزینه و فصول بودجه سال 1345=qq289020
تصمیم متخده کمیسیون بودجه مجلس شورای ملی دائر باصلاح بودجه سال 1348 وزارت کار و امور اجتماعی=qq289083
تصمیم متخذه کمیسیون بودجه دائر به اجازه خرید یکدستگاه جیپ استیشن جهت وزارت صنایع و معادن [صنعت، معدن و تجارت]=qq113965
تصمیم متخذه کمیسیون مشترک دارائی برنامه مجلسین دائر باصلاح تبصره 2 آئین نامه اجرایی قسمت اول تبصره 29 قانون بودجه سال 1344 کل کشور و حذف=qq114901
تصمیم متخذه کمیسیون مشترک در مورد هزینه های دادگستری و ثبت و حق تمبر پروانه=qq113344
تصویب نامه راجع به تمدید تعهد اعتبار وزارت بهداری=qq184596
تصویب نامه شماره 3588 ـ5/3/1342 دولت راجع به‌ وام شماره 017/ه/265 از سازمان عمران بین المللی آمریکا برای تأمین هزینه پروژه‌های بندر عباس=qq121069
تصویب نامه شماره 3626 ـ6/3/1342 راجع به وام شماره 016/ه/265 از سازمان عمران بین المللی آمریکا برای تأمین هزینه پروژه‌های اصلی برق ایران=qq184693
تصویب نامه قانونی لغو معافیت ورود و صدور اشیاء عتیقه و آثار فرهنگی هنری اصیل=qq118279
تصویبنامه شماره 12/26202 مورخ 1339/9/26 هیأت وزیران راجع باجازه پرداخت مبلغ ده میلیون ریال از محل ‌درآمد عمومی کشور در سال 1339 بوزارت بهداری جهت مبارزه با وبا=qq121087
تصویبنامه شماره 20942 مورخ 1339/7/26 هیأت وزیران راجع بپرداخت مبلغ ده میلیون ریال از درآمد عمومی‌ سال 1339 بوزارت بهداری برای جلوگیری از مرض وبا ‌=qq121087
تصویبنامه شماره 22842 مورخ 22 ر8ر1339 هیأت وزیران راجع به اجازه مصرف مبلغ چهار میلیون ریال از محل مازاد ‌درآمد اختصاصی بنگاه دامپروری برای توسعه و پیشرفت امور موسسه دامپروری=qq121075
‌تصویبنامه شماره 9878 مورخ 26 ر3ر1339 هیأت وزیران راجع به اجازه پرداخت مبلغ هفتصد و پنجاه میلیون ریال وام‌ به سازمان برنامه از محل درآمدهای دولت در سال 1339 ‌=qq121055
دادن اختیار به وزارت کشاورزی در خصوص معاملات مربوط به دهات ششدانک=0
رد تصویب نامه شماره 3588 ـ5/3/1342 دولت راجع به‌وام شماره 017/ه/265 از سازمان عمران بین المللی آمریکا برای تأمین هزینه پروژه‌های بندر عباس=qq165841
رد تصویب نامه شماره 3626 - 1342/3/6 راجع به وام شماره 016/ه/265 از سازمان عمران بین المللی آمریکا برای تأمین هزینه پروژه‌های اصلی برق ایران=qq184693
رد تصویب نامه شماره 8028/ت ـ 25/3/1340 دولت راجع به تحصیل اعتبار از بانک صادرات و واردات آمریکا جهت خرید کالاهای تولیدی از آمریکا=qq165859
رد لایحه راجع به تشکیل اداره دعاوی وزارت دارائی که در کمیسیون مشترک مجلسین رد شده است=qq114031
قانون اجازه استقراض دو ملیون ریال از بانک ملی برای شهرداری رشت=qq112541
قانون اجازه تجدید قرارداد استخدامی آقای ویلهلم مایر تبعه دولت آلمان=qq112556
قانون اجازه تحصیل مبلغ بیست و پنج میلیون دلار وام از صندوق وامهای عمرانی امریکا=qq85231
قانون اجازه ساختمان راه‌آهن مابین خورموسی و بندر محمره و بندر جز=qq115835
قانون اجازه مبادله عهدنامه مودت منعقده بین دولتین ایران و افغانستان=qq84876
قانون اجازه مبادله قراداد بازرگانی ایران و آلمان=qq114422
قانون استخدام جانبازان ،اسراوافرادخانواده های شهدا،جانبازان ازکارافتاده ،اسراومفقودالاثرهای انقلاب اسلامی وجنگ تحمیلی وهمچنین افرادی که حداقل 9 ماه متوالی یایکسال متناوب داوطلبانه درجبهه خدمت نموده اند=qq83370
قانون استخدام نیروهای مسلح شاهنشاهی ایران [قانون ارتش جمهوری اسلامی ایران]=qq113595
قانون اصلاح بند (و) ماده (1) قانون برنامه چهارم توسعه اقتصادی‘ اجتماعی و فرهنگی جمهوری اسلامی ایران و جداول مربوط و اختصاص معادل تا دویست و پنجاه میلیون (250/000/000) دلار برای ماهواره سازمان صدا و سیمای جمهوری اسلامی ایران=qq121771
قانون اصلاح بند«ج»ماده 15 قانون استخدام نیروهای مسلح شاهنشاهی=qq111882
قانون اصلاح پاره ای از مقررات مربوط به پایه حقوق اعضای رسمی هیات علمی ( آموزشی و پژوهشی ) شاغل و بازنشسته دانشگاهها و موسسات آموزش عالی=qq120722
قانون اصلاح تبصره یک مصوب 1364/06/28 ماده 9 قانون روابط موجر و مستاجر مصوب 1362/02/13 مجلس شورای اسلامی=qq111747
قانون اصلاح جداول شماره (4) و (8) قانون برنامه چهارم توسعه اقتصادی، اجتماعی و فرهنگی جمهوری اسلامی ایران و قانون بودجه سال 1386 کل کشور به منظور تآمین کسری اعتبار گاز رسانی به روستاهای کشور=qq36662
قانون اصلاح فصل دوم و پنجم قانون ترفیعات ارتش شاهنشاهی=qq112640
قانون اصلاح قانون طبقه بندی مشاغل و برقراری کمک هزینه مسکن کارگری مصوب 1359/01/27 شورای انقلاب جمهوری اسلامی ایران=qq83726
قانون اصلاح قانون معادن مصوب 62/3/1 [1362] مجلس شورای اسلامی=qq85625
قانون اصلاح قانون معافیت یک نفر از فرزندان خانواده های شهداء، معلولین، اسرا، مفقودالاثرها از خدمت نظام وظیفه عمومی مصوب 1366=qq84464
قانون اصلاح قانون نحوه جبران زحمات و خسارات کارکنان سازمان حفاظت محیط زیست در ارتباط جرائم زیست محیطی=qq87760
قانون اصلاح قانون نظام هماهنگ پرداخت کارکنان دولت مصوب 1370/6/13=qq83577
قانون اصلاح ماده (56) قانون الحاق موادی به قانون تنظیم بخشی از مقررات مالی دولت =qq121967
قانون اصلاح ماده 113 قانون اصلاح قانون استخدام نیروهای مسلح شاهنشاهی=qq86913
قانون اصلاح ماده 4 قانون شمول قانون استخدام نیروهای مسلح شاهنشاهی بافسران و درجه داران و افراد شهربانی کل کشور=qq115007
قانون اصلاح ماده 70 قانون استخدام نیروهای مسلح شاهنشاهی=qq237979
قانون اصلاح ماده 85 قانون استخدام نیروهای مسلح شاهنشاهی=qq114509
قانون اصلاح مواد 13 ر 41 ر 43 ر70 ر111 ر117 قانون ثبت اسناد و املاک=qq112144
قانون اصلاح مواد 13ر 41ر 43ر70ر111ر117قانون ثبت اسناد و املاک=qq112144
قانون اصلاح موادی از قانون برنامه چهارم توسعه اقتصادی، اجتماعی و فرهنگی جمهوری اسلامی ایران و اجراء سیاستهای کلی اصل چهل و چهارم (44) قانون اساسی [قانون اجرای سیاستهای کلی اصل چهل و چهارم (44) قانون اساسی]=qq178058
قانون اصلاح موادی از قانون شکار و صید - مصوب 1346 – و اصلاحیه بعدی آن=qq83519
قانون الحاق تبصره (6) به ماده (31) قانون خدمت وظیفه عمومی=qq86843
قانون الحاق دو تبصره به ماده (617) قانون مجازات اسلامی (کتاب پنجم ـ تعزیرات و مجازات های بازدارنده)=qq260019
قانون الحاق دولت جمهوری اسلامی ایران به پروتکل 1992جهت اصلاح کنوانسیون بین المللی مسوولیت مدنی ناشی ازخسارت آلودگی نفتی ( 1969 ) و پروتکل 1992 جهت اصلاح کنوانسیون تاسیس یک صندوق بین المللی برای جبران خسارت آلودگی نفتی (1971)=qq116450
قانون الحاق موادی به قانون نحوه حفظ آثار و یاد حضرت امام خمینی رضوان ا...تعالی علیه=0
قانون الحاق یک بند بماده 15 قانون استخدام نیروهای مسلح شاهنشاهی=qq86939
قانون الحاق یک بند به عنوان بند ج و دو تبصره به ماده 2 قانون روابط موجر و مستأجرمصوب 1362=qq83421
قانون الحاق یک تبصره بعنوان تبصره یک به ماده 9 قانون روابط موجر ومستاجر مصوب 1362/2/13=qq111600
قانون الحاق یک تبصره به ماده (182) قانون ایین نامه داخلی مجلس شورای اسلامی=0
قانون الحاق یک تبصره به ماده 40 قانون نظام پزشکی جمهوری اسلامی ایران=qq185059
قانون برقراری حقوق وظیفه یا مستمری بازماندگان آن دسته از مهاجران وکسانی که به مناطق جنگی مراجعت نموده و بعلت برخورد با مواد منفجره معلول یا فوت میشوند=qq83692
قانون تجدید کنترات دکتر کراندل تبعه دولت فرانسه برای ریاست قسمت فنی و اداری موسسه پاستور به مدت سه سال=qq289936
قانون تشکیل میراث فرهنگی و گردشگری=qq86061
قانون تشکیلات و آیین دادرسی دیوان عدالت اداری=qq302246
قانون تصویب عهدنامه تسویه مسالمت آمیز اختلافات بین دولت شاهنشاهی ایران و دولت پادشاهی عراق=qq85019
قانون تفسیر جزء (1 ـ 5) قوانین بودجه سالهای 1391 و 1392 کل کشور=qq220596
قانون تفسیر قانون الحاق یک ماده به قانون تعیین تکلیف استخدامی معلمین حق التدریسی و آموزشیاران نهضت سواد آموزی مصوب 13 /6 /1397=qq286515
قانون تفسیرتبصره 2 ماده 22 قانون تشکیل سازمان نظام پزشکی جمهوری اسلامی ایران=qq83795
قانون حدود و قصاص و مقررات آن از ماده 196 تا 218=qq87694
قانون راجع باجازه پرداخت تفاوت اضافات سال 34 کارمندان دون پایه و خدمتگذاران جزء وزارتخانه ها و ادارات دولتی=qq113724
قانون راجع باصلاح تبصره ماده 3 قانون استخدام پرستار و ماما و کارمند فنی مصوب 12 ر12 ر38=qq114773
قانون راجع برشد متعاملین=qq112444
قانون راجع بقرارداد فرهنگی بین دولت شاهنشاهی ایران و دولت متحده بریتانیای کبیر و ایرلند شمالی=qq85085
قانون راجع بلغو گذرنامه برای مسافرت عراق و مرز سوریه=qq114552
قانون راجع به چرانیدن دام در منابع طبیعی=qq177315
قانون راجع به قرداد منعقده بین دفتربرنامه ریزی و هدایت ترابری وزارت راه و ترابری جمهوری اسلامی ایران و اتحادیه کل انتفاعی و بازرگانی (سایوزترانزیت) شوروی درباره ترانزیت کالاهای تجاری با پروتکل و پیوست های چهارگانه=qq84998
قانون راجع به موسسه اصلاح و تهیه نهال و بذر=qq113991
قانون سرباز گیری=0
قانون شمول تبصره 3 قانون نحوه بازنشستگی جانبازان انقلاب اسلامی و جنگ تحمیلی و معلولان عادی و شاغلین مشاغل سخت و زیان آور به کارکنان واحدهای صنعتی و تحقیقاتی وزارت دفاع و پشتیبانی نیروهای مسلح=qq84394
قانون شمول قانون استخدام نیروهای مسلح شاهنشاهی بافسران و درجه داران و افراد شهربانی کل کشور=qq114356
قانون فهرست قوانین و احکام منسوخ در حوزه محیط زیست=qq289668
قانون قراداد تشویق وحمایت متقابل سرمایه گذاری بین دولت ایران وجمهوری فدرال آلمان=qq85065
قانون لغو تبصره 70 قانون بودجه سال 1342 کل کشور و تبصره ماده 74 قانون استخدام نیروهای مسلح شاهنشاهی=qq86760
قانون متمم بودجه سال 313 [1313]مملکتی=qq115907
قانون مربوط باصلاح ماده 49 قانون ثبت احوال مصوب 13 اسفند ماه 1334=qq114576
قانون مربوط بالحاق یک تبصره بماده 370 قانون امور حسبی و یک تبصره بماده 56 قانون شریع(تسریع) محاکمات=qq113534
قانون مربوط بقرداد فروش و خرید گاز طبیعی بین شرکت ملی ایران وشرکت متالیمکس (METALIMEX)چکسلواکی=qq86609
قانون مربوط بقرداد فروش و خریدگازطبیعی بین شرکت ملی گاز ایران و شرکتهای روهرگاز Ruhrgaz گاز دوفرانس (Gaz de France)و نفت معدنی اطریش Oesterreichische Mineraloel Verwaltung Aktiengesellschaft=qq86601
قانون مربوط بموافقت‌نامه راجع به سرویسهای حمل و نقل بازرگانی منعقده بین دولت شاهنشاهی ایران و دولت هلند=qq114554
قانون مربوط به اجازه پرداخت اجرت تعمیر الات [آلات] هواپیماهای سمپاش دفع آفات نباتی بدون رعایت تشریفات مناقصه به کمپانی جوناس ارکرافت نیویورک (jonas Airctaft)=qq114748
قانون معافیت بهداشتکاران دهان و دندان و بهداران (تکنیسین های بهداشت و مبارزه با بیماریها) از انجام خدمات وظیفه عمومی=qq85375
قانون موافقتنامه تشویق و حمایت متقابل از سرمایه گذاری بین دولت جمهوری اسلامی ایران و دولت جماهیری عربی مردمی سوسیالیستی=qq117914
قرار دادن مبلغ 15‌000‌000 میلیون ریال از محل تنخواه گردان خزانه داری کل در اختیار اداره کل حسابداری نخست وزیری=qq234522
کسر مبلغ دو میلیون ریال از اعتبار ماده 13 بودجه اختصاصی 3 ه سهمیه وزارت بهداری و افزودن به اعتبار ماده 14 همان بودجه=qq94273
کمک به بهبود نحوه تولید و استانداردیزاسیون کالاهای صادراتی کشور=qq232936
لایحه قانونی اصلاح بعضی از موارد مقررات استخدامی شرکتهای دولتی و الحاق مواد و تبصره هائی به آن=qq86734
لایحه قانونی اصلاح قانون مربوط بسرسید سفته ها وتضمین نامه ها وبروات و چکها=qq86971
لایحه قانونی اصلاح قانون مربوط بسرسید سفته ها وتضمین نامه ها وبروات و چکها=qq86971
لایحه قانونی اصلاح ماده3 آئین نامه کمک خرج بکارمندان دولت=qq176339
لایحه قانونی الحاق سه تبصره به مواد 7 و 11 و 14 قانون تشکیل دادگاههای عمومی و یک تبصره بماده 17 قانون اصلاح قانون منع کشت خشخاش مصوب سال 1338 و اصلاح ماده 46 قانون اصول تشکیلات دادگستری=qq87062
لایحه قانونی الحاق سه تبصره به مواد 7 و 11 و 14 قانون تشکیل دادگاههای عمومی و یک تبصره بماده 17 قانون اصلاح قانون منع کشت خشخاش مصوب سال 1338 و اصلاح ماده 46 قانون اصول تشکیلات دادگستری=qq87062
لایحه قانونی انتقال وجوه حاصله از فروش اراضی یوسف آباد ببانک ساختمانی=qq176113
لایحه قانونی تصویب قرارداد بین المللی ارتباطات دوره منعقده در بوئنوس آیرس در سال 1331=qq113460
لایحه قانونی تصویب قرارداد بین المللی ارتباطات دوره منعقده در بوئنوس آیرس در سال 1331=qq113460
لایحه قانونی راجع به شمول مقررات قانون استخدام کشوری به سازمان ملی حفاظت آثار باستانی -تالار رودکی ـ مرکز اسناد فرهنگی آسیا ـ تأتر شهر=qq87513
لایحه قانونی لغو تصویبنامه های مالیات اراضی شهر تهران و چندین شهر دیگر=qq175762
لایحه قانونی مالکیت و بهره برداری از اراضی واقع در آبخورسد دز و الغاء قردادهای کشت و صنعت=qq87024
لایحه قانونی مالکیت و بهره برداری از اراضی واقع در آبخورسد دز و الغاء قردادهای کشت و صنعت=qq87024
لایحه قانونی ملی کردن سهام شرکت سهامی انبارهای عمومی=qq83938
لایحه قانونی ملی کردن سهام شرکت سهامی انبارهای عمومی=qq83938
لغو تصویب نامه شماره 22742 مورخ 20/6/1341 دولت راجع به مالیات پیشه وران=qq165988
ماده واحده راجع به اخذ فارغ‌التحصیلان دیپلمه داوطلب خدمت و ارتش و شماره دانش=qq227748
موافقتنامه فرهنگی بین دولت جمهوری اسلامی ایران و دولت جمهوری متحده تانزانیا=qq85196
قانون استخدام نیروهای مسلح شاهنشاهی ایران [قانون ارتش جمهوری اسلامی ایران]=qq113595
+32
View File
@@ -0,0 +1,32 @@
لایحه قانونی راجع به آئین نامه اجرائی دفتر معاملات مسکن و تغییرنام=qq118694
منتفی بودن لایحه قانونی تشکیل انجمنهای ده و اصلاح امور اجتماعی و عمرانی دهات=qq120753
خریداری کلیه اراضی گودهای کوره پزخانه های سابق و فعلی واقع در جنوب تهران بین خیابانهای شوش و حد جنوبی جدید تهران و جاده آرامگاه و خیابان سپهبد رزم آرا توسط شهرداری تهرات برای رفع نیازمندی های عمومی شهر=0
قانون راجع باجازه تحصیل مبلغ هفتاد و دو میلیون دلار وام از بانک بین‌المللی ترمیم و توسعه=qq113980
قانون راجع به احداث و توسعه معابر و خیابان ها=qq112239
قانون بودجه 1385 کل کشور=qq87759
قانون بودجه سال 1369کل کشور=qq84519
قانون اصلاح مواد 4 و 6 قانون تغییر نام وزارت آبادانی و مسکن بوزارت مسکن و شهرسازی و تعیین وظایف آن=qq86848
ائین‌نامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28ر12ر1345=qq115135
قانون اعطای امتیاز نفط بشرکت نفط انگیس[انگلیس] و ایران محدود=qq85083
آئین نامه اجرائی لایحه قانونی اصلاح لایحه قانونی واگذاری و احیاء اراضی در حکومت جمهوری اسلامی ایران مصوب 21/1/59=qq83760
لایحه قانونی ملی کردن سهام شرکت سهامی انبارهای عمومی=qq83938
لایحه قانونی الحاق سه تبصره به مواد 7 و 11 و 14 قانون تشکیل دادگاههای عمومی و یک تبصره بماده 17 قانون اصلاح قانون منع کشت خشخاش مصوب سال 1338 و اصلاح ماده 46 قانون اصول تشکیلات دادگستری=qq87062
لایحه قانونی مالکیت و بهره برداری از اراضی واقع در آبخورسد دز و الغاء قردادهای کشت و صنعت=qq87024
لایحه قانونی اصلاح قانون مربوط بسرسید سفته ها وتضمین نامه ها وبروات و چکها=qq86971
تصمیم قانونی راجع به آئین نامه جلوگیری از آلودگی هوا=0
قانون قراداد تشویق وحمایت متقابل سرمایه گذاری بین دولت ایران وجمهوری فدرال آلمان=qq85065
قانون اجازه تحصیل مبلغ بیست و پنج میلیون دلار وام از صندوق وامهای عمرانی امریکا=qq85231
رد لایحه راجع به تشکیل اداره دعاوی وزارت دارائی که در کمیسیون مشترک مجلسین رد شده است=qq114031
آئین نامه اجرائی ماده 18 قانون اصلاح قانون مالیات بر درآمد=qq113975
قانون مربوط بالحاق یک تبصره بماده 370 قانون امور حسبی و یک تبصره بماده 56 قانون شریع(تسریع) محاکمات=qq113534
لایحه قانونی تصویب قرارداد بین المللی ارتباطات دوره منعقده در بوئنوس آیرس در سال 1331=qq113460
قانون مربوط بموافقت‌نامه راجع به سرویسهای حمل و نقل بازرگانی منعقده بین دولت شاهنشاهی ایران و دولت هلند=qq114554
تصمیم متخذه کمیسیون مشترک در مورد هزینه های دادگستری و ثبت و حق تمبر پروانه=qq113344
قانون تصویب عهدنامه تسویه مسالمت آمیز اختلافات بین دولت شاهنشاهی ایران و دولت پادشاهی عراق=qq85019
قانون راجع برشد متعاملین=qq112444
قانون اصلاح مواد 13ر 41ر 43ر70ر111ر117قانون ثبت اسناد و املاک=qq112144
قانون اجازه مبادله عهدنامه مودت منعقده بین دولتین ایران و افغانستان=qq84876
قانون اصلاح جداول شماره (4) و (8) قانون برنامه چهارم توسعه اقتصادی، اجتماعی و فرهنگی جمهوری اسلامی ایران و قانون بودجه سال 1386 کل کشور به منظور تآمین کسری اعتبار گاز رسانی به روستاهای کشور=qq36662
قانون الحاق دولت جمهوری اسلامی ایران به پروتکل 1992جهت اصلاح کنوانسیون بین المللی مسوولیت مدنی ناشی ازخسارت آلودگی نفتی ( 1969 ) و پروتکل 1992 جهت اصلاح کنوانسیون تاسیس یک صندوق بین المللی برای جبران خسارت آلودگی نفتی (1971)=qq116450
قانون مربوط بقرداد فروش و خرید گاز طبیعی بین شرکت ملی ایران وشرکت متالیمکس (METALIMEX)چکسلواکی=qq86609
قانون مربوط بقرداد فروش و خریدگازطبیعی بین شرکت ملی گاز ایران و شرکتهای روهرگاز Ruhrgaz گاز دوفرانس (Gaz de France)و نفت معدنی اطریش Oesterreichische Mineraloel Verwaltung Aktiengesellschaft=qq86601
+588
View File
@@ -0,0 +1,588 @@
import os
from dotenv import load_dotenv
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import time
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper
##--------------------------------
# بخاطر خطایی که در تبدیل داده به الاستیک برای مواردی که حرف کشیده به جای خط تیر استفاده شده بود، ایجاد شد
# و این داده به مجلس ارسال شد و کارمندان مجلس هم در داده قانون تغییراتی ایجاد کردند
# لازم شد داده مجلس گرفته شود و اصلاح با احتیاط انجام شود تا تغییرات مجلس نیز حفظ شود
# طبیعتا دیگر نیاز به اجرای این برنامه نخواهد بود
##------------------------------------
# cursor, cnxn = create_cursor()
def extract_all_effecteds(elastic, index_name, body={}):
try:
list = elastic.es_iterate_all_documents(index_name, body)
except Exception as e:
save_error(0, e)
count = 0
text_normal = TextNormalizer()
result = {}
result_new = {}
for mentry in list:
entry = mentry["source"]
id = entry.get("id", "")
effects = entry.get("effects", [])
for effect in effects :
to_section_id = effect["to_section_id"]
effect_type = effect["effect_type"]
result[to_section_id] = effect_type
if effect_type == 'الحاقی' or effect_type =='یتفسیر' :
id = effect["id"]
result_new[id] = to_section_id
return result, result_new
def repair_law_section_text(cursor, elastic, index_name, dict_changed, file_log) :
query = '''
select
s.ID as sectionId
,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره
,isnull(l.APPROVEDATE,'') as aproveDate -- تاریخ تصویب
from lwSection s
left join lwLaw l on s.F_LWLAWID = l.ID
where l.ISLAW = 1
order by s.F_LWLAWID,textOrder
'''
cursor.execute(query)
text_normal = TextNormalizer()
total_count = 0
bulk_data = []
t1= datetime.datetime.now()
print(t1)
file = open(file_log, 'a+', encoding='utf8')
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.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)
text2 = text_normal.normalize_qanon(text,True)
# در این صورت مشکل خطای حذف خط تیره کشیده در این متن نبوده و نیازه به بروز رسانی متن نیست
if len(text) == len(text2) :
if text != text2 :
print(' ??????????> changed content : ', eid, "\ntext:", text , "\ntext2:", text2)
continue
content_len = text.__len__()
eid='qs'+ str(row.sectionId)
ts_year = ''
if row.aproveDate :
items = row.aproveDate.split("/")
if items.__len__() > 0:
ts_year = items[0]
data={}
if eid in dict_changed :
print( ' ------------------> chenged effected : ', dict_changed[eid])
file.write(' ------------------> chenged effected : '+ dict_changed[eid] + '\n')
if dict_changed[eid] == 'اصلاحی' or dict_changed[eid] == 'جایگزین':
# اصلاح تاریخ تصویب که بخاطر خطای سامانه ایجاد شده است
data={
'_id':eid,
'_source' : {
'ts_date': row.aproveDate,
'ts_year': ts_year,
}
}
#word_len = len(split_words(text))
if not data :
data={
'_id':eid,
'_source' : {
'content': text,
'content_len': content_len,
}
}
item = {}
try:
item = elastic.get_doctument(index_name, eid)
# در اینصورت محتوای ماده توسط مجلس تغییر یافته است
text_m = text_normal.normalize_qanon(item['_source']['content'], True).strip().replace(' ', '')
text_m2 = text_normal.normalize_qanon(text, True).strip().replace(' ', '')
if text_m != text_m2 :
print(' ==========> changed content : ', eid, "\ntext:", text_m , "\ntext:", text_m2)
file.write(' ==========> changed content : '+ eid + '\n')
continue
except Exception as e:
# print(type(e).__name__)
continue
# _source = item['_source']
# if 'ref_state' in _source :
# for ref in _source['ref_state'] :
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid)
elastic.updateBulkList(bulk_data, index_name)
bulk_data = []
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 )
elastic.updateBulkList(bulk_data, index_name)
file.close()
print('end success import_law_section_to_elastic')
t2= datetime.datetime.now()
print(t2-t1)
def repair_error_new_section_ts_date( elastic, index_name, dict_changed, file_log) :
total_count = 0
bulk_data = []
t1= datetime.datetime.now()
print(t1)
file = open(file_log, 'a+', encoding='utf8')
i = 0
for key in dict_changed.keys():
# باعث خطای کوئری میشد و نیاز نبود
# print(i)
i=i+1
eid=key
eid_prev = dict_changed[key]
ts_year = ''
item = {}
try:
item = elastic.get_doctument(index_name, eid_prev)
ts_date = item['_source']['ts_date']
ts_year = item['_source']['ts_year']
sort_date_timestamp = item['_source']['sort_date_timestamp']
# در اینصورت محتوای ماده توسط مجلس تغییر یافته است
except Exception as e:
continue
data={
'_id':eid,
'_source' : {
'ts_date': ts_date,
'ts_year': ts_year,
'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp
}
}
if len(bulk_data) >= 10:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid)
elastic.updateBulkList(bulk_data, index_name)
bulk_data = []
if data :
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 )
elastic.updateBulkList(bulk_data, index_name)
file.close()
print('end success import_law_section_to_elastic')
t2= datetime.datetime.now()
print(t2-t1)
def repair_error_section_ts_date(cursor, elastic, index_name, dict_changed, file_log) :
ids = ''
for key in dict_changed.keys():
# باعث خطای کوئری میشد و نیاز نبود
if '_' in key :
continue
key = key.replace('qs', '')
# if key == 'qs1414840_2512221' or key == 'qs1414840_2511' or key=='qs67f53e80b9949_008' :
# continue
# number = False
# try :
# number = int(key)
# except :
# number = False
# if not number :
# continue
if ids != '' :
ids = ids + ','
ids = ids + key[2:]
query = f'''
select
s.ID as sectionId
,isnull(s.SECTIONTEXT,'') as sectionText -- متن ماده یا تبصره
,isnull(l.APPROVEDATE,'') as aproveDate -- تاریخ تصویب
from lwSection s
left join lwLaw l on s.F_LWLAWID = l.ID
where l.ISLAW = 1 and s.ID in ({ids})
order by s.F_LWLAWID,textOrder
'''
print(query)
cursor.execute(query)
text_normal = TextNormalizer()
total_count = 0
bulk_data = []
t1= datetime.datetime.now()
print(t1)
file = open(file_log, 'a+', encoding='utf8')
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.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)
text2 = text_normal.normalize_qanon(text,True)
# در این صورت مشکل خطای حذف خط تیره کشیده در این متن نبوده و نیازه به بروز رسانی متن نیست
if len(text) == len(text2) :
if text != text2 :
print(' ??????????> changed content : ', eid, "\ntext:", text , "\ntext2:", text2)
continue
content_len = text.__len__()
eid='qs'+ str(row.sectionId)
ts_year = ''
if row.aproveDate :
items = row.aproveDate.split("/")
if items.__len__() > 0:
ts_year = items[0]
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 # خطا یا خالی
data={}
if eid in dict_changed :
# if dict_changed[eid] == 'اصلاحی' or dict_changed[eid] == 'جایگزین':
# اصلاح تاریخ تصویب که بخاطر خطای سامانه ایجاد شده است
data={
'_id':eid,
'_source' : {
'ts_date': row.aproveDate,
'ts_year': ts_year,
'sort_date_timestamp': sort_date_timestamp, # created from repairQanon.getSortTimestamp
}
}
if len(bulk_data) >= 10:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid)
elastic.updateBulkList(bulk_data, index_name)
bulk_data = []
if data :
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 )
elastic.updateBulkList(bulk_data, index_name)
file.close()
print('end success import_law_section_to_elastic')
t2= datetime.datetime.now()
print(t2-t1)
def repair_law_section_ref_state(cursor, elastic, index_name, dict_changed, file_log) :
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()
total_count = 0
bulk_data = []
previd = ''
prev_effect_type = ''
prev_efect_section_id = ''
ref_state_array = []
t1= datetime.datetime.now()
print(t1)
file = open(file_log, 'a+', encoding='utf8')
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
if eid in dict_changed :
print( ' ------------------> chenged effected : ', eid, ' : ', dict_changed[eid])
file.write(' ------------------> chenged effected : '+ eid+ ' : ' + dict_changed[eid] + '\n')
if dict_changed[eid] == 'اصلاحی' or dict_changed[eid] == 'جایگزین':
continue
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,
'_source' : {
'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('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid)
elastic.updateBulkList(bulk_data, index_name)
bulk_data = []
if ref_state_array.__len__() > 0 :
data={
'_id':previd,
'_source' : {
'ref_state' : ref_state_array
}
}
bulk_data.append(data)
# print(bulk_data)
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + eid)
elastic.updateBulkList(bulk_data, index_name)
bulk_data = []
print('end success import_law_section_update_ref_state')
t2= datetime.datetime.now()
print(t2-t1)
load_dotenv(dotenv_path='config.env')
host=os.getenv('HOST_160')
password=os.getenv('HOST_160_PASS')
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
cursor, cnxn = create_cursor()
body={
"query": {
"exists": {"field": "effects"}
}
}
dict_effected_sections, dict_effected_new_sections = extract_all_effecteds(elastic, "mj_df_qanon", body)
# print(dict_effected_sections)
# try:
# item = elastic.get_doctument("mj_qa_section", "3223423")
# except Exception as e:
# print(e)
# print(type(e).__name__)
# print(str(e))
###### step 1 repair text - ###########################
repair_law_section_text(cursor, elastic, "mj_qa_section", dict_effected_sections, "./output/log_r1.txt")
###### step 2 : repair date #############
repair_error_section_ts_date(cursor, elastic, "mj_qa_section", dict_effected_sections, "./output/log_r1.txt")
repair_error_new_section_ts_date( elastic, "mj_qa_section", dict_effected_new_sections, "./output/log_r1.txt")
###### step 3 : not nead #############
#repair_law_section_ref_state(cursor, elastic, "mj_qa_section", dict_effected_sections, "./output/log_r2.txt")
+105
View File
@@ -0,0 +1,105 @@
import os
from dotenv import load_dotenv
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import time
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper
def moveModelToQaSectionMirror(elastic, index_name_i, index_name_o):
try:
body={}
try:
list = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
dtime = myTimestamp(-100)
count = 0
for mentry in list:
count += 1
entry = mentry["source"]
if (count % 100) == 0 :
print("%s -> %.2f " % (id , (count / elastic.total) if elastic.total > 0 else 0))
id = entry.get("ref_id", "")
qanon_title = entry.get("qanon_title", "")
ts_date = entry.get("ts_date", "")
qanon_id = entry.get("qanon_id", "")
other_info = entry.get("other_info", {})
model_work_tags = entry.get("work_tags", [])
model_work_state = entry.get("work_state", [])
model_rules = entry.get("rules", [])
model_rules_logics = entry.get("rules_logics", [])
model_rules_logics_triples = entry.get("rules_logics_triples", [])
model_rules_spins = entry.get("rules_spins", [])
model_files = entry.get("files", [])
user_edit = entry.get("user_edit", "")
time_edit = entry.get("time_edit", dtime)
user_logs = entry.get("user_log", [])
doc_states = ['user', 'model']
edit_type = 'model'
is_delete = 0
eid = edit_type + str(id) + '_' + str(user_edit)
data = {
"id" : id,
"qanon_title" : qanon_title,
"ts_date" : ts_date,
"qanon_id" : qanon_id,
"other_info" : other_info,
"model_work_tags" : model_work_tags,
"model_work_state" : model_work_state,
"model_rules" : model_rules,
"model_rules_logics" : model_rules_logics,
"model_rules_logics_triples" : model_rules_logics_triples,
"model_rules_spins" : model_rules_spins,
"model_files" : model_files,
"user_edit" : user_edit,
"time_edit" : time_edit,
"user_logs" : user_logs,
"doc_states" : doc_states,
"edit_type" : edit_type,
"is_delete" : is_delete,
}
try:
resp = elastic.update_index_doc(False, index_name_o, eid, data)
except Exception as e:
print(e)
# save_error(id, e)
except Exception as e:
print("1111")
print(e)
load_dotenv(dotenv_path='config.env')
# host=os.getenv('HOST_160')
# password=os.getenv('HOST_160_PASS')
host=os.getenv('HOST_112')
password=os.getenv('HOST_112_PASS')
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
elastic.createIndex("mj_qa_section-m1", 'majles', "mj_qa_section" )
moveModelToQaSectionMirror(elastic, "mj_model", "mj_qa_section-m1")
+712
View File
@@ -0,0 +1,712 @@
import os
import re
import traceback
import json
import pandas as pd
from dotenv import load_dotenv
# from app.common.general_functions import *
from app.common.qanon_functions import *
from app.common.elastic_helper import ElasticHelper
from app.common.config_base import *
def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""):
# excel_helper = ExcelHelper()
# df = excel_helper.load_data(file)
# df = pd.read_excel('records.xlsx', sheet_name='Cars', usecols=['Car Name', 'Car Price'])
# print(df)
df = pd.read_excel(file_excel, sheet_name=0, header=None)
# print(df[0:10])
# print(df.columns.ravel())
# print(df.columns.tolist())
# print(df['EmpName'].tolist())
# print(df[0].tolist())
count = 0
rows_list = df.to_dict(orient='records')
total = len(df[0])
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=0
try:
for row in rows_list:
section_title = row[column_names[0]]
ts_date = row[column_names[1]]
qanon_title = row[column_names[2]]
code_state = row[column_names[3]]
row_number = row[column_names[4]]
# if code_state :
# print ( 'ddddddddddddddcode_state' , code_state)
# else :
# print ( 'ccccccccccccccode_state' , code_state)
qanon_id = 0
section_id = 0
state = ''
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
if section_title is None or is_nan_or_none_or_empty(section_title) or qanon_title is None or is_nan_or_none_or_empty(qanon_title) :
file.write('!!!!!! nan error !!!!!!!' + str(count) + '\n')
state = 'خطا-پرش'
else:
section_title = text_normalizer.normalize_search_qanon(str(section_title))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
if qanon_id == 0 :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
dic_error_qanon_title[qanon_title]=count
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
else:
state = 'قانون-جستجو'
# اگر شناسه قانون یافت شد، برای شناسه جزء جستجو کند ...
if not qanon_id == 0 :
section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title)
# - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود
if score < 90 :
dic_error_section_title[str(qanon_id)+'=='+section_title]=count
print('='*10 , str(count) , ' section error', qanon_id, ' --> ', section_title )
file.write('---- section error ---' + str(qanon_id) + ' ----- ' + section_title + '\n')
section_id = 0
state = 'خطا-جزء'
else :
state = 'صحیح'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row[5]=qanon_id
row[6]=section_id
row[7]=state
rows_list_new.append(row)
data={}
# ذخیره کد در الاستیک برای شناسه های یافت شده
if section_id and section_id != 0:
item = elastic.get_doctument(index_name_o,section_id)
tcode_mains = []
tcode_subs = []
if "tcode_mains" in item['_source'] :
tcode_mains= item['_source']["tcode_mains"]
if "tcode_subs" in item['_source'] :
tcode_subs= item['_source']["tcode_subs"]
code = {
"label" : tcode_label,
"id" : tcode_id
}
if code_state == True :
tcode_mains.append(code)
else:
tcode_subs.append(code)
data={
'_id':section_id,
'_source' : {
'tcode_mains': tcode_mains,
'tcode_subs': tcode_subs,
}
}
bulk_data.append(data)
# انتقال دسته جمعی کدها به الاستیک
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) )
elastic.updateBulkList(bulk_data, index_name_o)
##### columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
# columns=[0, 1, 2, 3, 4, 5, 6, 7]
# new_df = pd.DataFrame(rows_list_new, columns=columns)
# if result_path == '' :
# directory_path = os.path.dirname(file_excel)
# result_path = directory_path + "/result/"
# file_name = os.path.basename(file_excel)
# file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
# print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
file_log2= file_log.replace(".txt", "_2.txt")
with open(file_log2, 'w', encoding='utf8') as file2:
file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4))
def importEtebarToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""):
df = pd.read_excel(file_excel, sheet_name=0)
count = 0
rows_list = df.to_dict(orient='records')
column_names = df.columns.tolist()
column_count = len(column_names)
# print(column_names)
total = len(df[column_names[0]])
print('total : ', total)
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=0
prevRow = None
try:
for row in rows_list:
row_number = row[column_names[0]]
title = row[column_names[1]]
section_title = row[column_names[2]]
ts_date = ""
code_state = ""
if title is None or is_nan_or_none_or_empty(title) or title is None or is_nan_or_none_or_empty(title) :
title = prevRow[column_names[1]]
else:
prevRow = row
qanon_id = 0
section_id = 0
state = ''
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
title = text_normalizer.normalize_search_qanon(title)
qanon_title, ts_date, ts_ref = get_qanon_date(title)
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
# قانون ساختمان شاهراه تهران – كرج
qanon_title = qanon_title.replace("–", "-")
score = 100
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
if qanon_id == 0 :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
dic_error_qanon_title[qanon_title]=count
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
else:
state = 'قانون-جستجو'
# اگر شناسه قانون یافت شد، برای شناسه جزء جستجو کند ...
section_title = text_normalizer.normalize_search_qanon(str(section_title))
result_section_title = get_section_correct(section_title)
result_section_id = []
if qanon_id != 0 :
for section_title in result_section_title:
if section_title == 'all' :
state = 'صحیح'
result_section_id.append('all')
continue
section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title)
# - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود
if score < 90 :
dic_error_section_title[str(qanon_id)+'=='+section_title]=count
print('='*10 , str(count) , ' section error', qanon_id, ' --> ', section_title )
file.write('---- section error ---' + str(qanon_id) + ' ----- ' + section_title + '\n')
section_id = 0
state = 'خطا-جزء'
elif state == '':
state = 'صحیح'
result_section_id.append(section_id)
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row[column_count+1]=qanon_id
row[column_count+2]= '#'.join(str(item) for item in result_section_id)
row[column_count+3]=state
row[column_count+4]=qanon_title +'#'+ ts_date +'#'+ ts_ref
row[column_count+5]='#'.join(result_section_title)
rows_list_new.append(row)
data={}
tstate = 'نامعتبر'
c_name = 'وضعیت اعتبار'
if c_name in column_names :
tstate = row[c_name].replace('#', '').replace('=', '')
if tstate.startswith('نامعتبر') :
tstate = 'نامعتبر-' + tstate
treason = ''
c_name = 'مستند عدم اعتبار'
if c_name in column_names :
treason = row[c_name].replace('#','\n').replace('=','\n')
description = ''
c_name = 'توضیحات'
if c_name in column_names :
description = row[c_name].replace('*', '')
# ذخیره کد در الاستیک برای شناسه های یافت شده
for section_id in result_section_id :
if section_id == '' or section_id == 0 :
continue
if section_id =='all':
tstate = tstate + ' کل '
result = get__all_section_qanon(elastic, index_name_o, qanon_id)
for sid in result :
tvalid_state={
"tstate": tstate.strip(),
"description": description,
"treason": treason,
# "treason_type": treason_type
}
data={
'_id':sid,
'_source' : {
'tvalid_state': tvalid_state
}
}
bulk_data.append(data)
break
tvalid_state={
"tstate": tstate.strip(),
"description": description,
"treason": treason,
# "treason_type": treason_type
}
data={
'_id':section_id,
'_source' : {
'tvalid_state': tvalid_state
}
}
bulk_data.append(data)
# انتقال دسته جمعی کدها به الاستیک
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) )
elastic.updateBulkList(bulk_data, index_name_o)
# columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
column_names.append(column_count+1)
column_names.append(column_count+2)
column_names.append(column_count+3)
column_names.append(column_count+4)
column_names.append(column_count+5)
columns= column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
tb = traceback.extract_tb(e.__traceback__)
print(tb)
line_number = tb[-1].lineno # Get the line number of the last call
print(f"Error: {e} on line {line_number}")
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
# file_log1= file_log.replace(".txt", "_1.txt")
# with open(file_log1, 'w', encoding='utf8') as file1:
# file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
# file_log2= file_log.replace(".txt", "_2.txt")
# with open(file_log2, 'w', encoding='utf8') as file2:
# file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4))
def importCodesToElastic(elastic, file_excel, index_name_o, tcode_label, tcode_id , file_log, result_path = ""):
# excel_helper = ExcelHelper()
# df = excel_helper.load_data(file)
# df = pd.read_excel('records.xlsx', sheet_name='Cars', usecols=['Car Name', 'Car Price'])
# print(df)
df = pd.read_excel(file_excel, sheet_name=0, header=None)
# print(df[0:10])
# print(df.columns.ravel())
# print(df.columns.tolist())
# print(df['EmpName'].tolist())
# print(df[0].tolist())
count = 0
rows_list = df.to_dict(orient='records')
total = len(df[0])
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=0
try:
for row in rows_list:
section_title = row[column_names[0]]
ts_date = row[column_names[1]]
qanon_title = row[column_names[2]]
code_state = row[column_names[3]]
row_number = row[column_names[4]]
qanon_id = 0
section_id = 0
state = ''
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
if section_title is None or is_nan_or_none_or_empty(section_title) or qanon_title is None or is_nan_or_none_or_empty(qanon_title) :
file.write('!!!!!! nan error !!!!!!!' + str(count) + '\n')
state = 'خطا-پرش'
else:
section_title = text_normalizer.normalize_search_qanon(str(section_title))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
if qanon_id == 0 :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
dic_error_qanon_title[qanon_title]=count
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
else:
state = 'قانون-جستجو'
# اگر شناسه قانون یافت شد، برای شناسه جزء جستجو کند ...
if not qanon_id == 0 :
section_id, score, section_item = searchSectionId(elastic, "mj_qa_section", qanon_id , section_title)
# - اگر شناسه یافت شده جزء قابل اطمینان نبود خطا ثبت شود
if score < 90 :
dic_error_section_title[str(qanon_id)+'=='+section_title]=count
print('='*10 , str(count) , ' section error', qanon_id, ' --> ', section_title )
file.write('---- section error ---' + str(qanon_id) + ' ----- ' + section_title + '\n')
section_id = 0
state = 'خطا-جزء'
else :
state = 'صحیح'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row[5]=qanon_id
row[6]=section_id
row[7]=state
rows_list_new.append(row)
data={}
# ذخیره کد در الاستیک برای شناسه های یافت شده
if section_id and section_id != 0:
item = elastic.get_doctument(index_name_o,section_id)
tcode_mains = []
tcode_subs = []
if "tcode_mains" in item['_source'] :
tcode_mains= item['_source']["tcode_mains"]
if "tcode_subs" in item['_source'] :
tcode_subs= item['_source']["tcode_subs"]
code = {
"label" : tcode_label,
"id" : tcode_id
}
if code_state :
tcode_mains.append(code)
else:
tcode_subs.append(code)
data={
'_id':section_id,
'_source' : {
'tcode_mains': tcode_mains,
'tcode_subs': tcode_subs,
}
}
bulk_data.append(data)
# انتقال دسته جمعی کدها به الاستیک
if len(bulk_data) >= 200:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count))
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if len(bulk_data) > 0:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(count) )
elastic.updateBulkList(bulk_data, index_name_o)
# columns=['جزء', 'مصوب', 'قانون', 'اصلی', 'ردیف', 'شناسه قانون', 'شناسه جزء', 'وضعیت پردازش']
columns=[0, 1, 2, 3, 4, 5, 6, 7]
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
file_log2= file_log.replace(".txt", "_2.txt")
with open(file_log2, 'w', encoding='utf8') as file2:
file2.write(json.dumps(dic_error_section_title, ensure_ascii=False, indent=4))
def run_Codes_directory(elastic, directory, output):
dic_code_id={
"آب" : 1,
"آمار، برنامه و بودجه" : 2,
"آموزش و پرورش" : 3,
"آیین دادرسی مدنی" : 5,
"سلامت" : 30,
"فرهنگ و هنر" : 33,
"مسکن و شهرسازی" : 42,
"مناطق آزاد و ویژه اقتصادی" : 45,
"نفت و گاز" : 49
}
# List all files in the specified directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
for file in files :
file_name = os.path.basename(file)
code_name = os.path.splitext(file_name)[0]
w1 = text_normalizer.split_words(code_name)[0]
log_file = output + "/log_r_"+w1+".txt"
file_path = os.path.join(directory, file)
try:
os.makedirs(output, exist_ok=True)
except Exception as e:
print(output)
code_id = 0
if code_name in dic_code_id :
code_id = dic_code_id[code_name]
importCodesToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file)
else :
print('00000 error 000000 ', code_name)
def run_Etebar_directory(elastic, directory, output):
dic_code_id={
"آب" : 1,
"آمار، برنامه و بودجه" : 2,
"آموزش و پرورش" : 3,
"آیین دادرسی مدنی" : 5,
"سلامت" : 30,
"فرهنگ و هنر" : 33,
"مسکن و شهرسازی" : 42,
"مناطق آزاد و ویژه اقتصادی" : 45,
"نفت و گاز" : 49,
}
# List all files in the specified directory
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
for file in files :
file_name = os.path.basename(file)
if '~$' in file_name :
continue
code_name = os.path.splitext(file_name)[0]
code_name = code_name.replace("نامعتبر-", "").strip()
w1 = text_normalizer.split_words(code_name)[0]
log_file = output + "/log_r_"+w1+".txt"
file_path = os.path.join(directory, file)
# if code_name != 'سلامت' :
# continue
try:
os.makedirs(output, exist_ok=True)
except Exception as e:
print(output)
code_id = 0
importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file)
# if code_name in dic_code_id :
# code_id = dic_code_id[code_name]
# importEtebarToElastic(elastic, file_path, "mj_qa_section", code_name, code_id, log_file)
# else :
# print('00000 error 000000 ', code_name)
load_dotenv(dotenv_path='config.env')
# host=os.getenv('HOST_160')
# password=os.getenv('HOST_160_PASS')
# host=os.getenv('HOST_112')
# password=os.getenv('HOST_112_PASS')
host=os.getenv('HOST_113')
password=os.getenv('HOST_113_PASS')
print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
#run_Codes_directory(elastic, "./data/tcodes", "./data/tcodes/result")
run_Etebar_directory(elastic, "./data/tetebar", "./data/tetebar/result")
# importCodesToElastic(elastic, "./data/tcodes/مسکن و شهرسازی.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r3.txt")
# importCodesToElastic(elastic, "./data/tcodes/آمار، برنامه و بودجه.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_آمار.txt")
# importCodesToElastic(elastic, "./data/tcodes/آیین دادرسی مدنی.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_دادرسی.txt")
# importCodesToElastic(elastic, "./data/tcodes/نفت و گاز.xlsx", "mj_qa_section", "مسکن و شهرسازی", "./data/log_r_نفت.txt")
# text="قانون  بلدیه"
#text = text.replace("\u00a0", " ") # No Break space
# text="قانون تشکیلات، وظایف و انتخابات شوراهای اسلامی کشور و انتخاب شهرداران مصوب 1 /3 /1375 و اصلاحات بعدی آن"
# text="ائین‌نامه[آئین نامه] اجرای مالیات اراضی بایر موضوع تبصره 4 ماده 214 قانون مالیاتهای مستقیم مصوب 28ر12ر1345"
# text="قانون بودجه سال 1369کل کشور"
# text="قانون تشکیلات، وظایف و انتخابات شوراهای اسلامی کشور و انتخاب شهرداران مصوب 1/3/1375 و اصلاحات بعدی آن"
text="قانون بودجه سال 1369کل کشور"
text="پیوست 3>متن >ضمیمه 1>قسمت الف>فصل پنجم>جدول الف-1-1-1 /5"
# searchSectionId(elastic, "mj_qa_section", "qq240970", text )
# text = text_normalizer.date_correction(text)
# text = re.sub(r"(\d+?) /(\d+?) /(\d+?)", r"\1/\2/\3", text)
# text = re.sub(r"(\d)/(\d)/(\d{4})", r"0\1/0\2/\3", text)
# print(text.split('/'))
# text1 = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", text)
# print(text)
# print(text1)
# print(text1==text)
# print( searchQanonId(elastic, text) )
+120
View File
@@ -0,0 +1,120 @@
import pandas as pd
import requests
import json
from app.common.text_normalizer import TextNormalizer
# from app.common.config_base import *
from app.common.general_functions import *
ADD_ITEM_ROUTE = "subject/add"
# TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDgyNTY3MTYsImp0aSI6IlZWejlWRDFGMUx5UkEyd01EaW5od3M3cTJRRkVqYW9kIiwiaXNzIjpudWxsLCJleHAiOjE3NDk1NTY3MTUsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDY0NVx1MDYyZlx1MDZjY1x1MDYzMSBcdTA2NDFcdTA2NDZcdTA2Y2MiLCJsYXN0X25hbWUiOiJcdTA2MzNcdTA2MjdcdTA2NDVcdTA2MjdcdTA2NDZcdTA2NDciLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.QljFs4f0HFT7S8qrib6q54kMWg7z381v2uqoiSFDfR4'
TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDk1NjU0NDksImp0aSI6IlwvODBxR2pEUHlleFZVRFErTkhKcGl0ejd6TmdvaDdHSiIsImlzcyI6bnVsbCwiZXhwIjoxNzUwODY1NDQ4LCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjIsImZpcnN0X25hbWUiOiJcdTA2MmRcdTA2NDVcdTA2Y2NcdTA2MmYiLCJsYXN0X25hbWUiOiJcdTA2MzVcdTA2NDFcdTA2MjdcdTA2Y2NcdTA2Y2MiLCJlbWFpbCI6InNhZmFlaS5oYW1pZEBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImhzYWZhZWkiLCJ1c2VyX2xldmVsIjoyfX0.XmEEA_DhVbUQe76guQxuNrEoTUxPRMYd5Zbi7l7m5M4'
ACCEPT = "application/json"
HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT}
# BASE_URL = "http://192.168.23.160/api/"
BASE_URL = "http://192.168.23.113/api/"
# TITLE = ""
def read_excel_data(file_path ):
df = pd.read_excel(file_path )
df.fillna("", inplace=True)
data = df.to_dict(orient="records")
text_normal = TextNormalizer()
for row in data:
row["CAPTION"] = text_normal.normalize_qanon(row["عنوان"])
row["ID"] = int(row["ردیف"])
row["META"] = row.get("توضیحات", "")
return data
def insert_project(title, id=''):
projectid = 8 # فرض کنید projectid ثابت است
return projectid
def insertProejct(title, id=''):
# ایجاد فهرست جدید
url = "project/add"
item = {
"id": id,
"title": title,
"type": 3,
"item_state": 1,
"ispublic" : 1,
}
result = requests.post(BASE_URL + 'list/' + url, data=item, headers = HEADERS)
res = json.loads(result.text)
if result.status_code == 200 :
# print(result.text)
New_ID = res["data"]["id"]
print(str('project added =' + str(New_ID)))
projectid = New_ID
return projectid
else :
New_ID = res["data"]["id"]
print(str('project exist=' + str(New_ID)))
projectid = New_ID
# print(res)
return projectid
def process_excel_data(file_path, send_to_server=True):
data = read_excel_data(file_path)
data = sorted(data, key=lambda x: x["ID"])
# projectid = insert_project('کدهای تنقیح 50 باب', 8)
projectid = insertProejct('کدهای تنقیح 50 باب', 8)
id_counter = 1 # برای fake_id
local_id_map = {} # برای نگه‌داشتن ID ساختگی در حالت تست
output_data = [] # لیستی برای ذخیره خروجی نهایی
for row in data:
caption = row["CAPTION"]
row_id = row["ID"]
meta = row.get("META", "")
meta = '{"description":"'+meta+'"}'
insertProejct('پلان ' + caption, 100+row_id)
# در حالت تست، parent_id از local map خونده میشه
payload = {
"title": caption,
"projectid": projectid,
"meta": meta,
"otherid": row_id,
"listtype": 0,
}
if send_to_server:
try:
response = requests.post(
BASE_URL + 'list/' + ADD_ITEM_ROUTE, data=payload, headers=HEADERS )
if response.status_code == 200:
res_json = response.json()
new_id = res_json["data"][0]["id"]
print(f"✅ Inserted {caption} => ID: {new_id}")
payload["id"] = new_id
else:
print(f"❌ Error inserting {caption} => Status Code: {response.status_code}")
except Exception as e:
print(f"❌ Failed to insert {caption} (ID={row_id}): {e}")
else:
fake_id = id_counter
local_id_map[row_id] = fake_id
id_counter += 1
# print(f"🧪 TEST MODE: Would insert => {payload} | Fake ID: {fake_id}")
output_data.append(payload)
file_name = "mmm1.json"
with open(file_name, "w", encoding="utf-8") as file:
json.dump(output_data, file, ensure_ascii=False, indent=4)
print(f"\n📁 خروجی در فایل «{file_name}» ذخیره شد.")
if __name__ == "__main__":
file_path = "data/کدهای 50 گانه.xlsx"
process_excel_data(file_path ,send_to_server=True ) # False for test
+224
View File
@@ -0,0 +1,224 @@
import pandas as pd
import requests
import json
import os
from app.common.text_normalizer import TextNormalizer
# from app.common.config_base import *
from app.common.general_functions import *
ADD_ITEM_ROUTE = "subject/add"
# TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDgyNTY3MTYsImp0aSI6IlZWejlWRDFGMUx5UkEyd01EaW5od3M3cTJRRkVqYW9kIiwiaXNzIjpudWxsLCJleHAiOjE3NDk1NTY3MTUsImF1ZCI6bnVsbCwiZGF0YSI6eyJpZCI6MSwiZmlyc3RfbmFtZSI6Ilx1MDY0NVx1MDYyZlx1MDZjY1x1MDYzMSBcdTA2NDFcdTA2NDZcdTA2Y2MiLCJsYXN0X25hbWUiOiJcdTA2MzNcdTA2MjdcdTA2NDVcdTA2MjdcdTA2NDZcdTA2NDciLCJlbWFpbCI6ImRldkBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImRldiIsInVzZXJfbGV2ZWwiOjJ9fQ.QljFs4f0HFT7S8qrib6q54kMWg7z381v2uqoiSFDfR4'
TOKEN='eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE3NDk1NjU0NDksImp0aSI6IlwvODBxR2pEUHlleFZVRFErTkhKcGl0ejd6TmdvaDdHSiIsImlzcyI6bnVsbCwiZXhwIjoxNzUwODY1NDQ4LCJhdWQiOm51bGwsImRhdGEiOnsiaWQiOjIsImZpcnN0X25hbWUiOiJcdTA2MmRcdTA2NDVcdTA2Y2NcdTA2MmYiLCJsYXN0X25hbWUiOiJcdTA2MzVcdTA2NDFcdTA2MjdcdTA2Y2NcdTA2Y2MiLCJlbWFpbCI6InNhZmFlaS5oYW1pZEBnbWFpbC5jb20iLCJ1c2VybmFtZSI6ImhzYWZhZWkiLCJ1c2VyX2xldmVsIjoyfX0.XmEEA_DhVbUQe76guQxuNrEoTUxPRMYd5Zbi7l7m5M4'
ACCEPT = "application/json"
HEADERS = {"Authorization": TOKEN, "Accept": ACCEPT}
# BASE_URL = "http://192.168.23.160/api/"
BASE_URL = "http://192.168.23.113/api/"
# TITLE = ""
def read_excel_data(file_path ,sheet_name):
df = pd.read_excel(file_path , sheet_name=sheet_name)
df.fillna("", inplace=True)
data = df.to_dict(orient="records")
column_names = df.columns.tolist()
text_normal = TextNormalizer()
for row in data:
row["CAPTION"] = text_normal.normalize_qanon(row["عنوان"])
row["ID"] = int(row["ردیف"])
row["F_PARENTID"] = int(row["سطح"]) - 1 if row["سطح"] > 1 else 0
row["LEVEL"] = int(row["سطح"])
row["CODE"] = row.get("کد", "")
return data, column_names
# def insert_project():
# projectid = 7 # فرض کنید projectid ثابت است
# return projectid
def insert_project(sheet_name):
json_file = 'کدهای 50 گانه.json'
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
for row in data:
if row.get("title") == sheet_name:
base_id = row.get("otherid", 0)
return base_id + 100 # افزایش ۱۰۰ واحدی
print(f"❌ Sheet name '{sheet_name}' not found in JSON data.")
return None
def insert_real_old(rows, projectid, IDS_DICT, childs,otherid):
remains = []
for row in rows:
try:
f_parentid = row["F_PARENTID"]
row_id = row["ID"]
caption = row["CAPTION"]
except KeyError:
print("Missing data in row:", row)
continue
# تعیین والد
if f_parentid == 0:
parent = 0
elif str(f_parentid) in IDS_DICT:
parent = IDS_DICT[str(f_parentid)]["id"]
else:
print(f"❗️ Parent not found for F_PARENTID={f_parentid}")
remains.append(row)
continue
# محاسبه شماره فرزند
number = childs.get(parent, 0) + 1
childs[parent] = number
# آماده‌سازی درخواست
ADD_ITEM_QUERY = {
"title": caption,
"projectid": projectid,
"otherid": otherid,
"meta": row.get("CODE", ""),
"childorder": number,
"listtype": 0,
"parent": parent,
}
try:
response = requests.post(
BASE_URL + 'list/' + ADD_ITEM_ROUTE,
data=ADD_ITEM_QUERY,
headers=HEADERS
)
response.raise_for_status()
res_json = response.json()
new_id = res_json["data"][0]["id"]
print(f"✅ {row_id}: {caption} -> ID={new_id}")
except Exception as e:
print(f"❌ Failed to insert {caption}: {e}")
remains.append(row)
continue
IDS_DICT[str(row_id)] = {
"id": new_id,
**ADD_ITEM_QUERY
}
return remains
def insert_real(rows, projectid, IDS_DICT, column_names,otherid):
remains = []
dic_level_parent = {1:0}
child_count = {}
prev_level = 0
prev_id = 0
new_row_list=[]
column_count = len(column_names)
for row in rows:
row_id = row["ID"]
caption = row["CAPTION"]
level = row["LEVEL"]
parent = 0
if level == 1 :
parent = 0
elif level == prev_level+1 :
parent = prev_id
dic_level_parent[level]=prev_id
elif level in dic_level_parent:
parent = dic_level_parent[level]
else :
print("error", level, row_id)
child_order = child_count.get(parent, 0) + 1
child_count[parent] = child_order
row[column_count+1] = parent
row[column_count+2] = child_order
new_row_list.append(row)
# آماده‌سازی درخواست
body = {
"title": caption,
"projectid": projectid,
"otherid": otherid,
"meta": row.get("CODE", ""),
"child_order": child_order,
"listtype": 0,
"parent": parent,
}
prev_level = level
try:
response = requests.post(
BASE_URL + 'list/' + ADD_ITEM_ROUTE,
data=body,
headers=HEADERS
)
response.raise_for_status()
res_json = response.json()
new_id = res_json["data"][0]["id"]
print(f"✅ {row_id}: {caption} -> ID={new_id}")
prev_id = new_id
except Exception as e:
print(f"❌ Failed to insert {caption}: {e}")
remains.append(row)
continue
IDS_DICT[str(row_id)] = {
"id": new_id,
**body
}
return new_row_list
def process_excel_data(file_path , sheet_name):
row_list, column_names = read_excel_data(file_path , sheet_name)
row_list = sorted(row_list, key=lambda x: x["ID"])
print(f"❗️ Parent not found for F_PARENTID={row_list}")
IDS_DICT = {}
childs = {}
projectid = insert_project(sheet_name)
otherid = projectid-100
if not projectid:
return
print("🚀 شروع درج داده‌ها")
rows_list_new = insert_real(row_list, projectid, IDS_DICT, column_names , otherid)
column_count=len(column_names)
column_names.append(column_count+1)
column_names.append(column_count+2)
columns=column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
result_path = os.path.dirname(file_path)
file_name = sheet_name
file_excel2 = result_path +'/پلن-'+ file_name + '.xlsx'
# print('rows_list_new', str(len(rows_list_new)), ' --> ', file_excel2)
# new_df.to_excel(file_excel2, index=False, engine='openpyxl')
# json_file_path = f'{sheet_name}.json'
# with open(json_file_path, "w", encoding="utf-8") as file:
# json.dump(IDS_DICT, file, ensure_ascii=False, indent=4)
# print(f"\n✅ تمام داده‌ها ثبت شدند و در {sheet_name} ذخیره شدند.")
if __name__ == "__main__":
file_path = "data/Plan.xlsx"
sheet_name = 'آموزش و پرورش'
process_excel_data(file_path , sheet_name)
sheet_name = 'مناطق آزاد و ویژه اقتصادی'
process_excel_data(file_path , sheet_name)
sheet_name = 'فرهنگ و هنر'
process_excel_data(file_path , sheet_name)
+538
View File
@@ -0,0 +1,538 @@
import os
import re
import traceback
import pandas as pd
import json
from dotenv import load_dotenv
from app.common.config_base import *
from app.common.elastic_helper import ElasticHelper
from app.common.qanon_functions import *
def parseBeforeInfos_SearchQanonTitle(elastic, file_excel, file_log, result_path = ""):
# df = pd.read_excel(file_excel, sheet_name=0, header=None)
df = pd.read_excel(file_excel, sheet_name=0)
count = 0
rows_list = df.to_dict(orient='records')
total = len(rows_list)
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
id2_index = column_names.index("_id2")
id3_index = column_names.index("_id3")
id_index = column_names.index("_id")
if not id_index :
id_index = len(column_names)
column_names.append("_id")
error_index = column_names.index("error")
if not error_index :
error_index = len(column_names)+1
column_names.append("error")
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=0
row_number = 0
try:
for row in rows_list:
row_id = row[column_names[0]]
qanon_title = row[column_names[1]]
# print(qanon_title)
ts_date = row[column_names[3]]
_id2 = ''
_id3 = ''
if id2_index :
_id2 = row[column_names[id2_index]]
if id3_index :
_id3 = row[column_names[id3_index]]
# print(ts_date)
row_number = row_number + 1
qanon_id = 0
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
state='قانون-جستجو'
qanon_id = 0
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
else :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score < 90 :
qanon_title = get_qanon_title_sample(qanon_title, False)
qanon_title, ts_date, ts_ref = get_qanon_date(qanon_title)
if ts_date or ts_ref :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score < 90 :
if _id3 :
qanon_id=_id3
state = 'دستی-مجلس'
elif score == 80 :
state = 'عنوان-تکراری'
elif score < 80 :
dic_error_qanon_title[qanon_title]= str(count) + ' - ' + str(row_number)
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row["_id"]=qanon_id
row["error"]=state
rows_list_new.append(row)
columns = column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
def parseQaaninKol_SearchQanonTitle(elastic, file_excel, file_log, sheet_name=0, result_path = ""):
# df = pd.read_excel(file_excel, sheet_name=0, header=None)
df = pd.read_excel(file_excel, sheet_name=sheet_name)
count = 0
rows_list = df.to_dict(orient='records')
total = len(rows_list)
print('total : ', total)
column_names = df.columns.tolist()
print(column_names)
id_index=30
try:
id_index = column_names.index("_id")
except ValueError:
id_index = len(column_names)
column_names.append("_id")
error_index=30
try:
error_index = column_names.index("error")
except ValueError:
error_index = len(column_names)
column_names.append("error")
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=0
row_number = 0
try:
for row in rows_list:
if sheet_name == 0 :
qanon_title = row[column_names[4]]
ts_date = row[column_names[6]]
else :
qanon_title = row[column_names[4]]
ts_date = row[column_names[5]]
row_number = row_number + 1
qanon_id = 0
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
state='قانون-جستجو'
qanon_id = 0
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
else :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score < 90 :
qanon_title = get_qanon_title_sample(qanon_title, False)
qanon_title, ts_date, ts_ref = get_qanon_date(qanon_title)
if ts_date or ts_ref :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score == 80 :
state = 'عنوان-تکراری'
elif score < 80 :
dic_error_qanon_title[qanon_title]= str(count) + ' - ' + str(row_number)
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row["_id"]=qanon_id
row["error"]=state
rows_list_new.append(row)
columns = column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_'+str(sheet_name+1) + '_result.xlsx')
new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
def convertField(name ):
base_items = [
{"type": "ابلاغ به رئیس جمهور", "order": 1},
{"type": "توشیح و امضاء قانون", "order": 2},
{"type": "ابلاغ به مجریان", "order": 3},
{"type": "ارسال به روزنامه رسمی", "order": 4},
{"type": "انتشار در روزنامه رسمی", "order": 5},
]
res_type=""
res_order=0
col=""
if name == "شماره":
col= "number"
elif name == "تاریخ اعلام نظر":
col="date"
elif name == "متن نظریه":
col="content"
elif name == "تاریخ ابلاغ به رئیس جمهور":
res_type=base_items[0]["type"]
res_order=base_items[0]["order"]
col="date"
elif name == "شماره ابلاغ به رئیس جمهور":
res_type=base_items[0]["type"]
res_order=base_items[0]["order"]
col="number"
elif name == "تاریخ توشیح و امضا قانون":
res_type=base_items[1]["type"]
res_order=base_items[1]["order"]
col="date"
elif name == "تاریخ ابلاغ به مجریان":
res_type=base_items[2]["type"]
res_order=base_items[2]["order"]
col="date"
elif name == "شماره ابلاغ به مجریان":
res_type=base_items[2]["type"]
res_order=base_items[2]["order"]
col="number"
elif name == "تاریخ ارسال به روزنامه رسمی":
res_type=base_items[3]["type"]
res_order=base_items[3]["order"]
col="date"
elif name == "شماره ارسال به روزنامه رسمی":
res_type=base_items[3]["type"]
res_order=base_items[3]["order"]
col="number"
elif name == "تاریخ انتشار در روزنامه رسمی":
res_type=base_items[4]["type"]
res_order=base_items[4]["order"]
col="date"
elif name == "شماره انتشار در روزنامه رسمی":
res_type=base_items[4]["type"]
res_order=base_items[4]["order"]
col="number"
# elif name == "تاریخ نظریه شورای نگهبان":
# col="date"
# elif name == "شماره نظریه شورای نگهبان":
# col="number"
# elif name == "مغایرت نظریه شورای نگهبان":
# col="content"
# elif name == "استمحالی":
# col=""
# elif name == "استنکافی":
# col=""
# elif name == "دستگاههای اجرایی مرتبط":
# col=""
return col, res_type, res_order
def getDictBeforeInfos(file_excel, sheet_name):
df = pd.read_excel(file_excel, sheet_name=sheet_name)
rows_list = df.to_dict(orient='records')
total = len(rows_list)
print('total : ', total)
column_names = df.columns.tolist()
result={}
try:
for row in rows_list:
row_id = row[column_names[0]]
if sheet_name == 1 : # eblagh
letters = []
letters_dict = {}
for col in column_names:
name, type, order = convertField(col)
if name != '' :
if order not in letters_dict :
letters.append({"order":order, "type":type})
letters_dict[order] = len(letters)-1
index = letters_dict[order]
letters[index][name] = row[col]
elif col == "استمحالی" or name == "استنکافی":
pass
elif col == "دستگاههای اجرایی مرتبط":
result["exceuter_organs"] = row[col]
except Exception as e:
# file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
pass
return result
def parseBeforeInfos_SendData(elastic, file_excel, file_log, result_path = ""):
# df = pd.read_excel(file_excel, sheet_name=0, header=None)
df_main = pd.read_excel(file_excel, sheet_name=0)
count = 0
rows_list = df_main.to_dict(orient='records')
total = len(rows_list)
print('total : ', total)
column_names = df_main.columns.tolist()
print(column_names)
id2_index = column_names.index("_id2")
id3_index = column_names.index("_id3")
id_index = column_names.index("_id")
if not id_index :
id_index = len(column_names)
column_names.append("_id")
error_index = column_names.index("error")
if not error_index :
error_index = len(column_names)+1
column_names.append("error")
file = open(file_log, 'w+', encoding='utf8')
dict_qanon_id = get_dict_qanon_title("qanon_title_ids.txt")
# Print the list of rows
dic_error_qanon_title={}
dic_error_section_title={}
rows_list_new = []
bulk_data = []
total_count=0
row_number = 0
try:
for row in rows_list:
row_id = row[column_names[0]]
qanon_title = row[column_names[1]]
# print(qanon_title)
ts_date = row[column_names[3]]
_id2 = ''
_id3 = ''
if id2_index :
_id2 = row[column_names[id2_index]]
if id3_index :
_id3 = row[column_names[id3_index]]
# print(ts_date)
row_number = row_number + 1
qanon_id = 0
count = count + 1
if (count % 10) == 0 :
print("%s, %.2f " % ( '================== ', (count / total) * 100 if total > 0 else 0))
qanon_title = text_normalizer.normalize_search_qanon(qanon_title)
# جداسازی اعداد چسبیده به کلمات قبل یا بعد مثل
# قانون بودجه سال 1369کل کشور
qanon_title = re.sub(r"([^\/])(\d+)([\u0600-\u06FF\u0750-\u077F]+?)", r"\1\2 \3", qanon_title)
score = 100
state='قانون-جستجو'
qanon_id = 0
# ابتدا از قانونهای خاص که شناسه ذخیره شده دارند جستجو کند
if qanon_title in dict_qanon_id :
score = 100
qanon_id = dict_qanon_id[qanon_title]
state = 'قانون-دستی'
# if qanon_id == 0 :
# continue # این قانون در بانک ما وجود ندارد
# اگر پیدا نشد، از الاستیک جستجو کند
else :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
# اگر قابل اطمینان نبود، خطا ثبت کند
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score < 90 :
qanon_title = get_qanon_title_sample(qanon_title, False)
qanon_title, ts_date, ts_ref = get_qanon_date(qanon_title)
if ts_date or ts_ref :
qanon_id, score, item = searchQanonId(elastic, qanon_title, ts_date, "mj_qa_qanon")
if score < 90 :
qanon_id, score, item = searchQanonTitleOfContent(elastic, qanon_title, ts_date)
if score < 90 :
if _id3 :
qanon_id=_id3
state = 'دستی-مجلس'
elif score == 80 :
state = 'عنوان-تکراری'
elif score < 80 :
dic_error_qanon_title[qanon_title]= str(count) + ' - ' + str(row_number)
print('-'*10 , str(count) , ' qanon error', qanon_title )
file.write('---- qanon error ---' + str(count) + ' ----- ' + qanon_title + '\n')
qanon_id = 0
state = 'خطا-قانون'
# ذخیره شناسه ها و وضعیت برای اکسل جدید
row["_id"]=qanon_id
row["error"]=state
rows_list_new.append(row)
columns = column_names
new_df = pd.DataFrame(rows_list_new, columns=columns)
if result_path == '' :
directory_path = os.path.dirname(file_excel)
result_path = directory_path + "/result/"
file_name = os.path.basename(file_excel)
file_excel2 = result_path + file_name.replace('.xlsx', '_result.xlsx')
new_df.to_excel(file_excel2, index=False, engine='openpyxl')
except Exception as e:
file.write('----Exception error ---' + str(count) + ' ***' + str(e) + '\n')
file.close()
file_log1= file_log.replace(".txt", "_1.txt")
with open(file_log1, 'w', encoding='utf8') as file1:
file1.write(json.dumps(dic_error_qanon_title, ensure_ascii=False, indent=4))
# ---------------------------------------------------------
# ---------------------------------------------------------
load_dotenv(dotenv_path='config.env')
# host=os.getenv('HOST_160')
# password=os.getenv('HOST_160_PASS')
# host=os.getenv('HOST_112')
# password=os.getenv('HOST_112_PASS')
host=os.getenv('HOST_113')
password=os.getenv('HOST_113_PASS')
print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# ---------------------------------------------------------
# ---------------------------------------------------------
# parseBeforeInfos_SearchQanonTitle(elastic, "./data/جداول بانک قوانین_info-شناسه قانون یار.xlsx" , "./data/result/پیشا قانون.txt", "./data/result/")
#parseQaaninKol_SearchQanonTitle(elastic, "./data/فهرست تمام قوانین.xlsx", "./data/result/فهرست 1 تمام قوانین.txt", 0, "./data/result/")
#parseQaaninKol_SearchQanonTitle(elastic, "./data/فهرست تمام قوانین.xlsx", "./data/result/فهرست 2 تمام قوانین.txt", 1, "./data/result/")
# ---------------------------------------------------------
# ---------------------------------------------------------
parseBeforeInfos_SendData(elastic, "./data/جداول بانک قوانین_info-شناسه قانون یار.xlsx" , "./data/result/پیشا قانون.txt", "./data/result/")
qanon_title=" قانون الحاق دو تبصره به عنوان تبصره های 3 و 4 به ماده 9 قانون روابط موجر و مستأجر مصوب 1362.2.13"
ts_data="1369/07/08"
# qanon_title = get_qanon_title_sample(qanon_title, False)
# print(get_qanon_date(qanon_title))
# searchQanonId(elastic, qanon_title, ts_data)
# searchQanonTitleOfContent(elastic, qanon_title, ts_data)
+170
View File
@@ -0,0 +1,170 @@
import os
from dotenv import load_dotenv
import json
import requests
import pyodbc
import requests
from bs4 import BeautifulSoup
from html import escape
import json
from decimal import Decimal
import datetime
import time
from app.common.config_base import *
from app.common.general_functions import *
from app.common.text_normalizer import TextNormalizer
from app.common.elastic_helper import ElasticHelper
##--------------------------------
# لازم است این فیلد پرشود تا مجلس بتواند دسترسی تغییر داشته باشد
##------------------------------------
def fill_doc_state( elastic, index_name_i, index_name_o, file_log) :
body = {
"sort": [
{"qanon_id": {"order": "asc"}},
{"child_order": {"order": "asc"}}
]
}
try:
list = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
count = 0
text_normal = TextNormalizer()
result = {}
result_new = {}
total_count = 0
bulk_data = []
bulk_data_section = []
t1= datetime.datetime.now()
print(t1)
file = open(file_log, 'a+', encoding='utf8')
i = 0
doc_tags=[]
qanon_id=0
prev_qanon_id = 0
siyasatha_list = ["qq85859", "qq260090", "qq121403", "qq222873", "qq198729", "qq121413", "qq118359", "qq305009", "qq118373", "qq286578"]
for mentry in list:
entry = mentry["source"]
id = entry.get("id", "")
qanon_id = entry.get("qanon_id", "")
qanon_title = entry.get("qanon_title", "")
nlp_tags = entry.get("nlp_tags", [])
ref_state = entry.get("ref_state", [])
# title_type = entry.get("title_type", "عادی")
title_type = getTitleType(qanon_title)
if prev_qanon_id == 0 :
prev_qanon_id = qanon_id
elif prev_qanon_id != qanon_id :
data={
'_id':prev_qanon_id,
'_source' : {
'doc_tags': doc_tags
}
}
body = {
"script": {
"source": "ctx._source.doc_tags=params.doc_tags",
"lang": "painless",
"params" : { 'doc_tags' : doc_tags }
},
"query": {
"term": {
"qanon_id": { "value" : prev_qanon_id }
}
}
}
elastic.updateByQueryIndex(index_name_i, body)
bulk_data.append(data)
doc_tags=[]
if len(ref_state) > 0 :
if "مهذب" not in doc_tags :
doc_tags.append("مهذب")
elif title_type not in ["عادی", "اصلی", "موافقتنامه", "بودجه"] :
if "تبعی" not in doc_tags :
doc_tags.append("تبعی")
elif title_type in ["عادی", "اصلی", "موافقتنامه", "بودجه"] :
if "اصلی" not in doc_tags :
doc_tags.append("اصلی")
if qanon_id in siyasatha_list :
if "سیاستهای کلی" not in doc_tags :
doc_tags.append("سیاستهای کلی")
if "qanon_usefull" in nlp_tags :
if "پرکاربرد" not in doc_tags :
doc_tags.append("پرکاربرد")
prev_qanon_id = qanon_id
i=i+1
if len(bulk_data) >= 10:
total_count += len(bulk_data)
print('=' * 5, 'law_section ===', ', total='+str(total_count) , str(i)+ ', id=' + qanon_id)
elastic.updateBulkList(bulk_data, index_name_o)
bulk_data = []
if prev_qanon_id != 0:
data={
'_id':prev_qanon_id,
'_source' : {
'doc_tags': doc_tags
}
}
body = {
"script": {
"source": "ctx._source.doc_tags=params.doc_tags",
"lang": "painless",
"params" : { 'doc_tags' : doc_tags }
},
"query": {
"term": {
"qanon_id": { "value" : prev_qanon_id }
}
}
}
elastic.updateByQueryIndex(index_name_i, body)
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=' + qanon_id )
elastic.updateBulkList(bulk_data, index_name_o)
file.close()
print('end success import_law_section_to_elastic')
t2= datetime.datetime.now()
print(t2-t1)
load_dotenv(dotenv_path='config.env')
host=os.getenv('HOST_160')
password=os.getenv('HOST_160_PASS')
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
# print(dict_effected_sections)
# try:
# item = elastic.get_doctument("mj_qa_section", "3223423")
# except Exception as e:
# print(e)
# print(type(e).__name__)
# print(str(e))
fill_doc_state( elastic, "mj_qa_section", "mj_qa_qanon", "./output/log_r1.txt")
+362
View File
@@ -0,0 +1,362 @@
import os
from dotenv import load_dotenv
from app.common.text_normalizer import TextNormalizer
# from general import *
from app.common.general_functions import *
from app.common.elastic_helper import ElasticHelper
load_dotenv(dotenv_path='config.env')
host=os.getenv('HOST_160')
password=os.getenv('HOST_160_PASS')
# host=os.getenv('HOST_112')
# password=os.getenv('HOST_112_PASS')
# host=os.getenv('HOST_60')
# password=os.getenv('HOST_60_PASS')
# host=os.getenv('HOST_80')
# password=os.getenv('HOST_80_PASS')
print(host)
# print(password)
path_base_map = "G:/Project2/gateway2_main/repo/_other/"
elastic = ElasticHelper(host, password, "elastic", path_base_map)
elastic.createIndex("gn_log_action", '', "gn_log_action" )
def meta_to_meta_action(elastic, index_name_i, index_name_o):
try:
try:
body={}
list_data = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
lst = list(list_data)
index = 0
percent_prev = 0
# text_normal = TextNormalizer()
prev_user_id = 0
prev_content = ''
prev_data={}
update = False
for mentry in lst:
#print(mentry)
index += 1
percent = int((index / len(lst)) * 100)
if percent != percent_prev:
print("progress -> %.2f %%" % percent)
percent_prev = percent
id = mentry["id"]
entry = mentry["source"]
meta = entry.get("meta", [])
meta_action={}
for m in meta:
meta_action[m["key"]] = m["value"]
data = entry
data["meta_action"]= meta_action
eid = id
try:
resp = elastic.update_index_doc(update, index_name_o, eid, data)
except Exception as e:
save_error(id, e)
except Exception as e:
save_error(id, e)
def refactorLogSearch(elastic, index_name_i, index_name_o):
try:
try:
body={
"sort":{
"userid": {"order": "asc"},
"query_String.keyword": {"order": "asc"},
"time": {"order": "desc"}
}
}
list_data = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
lst = list(list_data)
index = 0
percent_prev = 0
# text_normal = TextNormalizer()
prev_user_id = 0
prev_content = ''
prev_data={}
update = False
for mentry in lst:
#print(mentry)
index += 1
percent = int((index / len(lst)) * 100)
if percent != percent_prev:
print("progress -> %.2f %%" % percent)
percent_prev = percent
id = mentry["id"]
entry = mentry["source"]
user_id = entry.get("userid", "")
content = entry.get("query_String", "").strip()
if not content :
continue
content = content.strip("\", ")
id_click = entry.get("id_click", "")
time_edit = round(float(entry.get("time", ""))/1000)
ip = entry.get("id", "")
facet = entry.get("facet", "")
os_version = entry.get("os_version", "")
browser = entry.get("browser", "")
action_key = "normal"
ref_key="none"
values=[]
meta={}
if id_click :
value ={
"id" : id_click,
"type": "click",
"value": 1
}
values.append(value)
meta["ip"] = ip
if facet :
meta["filter"] = facet
if browser :
meta["browser"] = browser
if os_version :
meta["os"] = os_version
if prev_user_id == user_id and prev_content == content :
values = prev_data["values"]
if id_click :
founded = False
i = 0
for value in values :
if value["id"] == id_click :
founded = True
value["value"] = value["value"] + 1
values[i] = value
break
i +=1
if not founded :
values.append(
{
"id" : id_click,
"type": "click",
"value": 1
})
prev_data["values"] = values
continue
elif prev_data and prev_data["id"] :
eid = prev_data["id"]
try:
resp = elastic.update_index_doc(update, index_name_o, eid, prev_data)
except Exception as e:
save_error(id, e)
prev_data = {}
data = {}
data["id"]= id
data["content"]= content
data["user_id"]= user_id
data["time_edit"]= time_edit
data["action_key"]= action_key
data["ref_key"]= ref_key
data["values"]= values
data["meta_action"]= meta
prev_data = data
prev_user_id = user_id
prev_content = content
if prev_data :
eid = prev_data["id"]
try:
resp = elastic.update_index_doc(update, index_name_o, eid, prev_data)
except Exception as e:
save_error(id, e)
except Exception as e:
save_error(id, e)
def refactorLogSearch_0(elastic, index_name_i, index_name_o):
try:
try:
body={
"sort":{
"userid": {"order": "asc"},
"query_String.keyword": {"order": "asc"},
"time": {"order": "desc"}
}
}
list_data = elastic.es_iterate_all_documents(index_name_i, body)
except Exception as e:
save_error(0, e)
lst = list(list_data)
index = 0
percent_prev = 0
# text_normal = TextNormalizer()
prev_user_id = 0
prev_content = ''
prev_data={}
update = False
for mentry in lst:
#print(mentry)
index += 1
percent = int((index / len(lst)) * 100)
if percent != percent_prev:
print("progress -> %.2f %%" % percent)
percent_prev = percent
id = mentry["id"]
entry = mentry["source"]
user_id = entry.get("userid", "")
content = entry.get("query_String", "").strip()
if not content :
continue
content = content.strip("\", ")
id_click = entry.get("id_click", "")
time_edit = round(float(entry.get("time", ""))/1000)
ip = entry.get("id", "")
facet = entry.get("facet", "")
os_version = entry.get("os_version", "")
browser = entry.get("browser", "")
action_key = "normal"
ref_key="none"
values=[]
meta=[]
if id_click :
value ={
"id" : id_click,
"type": "click",
"value": 1
}
values.append(value)
ip_obj ={
"key" : "ip",
"value": ip
}
meta.append(ip_obj)
if facet :
m ={
"key" : "filter",
"value": facet
}
meta.append(m)
if browser :
m ={
"key" : "browser",
"value": browser
}
meta.append(m)
if os_version :
m ={
"key" : "os",
"value": os_version
}
meta.append(m)
if prev_user_id == user_id and prev_content == content :
values = prev_data["values"]
if id_click :
founded = False
i = 0
for value in values :
if value["id"] == id_click :
founded = True
value["value"] = value["value"] + 1
values[i] = value
break
i +=1
if not founded :
values.append(
{
"id" : id_click,
"type": "click",
"value": 1
})
prev_data["values"] = values
continue
elif prev_data and prev_data["id"] :
eid = prev_data["id"]
try:
resp = elastic.update_index_doc(update, index_name_o, eid, prev_data)
except Exception as e:
save_error(id, e)
prev_data = {}
data = {}
data["id"]= id
data["content"]= content
data["user_id"]= user_id
data["time_edit"]= time_edit
data["action_key"]= action_key
data["ref_key"]= ref_key
data["values"]= values
data["meta"]= meta
prev_data = data
prev_user_id = user_id
prev_content = content
if prev_data :
eid = prev_data["id"]
try:
resp = elastic.update_index_doc(update, index_name_o, eid, prev_data)
except Exception as e:
save_error(id, e)
except Exception as e:
save_error(id, e)
#refactorLogSearch(elastic, "gn_log_search", "gn_log_action")
meta_to_meta_action(elastic, "gn_log_action", "gn_log_action")