Ejemplo n.º 1
0
def import_coll_to_server():
    # chuyển collection từ local lên server
    a = list(coll_the.find())
    serverdb = create_connect_to_mongo(database='CleanData')
    # query= list(db['the_tin_dung'].find())
    coll_the_server = serverdb['cic_the_tin_dung']
    coll_the_server.insert_many(a)
Ejemplo n.º 2
0
def check_sum():
    #connect mongo
    db_cic = create_connect_to_mongo(locahost=True, database='cic')
    coll_the = db_cic['the_tin_dung_clean']
    query = coll_the.find({}, {'_id': 1})
    x = list()
    for a in query:
        x.append(a['_id'])
    with open(
            r'C:\nam\work\learn_tensorflow\credit\output\pickle\the_all_id.pickle',
            'wb') as f:
        pickle.dump(header_full, f)
    with open(
            r'C:\nam\work\learn_tensorflow\credit\output\pickle\header_full.pickle',
            'rb') as f:
        header_full = pickle.load(f)
    list_file = header_full[
        'BÁO CÁO THÔNG TIN THẺ TÍN DỤNG (Khách hàng Thể nhân) '] + header_full[
            'BÁO CÁO THÔNG TIN THẺ TÍN DỤNG (Khách hàng là Thể nhân)  '] + header_full[
                'BÁO CÁO THÔNG TIN THẺ TÍN DỤNG CÁ NHÂN  ']

    path = r'C:\Users\Windows 10 TIMT\OneDrive\Nam\OneDrive - Five9 Vietnam Corporation\work\data_input\credit\input 2014 redit\thong_tin_the'
    list_vay4 = [
        os.path.join(root, name) for root, dirs, files in os.walk(path)
        for name in files if name.endswith(".html")
    ]
    x_mongo = list_vay4 + x
    other = [x for x in list_file if x not in x_mongo]
Ejemplo n.º 3
0
def run_call_api():
    db = create_connect_to_mongo(database='cic', locahost=True)
    # query= list(db['the_tin_dung'].find())
    coll_cus = db['customer']
    # coll_cus.update_many({},{'$unset': {'address_new':1}})
    # query những document mà không có trường address_new (chú ý nếu cần thì có thể query những thằng có address_new.address = null)
    # query = list(coll_cus.find({'address_new':{'$exists':0}},{'address':1}))
    query = list(
        coll_cus.find(
            {
                'address_new': {
                    '$exists': 1
                },
                'address_new.address': None
            }, {
                'address_new': 1,
                'address': 1
            }))

    list_id = [a['_id'] for a in query]
    coll_cus_name = 'customer'
    lock = Lock()
    processes = [
        Process(target=call_api_address, args=(list_file, lock, coll_cus_name))
        for i, list_file in enumerate(split_list_to_N_equal_element(
            list_id, 5))
    ]
    for proc in processes:
        proc.start()
    for proc in processes:
        proc.join()
Ejemplo n.º 4
0
def create_coll_customer():

    db = create_connect_to_mongo(database='cic', locahost=True)
    # query= list(db['the_tin_dung'].find())
    coll_the = db['the_tin_dung_clean']
    pipeline = [
        {
            "$unwind": {
                "path": "$thong_tin_nhan_dang.phone.mobi_phone",
                'preserveNullAndEmptyArrays': True
            }
        },
        {
            "$unwind": {
                "path": "$thong_tin_nhan_dang.phone.fixed_phone",
                'preserveNullAndEmptyArrays': True
            }
        },
        {
            "$group": {
                "_id": "$thong_tin_nhan_dang.cic_id",
                "CMND": {
                    "$addToSet": "$thong_tin_nhan_dang.CMND"
                },
                "name": {
                    "$addToSet": "$thong_tin_nhan_dang.name"
                },
                "address": {
                    "$addToSet": "$thong_tin_nhan_dang.address"
                },
                # "mobi_phone": {"$addToSet": {"$each":"$thong_tin_nhan_dang.phone.mobi_phone"}},
                # "fixed_phone": {"$addToSet":{"$each":"$thong_tin_nhan_dang.phone.fixed_phone"}},
                "mobi_phone": {
                    "$addToSet": "$thong_tin_nhan_dang.phone.mobi_phone"
                },
                "fixed_phone": {
                    "$addToSet": "$thong_tin_nhan_dang.phone.fixed_phone"
                },
                "header": {
                    "$addToSet": "$thong_tin_nhan_dang.header"
                },
                "time_query": {
                    "$addToSet": "$thong_tin_nhan_dang.time_query"
                },
            }
        },
        {
            "$out": 'customer'
        }
    ]
    coll_the.aggregate(pipeline, allowDiskUse=True)
Ejemplo n.º 5
0
def clean_vay_part2():
    db = create_connect_to_mongo(database='cic', locahost=True)
    # query= list(db['the_tin_dung'].find())
    coll_the = db['vay_clean']
    bulk = coll_the.initialize_ordered_bulk_op()
    batch_number = 1000
    query = coll_the.find({'1_thong_tin_nhan_dang.time_query': {"$exists": 1}})
    counter = 0
    for doc in query:
        # a = list(query)
        # doc  = a[-3]
        # khởi tạo giá trị đầu tiên cho mỗi vòng lặp để đảm bảo k update giá trị trước của vòng lặp
        new_time = None
        time_query = doc['1_thong_tin_nhan_dang'].get('time_query')
        # time_query = '06/04/2015'
        try:
            if time_query is not None:
                time_query = time_query.split('-')[-1]
                time_query_split = [
                    int(a) if a.isdigit() else int(a[-2:])
                    for a in time_query.split('/')
                ]
                new_time = datetime.datetime(time_query_split[-1],
                                             time_query_split[-2],
                                             time_query_split[0])
                # bulk.find({'_id':doc['_id']}).update_one({"$set":{'thong_tin_nhan_dang.time_query':new_time}})
            if new_time is not None:
                bulk.find({
                    '_id': doc['_id']
                }).update_one({
                    "$set": {
                        'thong_tin_nhan_dang.time_query_correct': new_time
                    }
                })
            counter += 1
            if counter % batch_number == 0:  # update sau khi duyet 1000 document
                try:
                    bulk.execute()
                    # print('update thanh cong')
                    bulk = coll_the.initialize_ordered_bulk_op()
                except Exception as error:
                    print(error)
        except Exception as e:
            print(e)
    if counter % batch_number != 0:  # chạy batch cho phần còn lại (mà không chia hết cho batch_number)
        try:
            bulk.execute()
            # print('update thanh cong')
        except Exception as error:
            print(error)
Ejemplo n.º 6
0
def clean_the_tin_dung_part1():
    #clean database the tin dung
    db = create_connect_to_mongo(database='cic', locahost=True)
    # query= list(db['the_tin_dung'].find())
    coll_the = db['the_tin_dung_clean']

    coll_the.update_many({}, {
        '$rename': {
            '1.2. Thông tin về tổ chức phát hành thẻ ':
            'thong_tin_to_chuc_phat_hanh_the'
        }
    })
    coll_the.update_many(
        {}, {'$rename': {
            '1.3. Thông tin tài sản đảm bảo': 'thong_tin_tsdb'
        }})
    coll_the.update_many({}, {
        '$rename': {
            '2.1. Thông tin về số tiền thanh toán thẻ của chủ thẻ ':
            'thong_tin_so_tien_thanh_toan_chu_the'
        }
    })
    coll_the.update_many({}, {
        '$rename': {
            '2.2.2. Từ 15/8/2013 đến nay ': 'lich_su_cham_thanh_toan_sau_2013'
        }
    })
    coll_the.update_many({}, {
        '$rename': {
            '2.3 Tình hình thanh toán thẻ của chủ thẻ ':
            'tinh_hinh_cham_thanh_toan'
        }
    })

    #xóa column ''tinh_hinh_cham_thanh_toan''
    coll_the.update_many({'tinh_hinh_cham_thanh_toan': {
        '$exists': 1
    }}, {"$unset": {
        'tinh_hinh_cham_thanh_toan': 1
    }})
Ejemplo n.º 7
0
def clean_the_tin_dung_part2():
    # clean date  trong the tin dung
    db = create_connect_to_mongo(database='cic', locahost=True)
    # query= list(db['the_tin_dung'].find())
    coll_the = db['the_tin_dung_clean']
    bulk = coll_the.initialize_ordered_bulk_op()
    batch_number = 1000
    query = coll_the.find({'thong_tin_nhan_dang.time_query': {
        "$exists": 1
    }}, {'thong_tin_nhan_dang': 1})
    counter = 0
    for doc in query:
        # a = list(query)
        # doc  = a[-3]
        # khởi tạo giá trị đầu tiên cho mỗi vòng lặp để đảm bảo k update giá trị trước của vòng lặp
        new_time = None
        mobi_phone = None
        fixed_phone = None
        time_query = doc['thong_tin_nhan_dang'].get('time_query')
        try:
            if time_query is not None:
                time_query_split = [
                    int(a) for a in time_query.split('/') if a.isdigit()
                ]
                new_time = datetime.datetime(time_query_split[-1],
                                             time_query_split[-2],
                                             time_query_split[0])
                # bulk.find({'_id':doc['_id']}).update_one({"$set":{'thong_tin_nhan_dang.time_query':new_time}})
            phone_raw = doc['thong_tin_nhan_dang'].get('phone_number')
            # phone_raw = '0915400120 0437472828'
            if phone_raw is not None:
                dict_phone = apply_clean_phone_number(phone_raw)
                if dict_phone is not None:
                    mobi_phone = dict_phone.get('mobile phone')
                    fixed_phone = dict_phone.get('fixed phone')
            # bulk.find({'_id':doc['_id']}).update_one({"$set":{
            #     'thong_tin_nhan_dang.time_query_correct':new_time,
            #     'thong_tin_nhan_dang.phone.mobi_phone':mobi_phone,
            #     'thong_tin_nhan_dang.phone.fixed_phone':fixed_phone}})
            if new_time is not None:
                bulk.find({
                    '_id': doc['_id']
                }).update_one({
                    "$set": {
                        'thong_tin_nhan_dang.time_query_correct': new_time
                    }
                })
            if mobi_phone is not None:
                bulk.find({
                    '_id': doc['_id']
                }).update_one({
                    "$set": {
                        'thong_tin_nhan_dang.phone.mobi_phone': mobi_phone
                    }
                })
            if fixed_phone is not None:
                bulk.find({
                    '_id': doc['_id']
                }).update_one({
                    "$set": {
                        'thong_tin_nhan_dang.phone.fixed_phone': fixed_phone
                    }
                })
            counter += 1
            if counter % batch_number == 0:  # update sau khi duyet 1000 document
                try:
                    bulk.execute()
                    # print('update thanh cong')
                    bulk = coll_the.initialize_ordered_bulk_op()
                except Exception as error:
                    print(error)
        except Exception as e:
            print(e)
    if counter % batch_number != 0:  # chạy batch cho phần còn lại (mà không chia hết cho batch_number)
        try:
            bulk.execute()
            # print('update thanh cong')
        except Exception as error:
            print(error)
    correct_key_3_tong_du_no_tin_dung(coll_the)
Ejemplo n.º 8
0
def clean_vay_part1():
    # clean vay
    db = create_connect_to_mongo(database='cic', locahost=True)
    # query= list(db['the_tin_dung'].find())
    coll_vay = db['vay_clean']

    # check key
    field_all = check_unique_key(coll_vay)
    pd.DataFrame(field_all).to_clipboard()

    #rename key : 1.1. Thông tin nhận dạng => 1_1_thong_tin_nhan_dang
    # list_dict_

    coll_vay.update_many({}, {
        '$rename': {
            '1. THÔNG TIN CHUNG VỀ KHÁCH HÀNG   ': '1_thong_tin_nhan_dang'
        }
    })

    # get những subkey của primary key : "1_1_thong_tin_nhan_dang"
    distinctThingFields = check_unique_key(coll_vay, '1_thong_tin_nhan_dang')

    # đối những subkey trong primary key 1_1_thong_tin_nhan_dang có tên gần giống nhau thành 1 tên thống nhất
    #rename key : 1_1_thong_tin_nhan_dang.Mã số CIC: => 1_1_thong_tin_nhan_dang.Mã CIC:
    coll_vay.update_many({}, {
        '$rename': {
            '1_thong_tin_nhan_dang.Mã số CIC:': '1_thong_tin_nhan_dang.cic_id'
        }
    })
    update_key_with_regex(collection=coll_vay,
                          regex_sub_key=re.compile('chứng minh nhân dân'),
                          new_key='phone_number',
                          primary_key='1_thong_tin_nhan_dang')
    update_key_with_regex(collection=coll_vay,
                          regex_sub_key=re.compile('Tên khách hàng'),
                          new_key='name_customer',
                          primary_key='1_thong_tin_nhan_dang')
    update_key_with_regex(coll_vay, re.compile('ịa chỉ'), 'address',
                          '1_thong_tin_nhan_dang')

    coll_vay.update_many({}, {
        '$rename': {
            '2.1 Tổng hợp dư nợ hiện tại': '2_1_tong_hop_du_no_hien_tai'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            '2.2 Danh sách Tổ chức tín dụng đang quan hệ ':
            '2_2_danh_sach_TCTD_quan_he'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            '2.2 Danh sách Tổ chức tín dụng đã từng quan hệ ':
            '2_2_danh_sach_TCTD_quan_he'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            '2.2.	Chi tiết về nợ vay (không bao gồm nợ thẻ tín dụng)':
            '2_2_chi_tiet_vay_no'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            '2.3 Tình trạng dư nợ tín dụng hiện tại': '2_2_chi_tiet_vay_no'
        }
    })

    coll_vay.update_many({}, {
        '$rename': {
            '2.3 Thông tin Thẻ tín dụng và dư nợ thẻ tín dụng':
            '2_3_thong_tin_the_tin_dung'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            ' 2.4 Lịch sử nợ xấu 5 năm gần nhất ': '2_4_lich_su_no_nau_5_nam'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            ' 2.4 Lịch sử nợ xấu 5 năm gần nhất  ': '2_4_lich_su_no_nau_5_nam'
        }
    })
    update_key_with_regex(collection=coll_vay,
                          regex_sub_key=re.compile('VAMC'),
                          new_key='du_no_thuoc_VAMC')

    coll_vay.update_many({}, {
        '$rename': {
            ' 2.5 Nợ cần chú ý trong vòng 12 tháng gần nhất ':
            '2_5_no_can_chu_y_trong_12_thang'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            ' 2.5 Nợ cần chú ý trong vòng 12 tháng gần nhất  ':
            '2_5_no_can_chu_y_trong_12_thang'
        }
    })

    coll_vay.update_many({}, {
        '$rename': {
            ' 2.8. Nợ cần chú ý trong vòng 12 tháng gần nhất ':
            '2_8_no_can_chu_y_12_thang'
        }
    })

    coll_vay.update_many({}, {
        '$rename': {
            '  2.6.	Lịch sử nợ xấu tín dụng trong 05 năm gần nhất ':
            '2_6_lich_su_no_xau_5_nam'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            ' 2.6.	Lịch sử nợ xấu tín dụng trong 05 năm gần nhất ':
            '2_6_lich_su_no_xau_5_nam'
        }
    })

    coll_vay.update_many({}, {
        '$rename': {
            '2.7.	Lịch sử chậm thanh toán thẻ tín dụng trong 03 năm gần nhất':
            '2_7_lich_su_cham_thanh_toan_3_nam'
        }
    })

    coll_vay.update_many({}, {
        '$rename': {
            '3. DANH SÁCH TCTD TRA CỨU THÔNG TIN QUAN HỆ TÍN DỤNG CỦA KHÁCH HÀNG (trong 1 năm gần nhất)':
            '3_danh_sach_tctd_tra_cuu'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            '3. DANH SÁCH TCTD TRA CỨU THÔNG TIN QUAN HỆ TÍN DỤNG CỦA KHÁCH HÀNG (trong 1 năm gần nhất) ':
            '3_danh_sach_tctd_tra_cuu'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            '3.3. DANH SÁCH TCTD TRA CỨU THÔNG TIN QUAN HỆ TÍN DỤNG CỦA KHÁCH HÀNG (trong 1 năm gần nhất)':
            '3_danh_sach_tctd_tra_cuu'
        }
    })

    coll_vay.update_many({}, {
        '$rename': {
            '3.1 Thông tin về tài sản đảm bảo': '3_1_thong_tin_tsdb'
        }
    })

    coll_vay.update_many({}, {
        '$rename': {
            '3.2 Thông tin về hợp đồng tín dụng':
            '3_2_thong_tin_hop_dong_tin_dung'
        }
    })
    coll_vay.update_many({}, {
        '$rename': {
            '3.2 Thông tin về hợp đồng tín dụng ':
            '3_2_thong_tin_hop_dong_tin_dung'
        }
    })

    # Xoa field .đa số các giá trị của 2.2 Lịch sử chậm thanh toán thẻ của chủ thẻ đều có 2 bảng sub ở trong, nên ta sẽ k cần key này nữa
    coll_vay.update_many(
        {'2.1 Diễn biến dư nợ 12 tháng gần nhất': {
            '$exists': 1
        }}, {"$unset": {
            '2.1 Diễn biến dư nợ 12 tháng gần nhất': 1
        }})
    coll_vay.update_many(
        {'2.1 Diễn biến dư nợ 12 tháng gần nhất ': {
            '$exists': 1
        }}, {"$unset": {
            '2.1 Diễn biến dư nợ 12 tháng gần nhất ': 1
        }})
    coll_vay.update_many(
        {'2.5. Diễn biến dư nợ 12 tháng gần nhất': {
            '$exists': 1
        }}, {"$unset": {
            '2.5. Diễn biến dư nợ 12 tháng gần nhất': 1
        }})
    coll_vay.update_many(
        {'2.5. Diễn biến dư nợ 12 tháng gần nhất ': {
            '$exists': 1
        }}, {"$unset": {
            '2.5. Diễn biến dư nợ 12 tháng gần nhất ': 1
        }})
Ejemplo n.º 9
0
def import_html_to_mongodb(list_file,
                           lock,
                           process_id='1',
                           collection_name='vay'):
    '''
    idea: từ file html, scrape thông tin và import ra mongodb. 
    Dùng được cho cả report vay và report the tin dung, nếu xuất hiện những template khác thì cần thêm những regex cho tên table, và sửa lại case table trong class html_tables
    :param list_file: 
    :param lock: Lock cho multiprocess
    :param process_id:  id cho logger file được tạo ra
    :param collection_name: tên collection trên mongobb
    :return: 
    '''
    # tao logger
    global logger
    logger = logging.getLogger(__name__)
    logger = create_log_file(
        logger,
        logfile=
        r'C:\Users\Windows 10 TIMT\OneDrive\Nam\OneDrive - Five9 Vietnam Corporation\work\data_output\credit\log file\check_index{}'
        .format(process_id),
    )

    #connect mongo
    db_cic = create_connect_to_mongo(locahost=True, database='cic')
    coll_the = db_cic[collection_name]
    # coll_the.remove({})
    #  khai báo  regex cho những table cần lấy thông tin
    # regex cho the
    regex_thong_tin_nhan_dang_card = re.compile("thông tin nhận dạng|1\.1")
    regex_table12_card = re.compile('1\.2')
    #case này có 2 table trong 1 index 2.2
    regex_table22_card = re.compile('Lịch sử chậm thanh toán thẻ của chủ thẻ')
    # regex cho Vay
    regex_thong_tin_nhan_dang_vay = re.compile("THÔNG TIN CHUNG VỀ KHÁCH HÀNG")
    regex_table23_vay = re.compile(
        'Chi tiết về nợ vay (không bao gồm nợ thẻ tín dụng)|Chi tiết về nợ vay|Tình trạng dư nợ tín dụng hiện tại'
    )
    case_table23_vay = 'du_no_hien_tai_BC_VAY'  # giá trị argument khi đọc table html
    regex_table24_vay = re.compile('2\.4|Lịch sử nợ xấu 5 năm gần nhất')
    case_table24_vay = 'lich_su_no_xau_BC_VAY'  # giá trị argument khi đọc table html
    regex_table21_vay = re.compile('2\.1|Tổng hợp dư nợ hiện tại')
    case_table21_vay = 'tong_hop_du_no_21_BC_VAY'  # giá trị argument khi đọc table html

    for full_filename in list_file:
        try:
            input_db = dict()
            # full_filename = r'C:\nam\work\learn_tensorflow\credit\output\pickle\8\229326.html'
            with open(full_filename, encoding='utf-8') as file:
                soup = BeautifulSoup(file, "html.parser")
            #thông tin k nằm trong table nào
            no_number = soup.find(text=re.compile('Số:'))
            header = soup.find('span', attrs={'class': 'headerfont'}).text
            time_query = list(
                soup.find(text=re.compile('Thời gian gửi báo cáo:')).parent.
                parent.next_siblings)[1].get_text()
            time_query = time_query.strip()
            #find structure. TÌm những header lơn của file
            index_tags = get_index_tag(soup, full_filename)
            index_tags_text = [a.get_text().strip() for a in index_tags]
            # lặp giữa các index để lấy ra thông tin giữa 2 index nằm cạnh nhau
            for i in range(len(index_tags)):
                # i = 0
                record = dict()
                first_tag = index_tags[i]
                next_tag = set(first_tag.find_all_next('table'))
                key = first_tag.get_text()

                # đối với i cuối cùng, thì sẽ không có previuos tag
                if i < (len(index_tags) - 1):
                    second_tag = index_tags[i + 1]
                    previous_tag = set(second_tag.find_all_previous('table'))
                    tag = next_tag.intersection(previous_tag)
                else:
                    tag = next_tag

                # kiểm tra xem có bao nhiêu table giữa các index
                if len(tag) == 0:
                    # nếu k có table thì ta thử tìm text giữ 2
                    next_tag = set(first_tag.find_all_next())
                    previous_tag = set(second_tag.find_all_previous())
                    tag = next_tag.intersection(previous_tag)
                    tag = [x for x in tag if x.name not in ('th', 'td', 'tr')]
                    text = [
                        str(x.next_sibling)
                        if isinstance(x, Tag) and x.name == 'br'
                        and isinstance(x.next_sibling, NavigableString) else
                        x.get_text() for x in tag
                    ]
                    text = [
                        re.sub(re.compile('\+|\*|\-'), '', x) for x in text
                    ]
                    # text = [x.get_text()  for x in tag]
                    record = ' '.join(text).strip()
                elif len(tag) == 1:
                    df_table11 = html_tables(list(tag)[0])
                    # từng loại table sẽ có cách lấy table khác nhau
                    if collection_name == 'the_tin_dung':
                        if re.search(regex_thong_tin_nhan_dang_card,
                                     key) is not None:
                            # day là table 1.1
                            df_table11 = df_table11.clean_table(
                                header='first_column', remove_na=True)
                            # table chỉ có 1 dòng, nên ta sẽ lấy giá trị đầu tiên của nó
                            record = df_table11.to_dict('records')[0]
                            record['no_number'] = no_number
                            record['header'] = header
                            record['time_query'] = time_query
                            record['full_filename'] = full_filename
                        elif re.search(regex_table12_card, key) is not None:
                            # với table 12 này ta sẽ remove NAN sau khi đã transpose lại  table
                            df_table11 = df_table11.clean_table(remove_na=True)
                            record = df_table11.to_dict('records')
                        else:
                            df_table11 = df_table11.clean_table()
                            record = df_table11.to_dict('records')
                    if collection_name == 'vay':
                        if re.search(regex_thong_tin_nhan_dang_vay,
                                     key) is not None:
                            # day là table 1.1
                            df_table11 = df_table11.clean_table(
                                header='first_column', remove_na=True)
                            # table chỉ có 1 dòng, nên ta sẽ lấy giá trị đầu tiên của nó
                            record = df_table11.to_dict('records')[0]
                            record['no_number'] = no_number
                            record['header'] = header
                            record['time_query'] = time_query
                            record['full_filename'] = full_filename
                        elif re.search(regex_table23_vay, key) is not None:
                            # với table 12 này ta sẽ remove NAN sau khi đã transpose lại  table
                            df_table11 = df_table11.clean_table(
                                case=case_table23_vay)
                            record = df_table11.to_dict('records')
                        elif re.search(regex_table24_vay, key) is not None:
                            # với table 12 này ta sẽ remove NAN sau khi đã transpose lại  table
                            df_table11 = df_table11.clean_table(
                                case=case_table24_vay)
                            record = df_table11.to_dict('records')
                        elif re.search(regex_table21_vay, key) is not None:
                            # với table 12 này ta sẽ remove NAN sau khi đã transpose lại  table
                            df_table11 = df_table11.clean_table(
                                case=case_table21_vay)
                            record = df_table11.to_dict('records')
                        else:
                            df_table11 = df_table11.clean_table()
                            record = df_table11.to_dict('records')
                            # record[key] = record
                else:

                    # chu ý: table 2.2 của báo cáo thẻ tín dụng, có thể có 2 table, mà chưa được fix
                    # if re.search(regex_table22_card, key) is not None:
                    #
                    #
                    # # print('nhieu table tai day')
                    # else:
                    logger.warning(
                        'nhieu table tai day sau index: {} cua file{}'.format(
                            key, full_filename))
                    record = []
                    for tag_item in list(tag):
                        df_table11 = html_tables(tag_item)
                        df_table11 = df_table11.clean_table()
                        record_item = df_table11.to_dict('records')
                        record.append(record_item)

                # nếu dữ liệu thu được giữa cac index khác none thì ghi vào db
                if record != '':
                    key = key.replace('.', '\uff0E')
                    input_db[key] = record
                    input_db['_id'] = full_filename
            # sửa lại các key, và value theo các regex định nghĩa
            input_db = clean_change_key(input_db, case='the_tin_dung')
            with lock:
                coll_the.insert_one(input_db)
        except Exception as error:
            print('error at file: (%s), chi tiet loi nhu sau: (%s)' %
                  (full_filename, error))
            logger.error('error at file: (%s), chi tiet loi nhu sau: (%s)' %
                         (full_filename, error))
Ejemplo n.º 10
0
def call_api_address(list_id, lock, coll_cus_name):
    '''
    ys tưởng : chạy multiprocess, và nếu bị lỗi gì, thì ta gọi lại chính funtion này, nhưng kiểm tra trong list lại những id_ đã được update hay chưa, nếu 
    :param list_id: 
    :param lock: 
    :param coll_cus_name: 
    :return: 
    '''
    db = create_connect_to_mongo(database='cic', locahost=True)
    # phải tạo được connection trong function để có thể update được
    coll_cus_name = 'customer'
    coll_cus = db[coll_cus_name]
    driver = webdriver.Firefox()
    driver.get('http://vi.mygeoposition.com/?lang=vi')
    time.sleep(1)
    # list_id = [a['_id'] for a in query]
    query_true = list(
        coll_cus.find(
            {
                'address_new': {
                    '$exists': 1
                },
                'address_new.address': None,
                '_id': {
                    '$in': list_id
                }
            }, {
                'address_new': 1,
                'address': 1
            }))
    # query = list(coll_cus.find({'address_new':{'$exists':1},'address_new.address': None},{'address_new':1,'address':1}))

    # query_true = list(set(query_all).intersection(set(query)))
    try:
        for doc in query_true:
            try:
                input = WebDriverWait(driver, 10).until(
                    EC.presence_of_element_located((By.ID, "query")))
            except (UnexpectedAlertPresentException):
                driver.switch_to.alert.accept()
            # except WebDriverException:
            #     print('WebDriverException')
            except Exception as e:
                print(e)
                driver.quit()
                driver = webdriver.Firefox()
                driver.get('http://vi.mygeoposition.com/?lang=vi')
                time.sleep(1)
                continue
            input_vaues = doc['address']
            list_address = []
            for input_value in input_vaues:
                # input_value = 'dfdfdfdfdfd'
                try:
                    address = None
                    vi_do = None
                    kinh_do = None
                    khu_vuc_quan_ly = None
                    quan_huyen = None
                    khu_vuc_quan_ly_nho = None
                    vi_tri = None
                    duong_chinh = None
                    duong_chinh_khac = None
                    # input.clear()
                    # them viet nam vao in input
                    input_value_new = input_value + ', viet nam'
                    # input.send_keys(input_value_new , Keys.RETURN)
                    # # time.sleep(1)
                    # # chọn form geodata
                    # try:  # nếu có alert thì click chọn , ta chỉ nên đợi 3s thôi
                    #     geo_form = driver.find_element_by_xpath("//ul/li[3]/a")
                    #     time.sleep(0.5)
                    # except UnexpectedAlertPresentException: #neu co loi thi k can phai doi
                    #     # WebDriverWait(driver,5).until(EC.alert_is_present())
                    #     driver.switch_to.alert.accept()
                    #     continue
                    # except:
                    #     driver.quit()
                    #     driver = webdriver.Firefox()
                    #     driver.get('http://vi.mygeoposition.com/?lang=vi')
                    #     continue
                    driver = try_search(driver, input, input_value_new)
                    # geo_form.click()
                    source = driver.page_source
                    soup = BeautifulSoup(source, 'html.parser')
                    try:
                        select_form = driver.find_element_by_xpath(
                            "//p/button")
                        select_form.click()
                    except:
                        pass
                    df = pd.read_html(source)[0]
                    address = df[df[0] == 'Địa chỉ:'][1].values[0]
                    address = None if pd.isnull(address) else address
                    vi_do = df[df[0] == 'Vĩ độ:'][1].values[0]
                    vi_do = None if pd.isnull(vi_do) else vi_do

                    kinh_do = df[df[0] == 'Kinh độ:'][1].values[0]
                    kinh_do = None if pd.isnull(kinh_do) else kinh_do

                    khu_vuc_quan_ly = df[df[0] ==
                                         'Khu vực quản lý:'][1].values[0]
                    khu_vuc_quan_ly = None if pd.isnull(
                        khu_vuc_quan_ly) else khu_vuc_quan_ly

                    quan_huyen = df[df[0] == 'Quận:'][1].values[0]
                    quan_huyen = None if pd.isnull(quan_huyen) else quan_huyen

                    khu_vuc_quan_ly_nho = df[
                        df[0] == 'Khu vực quản lý cấp dưới:'][1].values[0]
                    khu_vuc_quan_ly_nho = None if pd.isnull(
                        khu_vuc_quan_ly_nho) else khu_vuc_quan_ly_nho

                    vi_tri = df[df[0] == 'Vị trí:'][1].values[0]
                    vi_tri = None if pd.isnull(vi_tri) else vi_tri

                    duong_chinh = df[df[0] == 'Đường chính:'][1].values[0]
                    duong_chinh = None if pd.isnull(
                        duong_chinh) else duong_chinh

                    duong_chinh_khac = df[df[0] ==
                                          'Đường chính #:'][1].values[0]
                    duong_chinh_khac = None if pd.isnull(
                        duong_chinh_khac) else duong_chinh_khac

                    if address == 'Hà Nội, Hoàn Kiếm, Hà Nội, Việt Nam':
                        address = None
                        vi_do = None
                        kinh_do = None
                        khu_vuc_quan_ly = None
                        quan_huyen = None
                        khu_vuc_quan_ly_nho = None
                        vi_tri = None
                        duong_chinh = None
                        duong_chinh_khac = None
                    # all = df.T.to_json()
                    # dict_new = {'address':address,'all':all}
                    dict_new = {
                        'address': address,
                        'vi_do': vi_do,
                        'kinh_do': kinh_do,
                        'khu_vuc_quan_ly': khu_vuc_quan_ly,
                        'quan_huyen': quan_huyen,
                        'khu_vuc_quan_ly_nho': khu_vuc_quan_ly_nho,
                        'vi_tri': vi_tri,
                        'duong_chinh': duong_chinh,
                        'duong_chinh_khac': duong_chinh_khac,
                    }
                    list_address.append(dict_new)
                except (UnexpectedAlertPresentException):
                    # WebDriverWait(driver, 5).until(EC.alert_is_present())
                    driver.switch_to.alert.accept()
                # except WebDriverException:
                #     print('WebDriverException')
                except Exception as e:
                    print(e)
                    print('loi tai adress: {}'.format(input_vaues))
                    driver.quit()
                    driver = webdriver.Firefox()
                    driver.get('http://vi.mygeoposition.com/?lang=vi')
                    time.sleep(1)
            with lock:
                coll_cus.update_one({'_id': doc['_id']},
                                    {'$set': {
                                        'address_new': list_address
                                    }})
    except:
        # driver.quit()
        call_api_address(list_id, lock, coll_cus_name)