This commit is contained in:
Noretsa 2020-08-31 18:07:04 +03:00
parent 99d8c5fb0b
commit c4bfc42df7
1422 changed files with 830 additions and 203319 deletions

43
.emacs.desktop Normal file
View File

@ -0,0 +1,43 @@
;; -*- mode: emacs-lisp; coding: emacs-mule; -*-
;; --------------------------------------------------------------------------
;; Desktop File for Emacs
;; --------------------------------------------------------------------------
;; Created Mon Aug 31 17:52:46 2020
;; Desktop file format version 208
;; Emacs version 26.3
;; Global section:
(setq desktop-saved-frameset [frameset 1 (24397 3774 977840 0) (desktop . "208") "norets@Alexeys-iMac.local" nil nil ((((minibuffer . t) (tty-type . "xterm-256color") (tty . "/dev/tty") (display-type . color) (background-mode . light) (foreground-color . "unspecified-fg") (menu-bar-lines . 0) (tool-bar-lines . 0) (background-color . "unspecified-bg") (font . "tty") (height . 40) (width . 135) (modeline . t) (unsplittable) (frameset--id . "2DC1-6FEA-719D-5D8F") (frameset--mini t)) ((min-height . 4) (min-width . 10) (min-height-ignore . 2) (min-width-ignore . 2) (min-height-safe . 1) (min-width-safe . 2) (min-pixel-height . 4) (min-pixel-width . 10) (min-pixel-height-ignore . 2) (min-pixel-width-ignore . 2) (min-pixel-height-safe . 1) (min-pixel-width-safe . 2)) leaf (pixel-width . 135) (pixel-height . 39) (total-width . 135) (total-height . 39) (normal-height . 1.0) (normal-width . 1.0) (buffer ".gitignore" (selected . t) (hscroll . 0) (fringes 0 0 nil) (margins nil) (scroll-bars nil 0 t nil 0 nil) (vscroll . 0) (dedicated) (point . 43) (start . 1))))])
(setq desktop-missing-file-warning nil)
(setq tags-file-name nil)
(setq tags-table-list nil)
(setq search-ring nil)
(setq regexp-search-ring nil)
(setq register-alist nil)
(setq file-name-history '("~/Documents/projects/klinteplo/"))
;; Buffer section -- buffers listed in same order as in buffer list:
(desktop-create-buffer 208
"/Users/norets/Documents/projects/klinteplo/.gitignore"
".gitignore"
'fundamental-mode
'(visual-line-mode override-global-mode company-mode undo-tree-mode)
43
'(89 nil)
nil
nil
'((buffer-display-time 24397 3771 932938 0) (buffer-file-coding-system . undecided-unix) (overwrite-mode) (truncate-lines))
'((mark-ring (90 75))))
(desktop-create-buffer 208
nil
"klinteplo"
'dired-mode
'(visual-line-mode override-global-mode company-mode)
843
'(843 nil)
t
'("/Users/norets/Documents/projects/klinteplo/")
'((buffer-display-time 24397 3760 234261 0) (overwrite-mode) (truncate-lines))
'((mark-ring (843 843))))

17
.gitignore vendored Normal file
View File

@ -0,0 +1,17 @@
*.jpg
*.jpeg
*.pyc
*.bak
*.bak.
*.png
*.pdf
.DS_Store
/data/**.*.jpg
/data/**.*.jpeg
/data/**.*.JPG
/data/**.*.JPEG
/data/**.DS_Store
/data_old/**
/env/**
/.ropeproject

244
classes/create_photo.py Normal file
View File

@ -0,0 +1,244 @@
from datetime import datetime, timedelta
import os
import shutil
from docx import Document
from docx.text.paragraph import Paragraph
from docx.shared import Inches, Pt, RGBColor
from docx.enum.style import WD_STYLE_TYPE
import sys
import subprocess
import re
from random import randint
import random
from pathlib import Path
from pdf2image import convert_from_path
from PIL import Image, ImageFilter, ImageDraw
from PIL.ImageFilter import (
BLUR, CONTOUR, DETAIL, EDGE_ENHANCE, EDGE_ENHANCE_MORE,
EMBOSS, FIND_EDGES, SMOOTH, SMOOTH_MORE, SHARPEN
)
def convert_to(folder, source, timeout=None):
args = [libreoffice_exec(), '--headless', '--convert-to', 'pdf', '--outdir', folder, source]
process = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
filename = re.search('-> (.*?) using filter', process.stdout.decode())
return filename.group(1)
def libreoffice_exec():
# TODO: Provide support for more platforms
if sys.platform == 'darwin':
return '/Applications/LibreOffice.app/Contents/MacOS/soffice'
elif sys.platform == 'win32':
# you need to add libreoffice to path
return 'soffice.exe'
return 'libreoffice'
def create_photo(address, user):
month = datetime.now().month
info = get_info(user)
path_to_template = os.path.join(os.path.abspath('.'), 'data', user)
template_docx = os.path.join(path_to_template, 'new_template.docx')
if len(info) > 0:
if not os.path.exists(template_docx):
# print(f"Копируем шаблоны графиков в {user}")
template_in_user = shutil.copyfile('new_template.docx', template_docx)
path_for_photo = os.path.join(path_to_template, str(month), address)
photos = get_photo(address, user)
if len(photos) > 0:
# print(len(photos))
if len(photos) > 7:
open_document(template_docx, True, info, address, path_for_photo, user)
else:
open_document(template_docx, False, info, address, path_for_photo, user)
return path_for_photo
else:
print(f"Нет фотографий по адресу {address}")
def get_info(user):
path = os.path.join(os.path.abspath('.'), 'data', user, 'img_5.txt')
if not os.path.exists(path):
print(f"Нет файла с информацией у пользователя {user}")
return []
with open(path, 'r') as f:
fd = f.readlines()
return fd
def get_photo(address, email):
photos = []
month = datetime.now().month
main_path = os.path.join(os.path.abspath('.'), 'data', email, str(month), address)
if not os.path.exists(main_path):
print(f"Нет фотографий по адресу: {address}")
return photos
else:
for images in os.listdir(main_path):
if images.endswith(".jpg") or images.endswith(".jpeg") or images.endswith(".JPG"):
photos.append(main_path + '/' + images)
return photos
def open_document(filename, lift, info, address, path_for_photo, user):
# print(f"Наличие лифта по адресу: {address} - {lift}")
# print(f"Начинаем подготавливать график для {address}, шаблон {filename}")
row_for_sign = 0
document = Document(filename)
styles = document.styles
tables = document.tables
date_now = datetime.today()
first_date = tables[0].rows[1].cells[0].text
first_date = datetime.strptime(first_date, '%d.%m.%y')
if datetime.now().date()-timedelta(12) > first_date.date():
clear_table(tables, lift, styles, info)
row_for_sign = fill_table(tables)
document.save(filename)
else:
row_for_sign = fill_table(tables)
document.save(filename)
paragraphs = document.paragraphs
fill_info(paragraphs, styles, info, address, lift)
document.save(filename)
make_png_with_sign(filename, row_for_sign, lift, path_for_photo, user)
def make_png_with_sign(filename, row_for_sign, lift, path_for_photo, user):
# print(f"Создаем картинку из графика {filename}")
horizontal = 0
if lift:
start_vertical = 780
else:
start_vertical = 680
result = convert_to('.', filename, timeout=15)
pages = convert_from_path(result, 200)
pages[0].save('template.png', 'PNG')
img2 = Image.open('template.png')
img2 = img2.convert("RGBA")
datas = img2.getdata()
newData = []
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2] == 255:
newData.append((255, 255, 255, 0))
else:
# if item[0] > 120:
# newData.append((105, 105, 105, 255))
# else:
newData.append(item)
img2.putdata(newData)
while (row_for_sign+1) > 0:
# if lift:
# horizontal = randint(1320, 1450)
# else:
horizontal = randint(1320, 1450)
vertical = start_vertical + ((row_for_sign) * 100)
# clear_background('my_sign.png')
sign = Image.open(os.path.join(os.path.abspath('.'), 'data', user, 'sign.png'))
width, height = sign.size
sign = sign.resize((int(width*1.5), int(height*1.5)))
# print(horizontal)
img2.paste(sign, (horizontal, vertical), sign) # vertical step = 150
row_for_sign -= 1
img2.save('template.png', "PNG")
add_image_to_image('template.png', 'fon2.png', path_for_photo)
def add_image_to_image(filename, filename_fon, dst_folder):
# print(f"Накладываем график {filename} на фон")
left = randint(0, 140)
upper = randint(0, 85)
w_rand = random.uniform(0.8, 1)
b_rand = random.uniform(0.5, 0.8)
try:
angle = 0
# img = img.filter(ImageFilter.GaussianBlur(radius=1))
background = Image.open(filename_fon)
foreground = Image.open(filename)
width, height = foreground.size
size = int(width*0.25), int(height*0.25)
width_b, height_b = background.size
foreground = foreground.resize(size).rotate(angle)
background.paste(foreground, (195, 290), foreground)
background = background.crop((left, upper, width_b*w_rand, height_b*w_rand))
background = background.filter(ImageFilter.GaussianBlur(radius=b_rand))
background.save(os.path.join(dst_folder, 'graph.jpg'))
# print(os.path.join(dst_folder, 'graph.jpg'))
# print(os.path.dirname(dst_folder))
except IOError:
print(sys.exc_info()[0])
pass
def delete_paragraph(paragraph):
p = paragraph._element
p.getparent().remove(p)
p._p = p._element = None
def clear_table(tables, lift, styles, info):
# print(f"Очищаем таблицу в графике")
fio = info[0].split('\n')[0]
count = 0
while count < len(tables[0].rows)-1:
date_to_add = datetime.now().date()+timedelta(count)
delete_paragraph(tables[0].rows[count+1].cells[0].paragraphs[0])
delete_paragraph(tables[0].rows[count+1].cells[2].paragraphs[0])
par = tables[0].rows[count+1].cells[0].add_paragraph()
par_fio = tables[0].rows[count+1].cells[2].add_paragraph()
p = par.add_run(datetime.strftime(date_to_add, '%d.%m.%y'))
p_fio = par_fio.add_run(fio)
par_fio.alignment = 1
p_fio.bold = True
p.bold = True
font = p.font
count += 1
def fill_table(tables):
# print("Заполняем таблицу в графике")
r_count = 0
count = 0
while count < len(tables[0].rows)-1:
date_in_cell = tables[0].rows[count+1].cells[0].text
date_in_cell = datetime.strptime(date_in_cell, '%d.%m.%y')
if date_in_cell.date() == datetime.now().date():
r_count = count
count += 1
return r_count
def fill_info(paragraphs, styles, info, address, lift):
# print(f"Заполняем шапку графика в {address}")
fio = info[0].split('\n')[0]
dol = info[1].split('\n')[0]
phone_number = info[2].split('\n')[0]
for paragraph in paragraphs:
name_style = paragraph.style.name
if 'по адресу:' in paragraph.text:
# p = paragraph.insert_paragraph_before()
style = styles[name_style]
style.font.size = Pt(14)
paragraph.text = ''
p = paragraph.add_run('по адресу: '+address[:-4]+' Подъезд № ' + address[-2])
p.bold = True
font = p.font
font.color.rgb = RGBColor(128, 128, 128)
paragraph.style = styles[name_style]
elif 'Должность:' in paragraph.text:
paragraph.text = ''
if lift:
text_for_perechen = 'Перечень обрабатываемых объектов:\n - Первые этажи подъездов: полы, дверные и оконные ручки, почтовые ящики, панели домофонов и кодовых замков, перила лестничных маршей\n - Лифтовые кабины: напольные покрытия, панели управления лифтами, лифтовые вентиляционные решетки'
else:
text_for_perechen = 'Перечень обрабатываемых объектов:\n - Первые этажи подъездов: полы, дверные и оконные ручки, почтовые ящики, панели домофонов и кодовых замков, перила лестничных маршей'
run = paragraph.add_run(' Должность: ' + dol +' Ф.И.О.: ' + fio + '\n тел: ' + phone_number + '\n' + text_for_perechen)
font = run.font

74
classes/desinfection.py Normal file
View File

@ -0,0 +1,74 @@
import classes.create_photo as cr_photo
import os
import time
def assign_task(session, headers, task, address):
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/assign'
task_assign = session.put(url, headers=headers)
if task_assign.status_code == 200:
print(f'Получили задание по адресу: {address}')
complete_task(session, headers, task, address)
else:
print(f"Не смогли получить задание {address} {task['id']}!")
def complete_task(session, headers, task, address):
photo_path = os.path.join(cr_photo.create_photo(address, headers['uid']), 'graph.jpg')
id_task = task['id']
# questions = get_questions(id_task, session, headers)
question_components = []
yes_no = {"id": 23384, "position": 0, "answer": 77, "start_time": int(time.time())}
time.sleep(2)
yes_no.update({"end_time": int(time.time())})
question_components.append(yes_no)
if not os.path.exists(photo_path):
print(f"Нет фотографии графика по адресу {address}")
else:
img = send_image(session, headers, task['id'], photo_path)#photos.pop(0))
image_graph = {"id": 23385, "position": 1, "answer": [img['id']], "start_time": int(time.time())}
time.sleep(2)
image_graph.update({"end_time": int(time.time())})
question_components.append(image_graph)
questions = [{"id": 7956, "question_components": question_components, "position": 0}]
question_chains = [{"id": 7396, "questions": questions}]
ans = {"question_chains": question_chains}
session_t = session
session_t.headers.update(
{
'referer': 'https://knd.mosreg.ru/executions'+str(task['id'])+'/solve',
'x-platform': 'wb',
'accept': '*/*'
}
)
complete = session_t.post('https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/answers', headers=headers, json=ans)
if complete.status_code == 200:
print(f'Задание по адресу {address} выполнено успешно!\n\n')
else:
print(f'Задание по адресу {address} не выполненно! Статус ошибки {complete.status_code}\n\n')
def send_image(session, headers, url, photo):
"""Отправляем фото на сервер. Сервер должен вернуть id и url."""
files = {
'image': (photo[-5:], open(photo, 'rb')),
}
# print(files)
img = session.post('https://knd.mosreg.ru//api/v1/executions/'+str(url)+'/images', headers=headers, files=files)
if img.status_code == 200:
print(f"Фото {photo} успешно отправлено")
return img.json()
else:
print(f"Не удалось загрузить фото на сервер по заданию {url}, статус ошибки {img.status_code}! Повторная попытка!")
second_img = send_image(session, headers, url, photo)
return second_img
# def get_questions(id_task, session, headers):
# url = 'https://knd.mosreg.ru//api/v1/executions/'+str(id_task)+'/questions'
# questions = session.get(url, headers=headers)
# json_quest = questions.json()
# chain = json_quest['question_chains'][0].get('questions')
# print(chain[0].get('question_components'))
# return json_quest['selected_chains']

137
classes/proverka.py Normal file
View File

@ -0,0 +1,137 @@
import os
import datetime
import time
def assign_task(session, headers, task, address):
# print('assign_task')
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/assign'
task_assign = session.put(url, headers=headers)
if task_assign.status_code == 200:
print(f'Получили задание по адресу: {address}')
complete_task(session, headers, task, address)
else:
print(f"Не смогли получить задание {address} {task['id']}!")
def complete_task(session, headers, task, address):
photos = get_photo(address, headers['uid'])
if len(photos) > 0:
photos.sort()
"""В папке лежит фото графика, которое отправляется из модуля des, поэтому убираем отсюда"""
if len(photos) == 7 or len(photos) == 9:
photos.pop()
id_task = task['id']
quest = get_questions(id_task, session, headers)
length_question = get_length_questions(quest)
prepared_answers = []
if len(photos) == length_question:
prepared_answers = prepare_answer(quest, photos, session, task, headers)
ans = {"question_chains": prepared_answers}
# print(ans)
session_t = session
session_t.headers.update(
{
'referer': 'https://knd.mosreg.ru/executions'+str(task['id'])+'/solve',
'x-platform': 'wb',
'accept': '*/*'
}
)
complete = session_t.post('https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/answers', headers=headers, json=ans)
if complete.status_code == 200:
print(f'Задание по адресу {address} выполнено успешно!\n\n')
else:
print(f'Задание по адресу {address} не выполненно! Статус ошибки {complete.status_code}\n\n')
else:
print(f"\n\n\nНесоответствие количества вопросов и фотографий по адресу {address}!!! \
Необходимо проверить!!!\n\n\n")
# print(len(quest)) 9 and 13
def get_length_questions(quest):
count = 0
for main_chain in quest:
for second_chain in main_chain['questions']:
for third_chain in second_chain['question_components']:
question_type = third_chain['type']
if question_type == "gallery":
count = count + 1
return count
def prepare_answer(quest, photos, session, task, headers):
questions = []
question_components= []
question_chains = []
for main_chain in quest:
for second_chain in main_chain['questions']:
for third_chain in second_chain['question_components']:
question_type = third_chain['type']
if question_type == 'list':
data = {"id": third_chain['id'], "answer": 77, "answer_status": None, "start_time": int(time.time())}
time.sleep(2)
data.update({"end_time": int(time.time())})
question_components.append(data)
elif question_type == "geo":
data = {"id": third_chain['id'], "answer": {"location": task['coord']}, "answer_status": None, \
"start_time": int(time.time())}
time.sleep(2)
data.update({"end_time": int(time.time())})
question_components.append(data)
elif question_type == "gallery":
img = send_image(session, headers, task['id'], photos.pop(0))#photos.pop(0))
data = {"id": third_chain['id'], "answer": [img['id']], "answer_status": None, \
"start_time": int(time.time())}
time.sleep(2)
data.update({"end_time": int(time.time())})
question_components.append(data)
if len(question_components) > 0:
main_data = {
"id": second_chain['id'],
"question_components": question_components
}
questions.append(main_data)
question_components = []
if len(questions) > 0:
q_dict = {
"id": main_chain['id'],
"questions" : questions
}
question_chains.append(q_dict)
questions = []
return question_chains
def get_photo(address, email):
photos = []
month = datetime.datetime.now().month
main_path = os.path.join(os.path.abspath('.'), 'data', email, str(month), address)
if not os.path.exists(main_path):
return photos
else:
for images in os.listdir(main_path):
if images.endswith(".jpg") or images.endswith(".jpeg") or images.endswith(".JPG"):
photos.append(main_path + '/' + images)
return photos
def get_questions(id_task, session, headers):
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(id_task)+'/questions'
questions = session.get(url, headers=headers)
json_quest = questions.json()
return json_quest['selected_chains']
def send_image(session, headers, url, photo):
"""Отправляем фото на сервер. Сервер должен вернуть id и url."""
files = {
'image': (photo[-5:], open(photo, 'rb')),
}
img = session.post('https://knd.mosreg.ru//api/v1/executions/'+str(url)+'/images', headers=headers, files=files)
if img.status_code == 200:
print(f"Фото {photo} успешно отправлено")
return img.json()
else:
print(f"Не удалось загрузить фото на сервер по заданию {url}, статус ошибки {img.status_code}! Повторная попытка!")
second_img = send_image(session, headers, url, photo)
return second_img

BIN
data/.DS_Store vendored

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1 +0,0 @@
kn8746

View File

@ -0,0 +1,3 @@
Драченко Оксана Владимировна
начальник РЭУ
8(985)574-77-92

Binary file not shown.

View File

@ -0,0 +1 @@
kn2512

Binary file not shown.

Binary file not shown.

View File

@ -1 +0,0 @@
kn2645

Binary file not shown.

Binary file not shown.

View File

@ -1 +0,0 @@
kn2001

Binary file not shown.

Binary file not shown.

View File

@ -1 +0,0 @@
kn9172

264
des.py Normal file
View File

@ -0,0 +1,264 @@
import requests
import random
import string
# import json
import datetime
import time
import os
from classes.users import Users
import classes.desinfection as des
import classes.proverka as prov
def get_questions(id_task, session, headers):
url = 'https://knd.mosreg.ru//api/v1/executions/'+str(id_task)+'/questions'
questions = session.get(url, headers=headers)
json_quest = questions.json()
return json_quest['selected_chains']
def send_image(session, headers, url, photo):
"""Отправляем фото на сервер. Сервер должен вернуть id и url."""
files = {
'image': (photo[-5:], open(photo, 'rb')),
}
# print(files)
img = session.post('https://knd.mosreg.ru//api/v1/executions/'+str(url)+'/images', headers=headers, files=files)
if img.status_code == 200:
print(f"Фото {photo} успешно отправлено")
return img.json()
else:
print(f"Не удалось загрузить фото на сервер по заданию {url}, статус ошибки {img.status_code}! Повторная попытка!")
second_img = send_image(session, headers, url, photo)
return second_img
def complete_task(session, headers, task, address):
photos = get_photo(address, headers['uid'])
if len(photos) > 0:
photos.sort()
print(task['id'])
id_task = task['id']
questions = get_questions(id_task, session, headers)
data = []
for answers in questions:
answer_chain = {
'id': answers['id'],
'questions': [] # answers['questions']
}
if answer_chain['id'] == 6146: # Цепочка без ответов
continue
for components in answers['questions']:
comp = []
q_c = {
'id': components['id'],
'question_components': []
}
if q_c['id'] == 6560: # Вопрос без ответа
continue
comp.append(q_c)
answer_chain.update({'questions': comp})
data.append(answer_chain)
if len(data) == len(photos):
for chain in data:
for item in chain['questions']:
if len(data) == len(photos):
photo_from_photos = photos.pop(0)
img = send_image(session, headers, task['id'], photo_from_photos) # photos.pop(0))
# count_send_photo = 0
# while img['id'] is None:
# count_send_photo += 1
# print("Попытка № " + str(count_send_photo) + "отправить фото" + str(photo_from_photos))
# img = send_image(session, headers, task['id'], photo_from_photos)#photos.pop(0))
first = {"id": 18850, "answer": [img['id']], 'answer_status': None, 'start_time': int(time.time())}
time.sleep(2)
first.update({'end_time': int(time.time())})
second = {"id": 18851, "answer": {"location": task['coord']}, 'answer_status': None, 'start_time': int(time.time())}
time.sleep(2)
second.update({'end_time': int(time.time())})
item['question_components'].append(first)
item['question_components'].append(second)
else:
# img = send_image(session, headers, task['id'], photos.pop(0))
photo_from_photos = photos.pop(0)
img = send_image(session, headers, task['id'], photo_from_photos) # photos.pop(0))
# count_send_photo = 0
# while img['id'] is None:
# count_send_photo += 1
# print("Попытка № " + str(count_send_photo) + " отправить фото" + str(photo_from_photos))
# img = send_image(session, headers, task['id'], photo_from_photos)#photos.pop(0))
first = {"id": 18856, "answer": 77, 'answer_status': None, 'start_time': int(time.time())}
time.sleep(2)
first.update({'end_time': int(time.time())})
second = {"id": 18857, "answer": [img['id']], 'answer_status': None, 'start_time': int(time.time())}
time.sleep(2)
second.update({'end_time': int(time.time())})
item['question_components'].append(first)
item['question_components'].append(second)
ans = {"question_chains": data}
# print(ans)
session_t = session
session_t.headers.update(
{
'referer': 'https://knd.mosreg.ru/executions'+str(task['id'])+'/solve',
'x-platform': 'wb',
'accept': '*/*'
}
)
complete = session_t.post('https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/answers', headers=headers, json=ans)
if complete.status_code == 200:
print(f'Задание по адресу {address} выполнено успешно!')
else:
print(f'Задание по адресу {address} не выполненно! Статус ошибки {complete.status_code}')
else:
print(f"Несоответствие количества вопросов и количества фотографий по адресу: {address}")
# send_execution(task,session, headers)
def get_photo(address, email):
photos = []
month = datetime.datetime.now().month
main_path = os.path.join(os.path.abspath('.'), 'data', email, str(month), address)
if not os.path.exists(main_path):
return photos
else:
for images in os.listdir(main_path):
if images.endswith(".jpg") or images.endswith(".jpeg") or images.endswith(".JPG"):
photos.append(main_path + '/' + images)
return photos
def get_addresses(email):
addresses = []
month = datetime.datetime.now().month
main_path = os.path.join(os.path.abspath('.'), 'data')
path = os.walk(os.path.join(main_path, email, str(month)))
if not os.path.exists(os.path.join(main_path, email, str(month))):
return f"Не найдена папка с месяцем у пользователя {email}! Проверьте структуру каталога!"
for d, dirs, files in path:
addresses.append(dirs)
if len(addresses[0]) > 0:
return addresses[0]
else:
return f"Ни одного адреса для пользователя {email} не найдено! Добавьте фото и запустите программу снова!"
# def assign_task(session, headers, task, address):
# url = 'https://knd.mosreg.ru//api/v1/executions/'+str(task['id'])+'/assign'
# task_assign = session.put(url, headers=headers)
# if task_assign.status_code == 200:
# print(f'Получили задани по адресу: {address}')
# complete_task(session, headers, task, address)
# else:
# print(f"Не смогли получить задание {address} {task['id']}!")
def get_task(session, headers):
"""Получаем все доступные задания. Если в переменную search добавить адрес,
то будет искать этот адрес. Он попадет в
json_tasks['executions_available'],
так что надо понять откуда берем задания. Отсюда можно возвращать
все параметры задания:
1 координаты
2 адрес
3 подъезд
4 id_задания"""
desinfection = 'Дезинфекция подъездов (МОП)'
proverka = 'Систематическая проверка подъездов МКД'
# Получаем адреса
addresses = get_addresses(headers['uid'])
# Если адреса получили
if isinstance(addresses, list):
session_t = session
session_t.headers.update(
{'referer': 'https://knd.mosreg.ru/executions',
'x-platform': 'wb',
'accept': '*/*'
}
)
for address in addresses:
# change '-' for '/'
# need split enterance from address
addr = address.replace("Чаиковского", "Чайковского")
addr = address.replace("Маиданово", "Майданово")
search = addr.replace("_", "/")[:-4]
# print(search)
data = {'search': search}
tasks = session_t.post('https://knd.mosreg.ru//api/v1/executions',
headers=headers,
data=data
)
json_tasks = tasks.json()
# get_t = False
# Если есть доступное задание с таким адресом
exec_assigned = json_tasks['executions_assigned'] # Уже полученные задания
exec_available = json_tasks['executions_available'] # Еще не принятые задания
# print(address)
if len(exec_available) > 0:
for n in exec_available:
coord = n['coord']
enterances = n['tasks']
for execution in enterances:
address_from_tasks = execution['dimensions'][0].get('entity_value_name')
name_from_tasks = execution['name']
enterance = execution['dimensions'][2].get('entity_value_name')
if address_from_tasks == 'Клин г, ' + addr.replace("_", "/")[:-4] and \
enterance[-1] == address[-2]:
print('\n')
print(name_from_tasks)
print('\n')
task = {
'id': execution['execution_id'],
'address': execution['dimensions'][0].get('entity_value_name'),
'enterance': execution['dimensions'][2].get('entity_value_name'),
'coord': coord
}
if name_from_tasks == desinfection:
des.assign_task(session, headers, task, address)
elif name_from_tasks == proverka:
pass
# prov.assign_task(session, headers, task, address)
else:
pass
else:
print(f"Нет доступных заданий для пользователя {headers['uid']} по адресу: {address}")
# Если адреса не получили выводим ошибку
else:
print(addresses)
def main():
users = Users()
logins = users.get_passwords()
if isinstance(logins, list):
url = 'https://knd.mosreg.ru//api/v1/auth/sign_in'
for user in logins:
session = requests.Session()
login = {
'email': user['email'],
'password': user['password']
}
response = session.post(url, data=login)
headers = {
'client': response.headers.get('client'),
'Access-token': response.headers.get('Access-token'),
'uid': response.headers.get('uid'),
}
if response.status_code == 200:
get_task(session, headers)
else:
print(f"Отказ в авторизации для пользователя {user['email']}!")
time.sleep(1)
else:
print(users.get_passwords())
if __name__ == "__main__":
main()
k = input("Press ENTER for exit")
def random_string(stringLength):
letters = string.ascii_letters
digits = string.digits
return ''.join(random.choice(letters+digits) for i in range(stringLength))

76
env/bin/activate vendored
View File

@ -1,76 +0,0 @@
# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly
deactivate () {
# reset old environment variables
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
PATH="${_OLD_VIRTUAL_PATH:-}"
export PATH
unset _OLD_VIRTUAL_PATH
fi
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
export PYTHONHOME
unset _OLD_VIRTUAL_PYTHONHOME
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
hash -r
fi
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
PS1="${_OLD_VIRTUAL_PS1:-}"
export PS1
unset _OLD_VIRTUAL_PS1
fi
unset VIRTUAL_ENV
if [ ! "${1:-}" = "nondestructive" ] ; then
# Self destruct!
unset -f deactivate
fi
}
# unset irrelevant variables
deactivate nondestructive
VIRTUAL_ENV="/Users/norets/Documents/projects/klinteplo/env"
export VIRTUAL_ENV
_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH
# unset PYTHONHOME if set
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
# could use `if (set -u; : $PYTHONHOME) ;` in bash
if [ -n "${PYTHONHOME:-}" ] ; then
_OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
unset PYTHONHOME
fi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1:-}"
if [ "x(env) " != x ] ; then
PS1="(env) ${PS1:-}"
else
if [ "`basename \"$VIRTUAL_ENV\"`" = "__" ] ; then
# special case for Aspen magic directories
# see http://www.zetadev.com/software/aspen/
PS1="[`basename \`dirname \"$VIRTUAL_ENV\"\``] $PS1"
else
PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
fi
fi
export PS1
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
hash -r
fi

37
env/bin/activate.csh vendored
View File

@ -1,37 +0,0 @@
# This file must be used with "source bin/activate.csh" *from csh*.
# You cannot run it directly.
# Created by Davide Di Blasi <davidedb@gmail.com>.
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; test "\!:*" != "nondestructive" && unalias deactivate'
# Unset irrelevant variables.
deactivate nondestructive
setenv VIRTUAL_ENV "/Users/norets/Documents/projects/klinteplo/env"
set _OLD_VIRTUAL_PATH="$PATH"
setenv PATH "$VIRTUAL_ENV/bin:$PATH"
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
if ("env" != "") then
set env_name = "env"
else
if (`basename "VIRTUAL_ENV"` == "__") then
# special case for Aspen magic directories
# see http://www.zetadev.com/software/aspen/
set env_name = `basename \`dirname "$VIRTUAL_ENV"\``
else
set env_name = `basename "$VIRTUAL_ENV"`
endif
endif
set prompt = "[$env_name] $prompt"
unset env_name
endif
alias pydoc python -m pydoc
rehash

75
env/bin/activate.fish vendored
View File

@ -1,75 +0,0 @@
# This file must be used with ". bin/activate.fish" *from fish* (http://fishshell.org)
# you cannot run it directly
function deactivate -d "Exit virtualenv and return to normal shell environment"
# reset old environment variables
if test -n "$_OLD_VIRTUAL_PATH"
set -gx PATH $_OLD_VIRTUAL_PATH
set -e _OLD_VIRTUAL_PATH
end
if test -n "$_OLD_VIRTUAL_PYTHONHOME"
set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
set -e _OLD_VIRTUAL_PYTHONHOME
end
if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
functions -e fish_prompt
set -e _OLD_FISH_PROMPT_OVERRIDE
functions -c _old_fish_prompt fish_prompt
functions -e _old_fish_prompt
end
set -e VIRTUAL_ENV
if test "$argv[1]" != "nondestructive"
# Self destruct!
functions -e deactivate
end
end
# unset irrelevant variables
deactivate nondestructive
set -gx VIRTUAL_ENV "/Users/norets/Documents/projects/klinteplo/env"
set -gx _OLD_VIRTUAL_PATH $PATH
set -gx PATH "$VIRTUAL_ENV/bin" $PATH
# unset PYTHONHOME if set
if set -q PYTHONHOME
set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
set -e PYTHONHOME
end
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
# fish uses a function instead of an env var to generate the prompt.
# save the current fish_prompt function as the function _old_fish_prompt
functions -c fish_prompt _old_fish_prompt
# with the original prompt function renamed, we can override with our own.
function fish_prompt
# Save the return status of the last command
set -l old_status $status
# Prompt override?
if test -n "(env) "
printf "%s%s" "(env) " (set_color normal)
else
# ...Otherwise, prepend env
set -l _checkbase (basename "$VIRTUAL_ENV")
if test $_checkbase = "__"
# special case for Aspen magic directories
# see http://www.zetadev.com/software/aspen/
printf "%s[%s]%s " (set_color -b blue white) (basename (dirname "$VIRTUAL_ENV")) (set_color normal)
else
printf "%s(%s)%s" (set_color -b blue white) (basename "$VIRTUAL_ENV") (set_color normal)
end
end
# Restore the return status of the previous command.
echo "exit $old_status" | .
_old_fish_prompt
end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
end

10
env/bin/chardetect vendored
View File

@ -1,10 +0,0 @@
#!/Users/norets/Documents/projects/klinteplo/env/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from chardet.cli.chardetect import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())

10
env/bin/easy_install vendored
View File

@ -1,10 +0,0 @@
#!/Users/norets/Documents/projects/klinteplo/env/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from setuptools.command.easy_install import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())

View File

@ -1,10 +0,0 @@
#!/Users/norets/Documents/projects/klinteplo/env/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from setuptools.command.easy_install import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())

10
env/bin/pip vendored
View File

@ -1,10 +0,0 @@
#!/Users/norets/Documents/projects/klinteplo/env/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())

10
env/bin/pip3 vendored
View File

@ -1,10 +0,0 @@
#!/Users/norets/Documents/projects/klinteplo/env/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())

10
env/bin/pip3.7 vendored
View File

@ -1,10 +0,0 @@
#!/Users/norets/Documents/projects/klinteplo/env/bin/python
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())

1
env/bin/python vendored
View File

@ -1 +0,0 @@
/Users/norets/.pyenv/versions/3.7.7/bin/python

1
env/bin/python3 vendored
View File

@ -1 +0,0 @@
python

View File

@ -1,21 +0,0 @@
This packge contains a modified version of ca-bundle.crt:
ca-bundle.crt -- Bundle of CA Root Certificates
Certificate data from Mozilla as of: Thu Nov 3 19:04:19 2011#
This is a bundle of X.509 certificates of public Certificate Authorities
(CA). These were automatically extracted from Mozilla's root certificates
file (certdata.txt). This file can be found in the mozilla source tree:
http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1#
It contains the certificates in PEM format and therefore
can be directly used with curl / libcurl / php_curl, or with
an Apache+mod_ssl webserver for SSL client authentication.
Just configure this file as the SSLCACertificateFile.#
***** BEGIN LICENSE BLOCK *****
This Source Code Form is subject to the terms of the Mozilla Public License,
v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain
one at http://mozilla.org/MPL/2.0/.
***** END LICENSE BLOCK *****
@(#) $RCSfile: certdata.txt,v $ $Revision: 1.80 $ $Date: 2011/11/03 15:11:58 $

View File

@ -1,82 +0,0 @@
Metadata-Version: 2.1
Name: certifi
Version: 2020.4.5.2
Summary: Python package for providing Mozilla's CA Bundle.
Home-page: https://certifiio.readthedocs.io/en/latest/
Author: Kenneth Reitz
Author-email: me@kennethreitz.com
License: MPL-2.0
Project-URL: Documentation, https://certifiio.readthedocs.io/en/latest/
Project-URL: Source, https://github.com/certifi/python-certifi
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
Classifier: Natural Language :: English
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Certifi: Python SSL Certificates
================================
`Certifi`_ provides Mozilla's carefully curated collection of Root Certificates for
validating the trustworthiness of SSL certificates while verifying the identity
of TLS hosts. It has been extracted from the `Requests`_ project.
Installation
------------
``certifi`` is available on PyPI. Simply install it with ``pip``::
$ pip install certifi
Usage
-----
To reference the installed certificate authority (CA) bundle, you can use the
built-in function::
>>> import certifi
>>> certifi.where()
'/usr/local/lib/python3.7/site-packages/certifi/cacert.pem'
Or from the command line::
$ python -m certifi
/usr/local/lib/python3.7/site-packages/certifi/cacert.pem
Enjoy!
1024-bit Root Certificates
~~~~~~~~~~~~~~~~~~~~~~~~~~
Browsers and certificate authorities have concluded that 1024-bit keys are
unacceptably weak for certificates, particularly root certificates. For this
reason, Mozilla has removed any weak (i.e. 1024-bit key) certificate from its
bundle, replacing it with an equivalent strong (i.e. 2048-bit or greater key)
certificate from the same CA. Because Mozilla removed these certificates from
its bundle, ``certifi`` removed them as well.
In previous versions, ``certifi`` provided the ``certifi.old_where()`` function
to intentionally re-add the 1024-bit roots back into your bundle. This was not
recommended in production and therefore was removed at the end of 2018.
.. _`Certifi`: https://certifiio.readthedocs.io/en/latest/
.. _`Requests`: https://requests.readthedocs.io/en/master/
Addition/Removal of Certificates
--------------------------------
Certifi does not support any addition/removal or other modification of the
CA trust store content. This project is intended to provide a reliable and
highly portable root of trust to python deployments. Look to upstream projects
for methods to use alternate trust.

View File

@ -1,13 +0,0 @@
certifi-2020.4.5.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
certifi-2020.4.5.2.dist-info/LICENSE,sha256=anCkv2sBABbVmmS4rkrY3H9e8W8ftFPMLs13HFo0ETE,1048
certifi-2020.4.5.2.dist-info/METADATA,sha256=6yXK-6O4Tg1tGBEdMbsqUVsknyVcKP6AxcRbaEsSDnw,2945
certifi-2020.4.5.2.dist-info/RECORD,,
certifi-2020.4.5.2.dist-info/WHEEL,sha256=kGT74LWyRUZrL4VgLh6_g12IeVl_9u9ZVhadrgXZUEY,110
certifi-2020.4.5.2.dist-info/top_level.txt,sha256=KMu4vUCfsjLrkPbSNdgdekS-pVJzBAJFO__nI8NF6-U,8
certifi/__init__.py,sha256=86CjQliP9oTG5vlZ0zXjWqE_bvVX8C1PxNvZLC2SUYI,64
certifi/__main__.py,sha256=xBBoj905TUWBLRGANOcf7oi6e-3dMP4cEoG9OyMs11g,243
certifi/__pycache__/__init__.cpython-37.pyc,,
certifi/__pycache__/__main__.cpython-37.pyc,,
certifi/__pycache__/core.cpython-37.pyc,,
certifi/cacert.pem,sha256=hwBo73gFnF0BKiP3FQKfG32xkGDhxl4SwCQiH2rDKr0,284099
certifi/core.py,sha256=V0uyxKOYdz6ulDSusclrLmjbPgOXsD0BnEf0SQ7OnoE,2303

View File

@ -1,6 +0,0 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.34.2)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any

View File

@ -1,3 +0,0 @@
from .core import contents, where
__version__ = "2020.04.05.2"

View File

@ -1,12 +0,0 @@
import argparse
from certifi import contents, where
parser = argparse.ArgumentParser()
parser.add_argument("-c", "--contents", action="store_true")
args = parser.parse_args()
if args.contents:
print(contents())
else:
print(where())

File diff suppressed because it is too large Load Diff

View File

@ -1,60 +0,0 @@
# -*- coding: utf-8 -*-
"""
certifi.py
~~~~~~~~~~
This module returns the installation location of cacert.pem or its contents.
"""
import os
try:
from importlib.resources import path as get_path, read_text
_CACERT_CTX = None
_CACERT_PATH = None
def where():
# This is slightly terrible, but we want to delay extracting the file
# in cases where we're inside of a zipimport situation until someone
# actually calls where(), but we don't want to re-extract the file
# on every call of where(), so we'll do it once then store it in a
# global variable.
global _CACERT_CTX
global _CACERT_PATH
if _CACERT_PATH is None:
# This is slightly janky, the importlib.resources API wants you to
# manage the cleanup of this file, so it doesn't actually return a
# path, it returns a context manager that will give you the path
# when you enter it and will do any cleanup when you leave it. In
# the common case of not needing a temporary file, it will just
# return the file system location and the __exit__() is a no-op.
#
# We also have to hold onto the actual context manager, because
# it will do the cleanup whenever it gets garbage collected, so
# we will also store that at the global level as well.
_CACERT_CTX = get_path("certifi", "cacert.pem")
_CACERT_PATH = str(_CACERT_CTX.__enter__())
return _CACERT_PATH
except ImportError:
# This fallback will work for Python versions prior to 3.7 that lack the
# importlib.resources module but relies on the existing `where` function
# so won't address issues with environments like PyOxidizer that don't set
# __file__ on modules.
def read_text(_module, _path, encoding="ascii"):
with open(where(), "r", encoding=encoding) as data:
return data.read()
# If we don't have importlib.resources, then we will just do the old logic
# of assuming we're on the filesystem and munge the path directly.
def where():
f = os.path.dirname(__file__)
return os.path.join(f, "cacert.pem")
def contents():
return read_text("certifi", "cacert.pem", encoding="ascii")

View File

@ -1,70 +0,0 @@
Chardet: The Universal Character Encoding Detector
--------------------------------------------------
.. image:: https://img.shields.io/travis/chardet/chardet/stable.svg
:alt: Build status
:target: https://travis-ci.org/chardet/chardet
.. image:: https://img.shields.io/coveralls/chardet/chardet/stable.svg
:target: https://coveralls.io/r/chardet/chardet
.. image:: https://img.shields.io/pypi/v/chardet.svg
:target: https://warehouse.python.org/project/chardet/
:alt: Latest version on PyPI
.. image:: https://img.shields.io/pypi/l/chardet.svg
:alt: License
Detects
- ASCII, UTF-8, UTF-16 (2 variants), UTF-32 (4 variants)
- Big5, GB2312, EUC-TW, HZ-GB-2312, ISO-2022-CN (Traditional and Simplified Chinese)
- EUC-JP, SHIFT_JIS, CP932, ISO-2022-JP (Japanese)
- EUC-KR, ISO-2022-KR (Korean)
- KOI8-R, MacCyrillic, IBM855, IBM866, ISO-8859-5, windows-1251 (Cyrillic)
- ISO-8859-5, windows-1251 (Bulgarian)
- ISO-8859-1, windows-1252 (Western European languages)
- ISO-8859-7, windows-1253 (Greek)
- ISO-8859-8, windows-1255 (Visual and Logical Hebrew)
- TIS-620 (Thai)
.. note::
Our ISO-8859-2 and windows-1250 (Hungarian) probers have been temporarily
disabled until we can retrain the models.
Requires Python 2.6, 2.7, or 3.3+.
Installation
------------
Install from `PyPI <https://pypi.python.org/pypi/chardet>`_::
pip install chardet
Documentation
-------------
For users, docs are now available at https://chardet.readthedocs.io/.
Command-line Tool
-----------------
chardet comes with a command-line script which reports on the encodings of one
or more files::
% chardetect somefile someotherfile
somefile: windows-1252 with confidence 0.5
someotherfile: ascii with confidence 1.0
About
-----
This is a continuation of Mark Pilgrim's excellent chardet. Previously, two
versions needed to be maintained: one that supported python 2.x and one that
supported python 3.x. We've recently merged with `Ian Cordasco <https://github.com/sigmavirus24>`_'s
`charade <https://github.com/sigmavirus24/charade>`_ fork, so now we have one
coherent version that works for Python 2.6+.
:maintainer: Dan Blanchard

View File

@ -1,96 +0,0 @@
Metadata-Version: 2.0
Name: chardet
Version: 3.0.4
Summary: Universal encoding detector for Python 2 and 3
Home-page: https://github.com/chardet/chardet
Author: Daniel Blanchard
Author-email: dan.blanchard@gmail.com
License: LGPL
Keywords: encoding,i18n,xml
Platform: UNKNOWN
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.6
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Classifier: Programming Language :: Python :: 3.5
Classifier: Programming Language :: Python :: 3.6
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Text Processing :: Linguistic
Chardet: The Universal Character Encoding Detector
--------------------------------------------------
.. image:: https://img.shields.io/travis/chardet/chardet/stable.svg
:alt: Build status
:target: https://travis-ci.org/chardet/chardet
.. image:: https://img.shields.io/coveralls/chardet/chardet/stable.svg
:target: https://coveralls.io/r/chardet/chardet
.. image:: https://img.shields.io/pypi/v/chardet.svg
:target: https://warehouse.python.org/project/chardet/
:alt: Latest version on PyPI
.. image:: https://img.shields.io/pypi/l/chardet.svg
:alt: License
Detects
- ASCII, UTF-8, UTF-16 (2 variants), UTF-32 (4 variants)
- Big5, GB2312, EUC-TW, HZ-GB-2312, ISO-2022-CN (Traditional and Simplified Chinese)
- EUC-JP, SHIFT_JIS, CP932, ISO-2022-JP (Japanese)
- EUC-KR, ISO-2022-KR (Korean)
- KOI8-R, MacCyrillic, IBM855, IBM866, ISO-8859-5, windows-1251 (Cyrillic)
- ISO-8859-5, windows-1251 (Bulgarian)
- ISO-8859-1, windows-1252 (Western European languages)
- ISO-8859-7, windows-1253 (Greek)
- ISO-8859-8, windows-1255 (Visual and Logical Hebrew)
- TIS-620 (Thai)
.. note::
Our ISO-8859-2 and windows-1250 (Hungarian) probers have been temporarily
disabled until we can retrain the models.
Requires Python 2.6, 2.7, or 3.3+.
Installation
------------
Install from `PyPI <https://pypi.python.org/pypi/chardet>`_::
pip install chardet
Documentation
-------------
For users, docs are now available at https://chardet.readthedocs.io/.
Command-line Tool
-----------------
chardet comes with a command-line script which reports on the encodings of one
or more files::
% chardetect somefile someotherfile
somefile: windows-1252 with confidence 0.5
someotherfile: ascii with confidence 1.0
About
-----
This is a continuation of Mark Pilgrim's excellent chardet. Previously, two
versions needed to be maintained: one that supported python 2.x and one that
supported python 3.x. We've recently merged with `Ian Cordasco <https://github.com/sigmavirus24>`_'s
`charade <https://github.com/sigmavirus24/charade>`_ fork, so now we have one
coherent version that works for Python 2.6+.
:maintainer: Dan Blanchard

View File

@ -1,91 +0,0 @@
../../../bin/chardetect,sha256=HRMEiJwVAmLgyuR-mIN4SyaWYH1w1Rq_awoUT-oKFpw,265
chardet-3.0.4.dist-info/DESCRIPTION.rst,sha256=PQ4sBsMyKFZkjC6QpmbpLn0UtCNyeb-ZqvCGEgyZMGk,2174
chardet-3.0.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
chardet-3.0.4.dist-info/METADATA,sha256=RV_2I4B1Z586DL8oVO5Kp7X5bUdQ5EuKAvNoAEF8wSw,3239
chardet-3.0.4.dist-info/RECORD,,
chardet-3.0.4.dist-info/WHEEL,sha256=o2k-Qa-RMNIJmUdIc7KU6VWR_ErNRbWNlxDIpl7lm34,110
chardet-3.0.4.dist-info/entry_points.txt,sha256=fAMmhu5eJ-zAJ-smfqQwRClQ3-nozOCmvJ6-E8lgGJo,60
chardet-3.0.4.dist-info/metadata.json,sha256=0htbRM18ujyGZDdfowgAqj6Hq2eQtwzwyhaEveKntgo,1375
chardet-3.0.4.dist-info/top_level.txt,sha256=AowzBbZy4x8EirABDdJSLJZMkJ_53iIag8xfKR6D7kI,8
chardet/__init__.py,sha256=YsP5wQlsHJ2auF1RZJfypiSrCA7_bQiRm3ES_NI76-Y,1559
chardet/__pycache__/__init__.cpython-37.pyc,,
chardet/__pycache__/big5freq.cpython-37.pyc,,
chardet/__pycache__/big5prober.cpython-37.pyc,,
chardet/__pycache__/chardistribution.cpython-37.pyc,,
chardet/__pycache__/charsetgroupprober.cpython-37.pyc,,
chardet/__pycache__/charsetprober.cpython-37.pyc,,
chardet/__pycache__/codingstatemachine.cpython-37.pyc,,
chardet/__pycache__/compat.cpython-37.pyc,,
chardet/__pycache__/cp949prober.cpython-37.pyc,,
chardet/__pycache__/enums.cpython-37.pyc,,
chardet/__pycache__/escprober.cpython-37.pyc,,
chardet/__pycache__/escsm.cpython-37.pyc,,
chardet/__pycache__/eucjpprober.cpython-37.pyc,,
chardet/__pycache__/euckrfreq.cpython-37.pyc,,
chardet/__pycache__/euckrprober.cpython-37.pyc,,
chardet/__pycache__/euctwfreq.cpython-37.pyc,,
chardet/__pycache__/euctwprober.cpython-37.pyc,,
chardet/__pycache__/gb2312freq.cpython-37.pyc,,
chardet/__pycache__/gb2312prober.cpython-37.pyc,,
chardet/__pycache__/hebrewprober.cpython-37.pyc,,
chardet/__pycache__/jisfreq.cpython-37.pyc,,
chardet/__pycache__/jpcntx.cpython-37.pyc,,
chardet/__pycache__/langbulgarianmodel.cpython-37.pyc,,
chardet/__pycache__/langcyrillicmodel.cpython-37.pyc,,
chardet/__pycache__/langgreekmodel.cpython-37.pyc,,
chardet/__pycache__/langhebrewmodel.cpython-37.pyc,,
chardet/__pycache__/langhungarianmodel.cpython-37.pyc,,
chardet/__pycache__/langthaimodel.cpython-37.pyc,,
chardet/__pycache__/langturkishmodel.cpython-37.pyc,,
chardet/__pycache__/latin1prober.cpython-37.pyc,,
chardet/__pycache__/mbcharsetprober.cpython-37.pyc,,
chardet/__pycache__/mbcsgroupprober.cpython-37.pyc,,
chardet/__pycache__/mbcssm.cpython-37.pyc,,
chardet/__pycache__/sbcharsetprober.cpython-37.pyc,,
chardet/__pycache__/sbcsgroupprober.cpython-37.pyc,,
chardet/__pycache__/sjisprober.cpython-37.pyc,,
chardet/__pycache__/universaldetector.cpython-37.pyc,,
chardet/__pycache__/utf8prober.cpython-37.pyc,,
chardet/__pycache__/version.cpython-37.pyc,,
chardet/big5freq.py,sha256=D_zK5GyzoVsRes0HkLJziltFQX0bKCLOrFe9_xDvO_8,31254
chardet/big5prober.py,sha256=kBxHbdetBpPe7xrlb-e990iot64g_eGSLd32lB7_h3M,1757
chardet/chardistribution.py,sha256=3woWS62KrGooKyqz4zQSnjFbJpa6V7g02daAibTwcl8,9411
chardet/charsetgroupprober.py,sha256=6bDu8YIiRuScX4ca9Igb0U69TA2PGXXDej6Cc4_9kO4,3787
chardet/charsetprober.py,sha256=KSmwJErjypyj0bRZmC5F5eM7c8YQgLYIjZXintZNstg,5110
chardet/cli/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
chardet/cli/__pycache__/__init__.cpython-37.pyc,,
chardet/cli/__pycache__/chardetect.cpython-37.pyc,,
chardet/cli/chardetect.py,sha256=YBO8L4mXo0WR6_-Fjh_8QxPBoEBNqB9oNxNrdc54AQs,2738
chardet/codingstatemachine.py,sha256=VYp_6cyyki5sHgXDSZnXW4q1oelHc3cu9AyQTX7uug8,3590
chardet/compat.py,sha256=PKTzHkSbtbHDqS9PyujMbX74q1a8mMpeQTDVsQhZMRw,1134
chardet/cp949prober.py,sha256=TZ434QX8zzBsnUvL_8wm4AQVTZ2ZkqEEQL_lNw9f9ow,1855
chardet/enums.py,sha256=Aimwdb9as1dJKZaFNUH2OhWIVBVd6ZkJJ_WK5sNY8cU,1661
chardet/escprober.py,sha256=kkyqVg1Yw3DIOAMJ2bdlyQgUFQhuHAW8dUGskToNWSc,3950
chardet/escsm.py,sha256=RuXlgNvTIDarndvllNCk5WZBIpdCxQ0kcd9EAuxUh84,10510
chardet/eucjpprober.py,sha256=iD8Jdp0ISRjgjiVN7f0e8xGeQJ5GM2oeZ1dA8nbSeUw,3749
chardet/euckrfreq.py,sha256=-7GdmvgWez4-eO4SuXpa7tBiDi5vRXQ8WvdFAzVaSfo,13546
chardet/euckrprober.py,sha256=MqFMTQXxW4HbzIpZ9lKDHB3GN8SP4yiHenTmf8g_PxY,1748
chardet/euctwfreq.py,sha256=No1WyduFOgB5VITUA7PLyC5oJRNzRyMbBxaKI1l16MA,31621
chardet/euctwprober.py,sha256=13p6EP4yRaxqnP4iHtxHOJ6R2zxHq1_m8hTRjzVZ95c,1747
chardet/gb2312freq.py,sha256=JX8lsweKLmnCwmk8UHEQsLgkr_rP_kEbvivC4qPOrlc,20715
chardet/gb2312prober.py,sha256=gGvIWi9WhDjE-xQXHvNIyrnLvEbMAYgyUSZ65HUfylw,1754
chardet/hebrewprober.py,sha256=c3SZ-K7hvyzGY6JRAZxJgwJ_sUS9k0WYkvMY00YBYFo,13838
chardet/jisfreq.py,sha256=vpmJv2Bu0J8gnMVRPHMFefTRvo_ha1mryLig8CBwgOg,25777
chardet/jpcntx.py,sha256=PYlNqRUQT8LM3cT5FmHGP0iiscFlTWED92MALvBungo,19643
chardet/langbulgarianmodel.py,sha256=1HqQS9Pbtnj1xQgxitJMvw8X6kKr5OockNCZWfEQrPE,12839
chardet/langcyrillicmodel.py,sha256=LODajvsetH87yYDDQKA2CULXUH87tI223dhfjh9Zx9c,17948
chardet/langgreekmodel.py,sha256=8YAW7bU8YwSJap0kIJSbPMw1BEqzGjWzqcqf0WgUKAA,12688
chardet/langhebrewmodel.py,sha256=JSnqmE5E62tDLTPTvLpQsg5gOMO4PbdWRvV7Avkc0HA,11345
chardet/langhungarianmodel.py,sha256=RhapYSG5l0ZaO-VV4Fan5sW0WRGQqhwBM61yx3yxyOA,12592
chardet/langthaimodel.py,sha256=8l0173Gu_W6G8mxmQOTEF4ls2YdE7FxWf3QkSxEGXJQ,11290
chardet/langturkishmodel.py,sha256=W22eRNJsqI6uWAfwXSKVWWnCerYqrI8dZQTm_M0lRFk,11102
chardet/latin1prober.py,sha256=S2IoORhFk39FEFOlSFWtgVybRiP6h7BlLldHVclNkU8,5370
chardet/mbcharsetprober.py,sha256=AR95eFH9vuqSfvLQZN-L5ijea25NOBCoXqw8s5O9xLQ,3413
chardet/mbcsgroupprober.py,sha256=h6TRnnYq2OxG1WdD5JOyxcdVpn7dG0q-vB8nWr5mbh4,2012
chardet/mbcssm.py,sha256=SY32wVIF3HzcjY3BaEspy9metbNSKxIIB0RKPn7tjpI,25481
chardet/sbcharsetprober.py,sha256=LDSpCldDCFlYwUkGkwD2oFxLlPWIWXT09akH_2PiY74,5657
chardet/sbcsgroupprober.py,sha256=1IprcCB_k1qfmnxGC6MBbxELlKqD3scW6S8YIwdeyXA,3546
chardet/sjisprober.py,sha256=IIt-lZj0WJqK4rmUZzKZP4GJlE8KUEtFYVuY96ek5MQ,3774
chardet/universaldetector.py,sha256=qL0174lSZE442eB21nnktT9_VcAye07laFWUeUrjttY,12485
chardet/utf8prober.py,sha256=IdD8v3zWOsB8OLiyPi-y_fqwipRFxV9Nc1eKBLSuIEw,2766
chardet/version.py,sha256=sp3B08mrDXB-pf3K9fqJ_zeDHOCLC8RrngQyDFap_7g,242

View File

@ -1,6 +0,0 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.29.0)
Root-Is-Purelib: true
Tag: py2-none-any
Tag: py3-none-any

View File

@ -1,3 +0,0 @@
[console_scripts]
chardetect = chardet.cli.chardetect:main

View File

@ -1 +0,0 @@
{"classifiers": ["Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Text Processing :: Linguistic"], "extensions": {"python.commands": {"wrap_console": {"chardetect": "chardet.cli.chardetect:main"}}, "python.details": {"contacts": [{"email": "dan.blanchard@gmail.com", "name": "Daniel Blanchard", "role": "author"}], "document_names": {"description": "DESCRIPTION.rst"}, "project_urls": {"Home": "https://github.com/chardet/chardet"}}, "python.exports": {"console_scripts": {"chardetect": "chardet.cli.chardetect:main"}}}, "generator": "bdist_wheel (0.29.0)", "keywords": ["encoding", "i18n", "xml"], "license": "LGPL", "metadata_version": "2.0", "name": "chardet", "summary": "Universal encoding detector for Python 2 and 3", "test_requires": [{"requires": ["hypothesis", "pytest"]}], "version": "3.0.4"}

View File

@ -1,39 +0,0 @@
######################## BEGIN LICENSE BLOCK ########################
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
# 02110-1301 USA
######################### END LICENSE BLOCK #########################
from .compat import PY2, PY3
from .universaldetector import UniversalDetector
from .version import __version__, VERSION
def detect(byte_str):
"""
Detect the encoding of the given byte string.
:param byte_str: The byte sequence to examine.
:type byte_str: ``bytes`` or ``bytearray``
"""
if not isinstance(byte_str, bytearray):
if not isinstance(byte_str, bytes):
raise TypeError('Expected object of type bytes or bytearray, got: '
'{0}'.format(type(byte_str)))
else:
byte_str = bytearray(byte_str)
detector = UniversalDetector()
detector.feed(byte_str)
return detector.close()

Some files were not shown because too many files have changed in this diff Show More