Initial release

This commit is contained in:
anon74133 2025-07-18 18:48:25 +03:00
parent b281adffc5
commit 7c4e1628b6
Signed by: Anon74123
GPG key ID: FA392911B1E88411
5 changed files with 274 additions and 0 deletions

View file

@ -0,0 +1,70 @@
import PyPDF2
import re
import fitz
import os
import webbrowser
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import showerror
def config():
if not os.path.exists("Settings.conf"):
f = open("Settings.conf", "w")
f.write("DeleteOld=0")
f.close()
f = open("Settings.conf", "r")
settings = f.read().split('\n')
global Deleteold
Deleteold = int(settings[0][-1])
def sign(path_pdf,output):
image = "sign.png"
# old params 402 17 565 230
position = fitz.Rect(432,24,500,230)
file_handle = fitz.open(path_pdf)
first_page = file_handle[0]
first_page.insert_image(position, filename=image)
file_handle.save(output)
def work(path_pdf):
data = extractData(path_pdf)
if not os.path.exists(data[0] + ' ' + 'SN ' + data[1] + ' ' + data[2] + '.pdf'):
sign(path_pdf, data[0] + ' ' + 'SN ' + data[1] + ' ' + data[2] + '.pdf')
if Deleteold:
os.remove(path_pdf)
return 1
return 0
def extractData(path_pdf):
pdf = open(path_pdf, 'rb')
read = PyPDF2.PdfReader(pdf)
page = read.pages[0]
all_text = page.extract_text()
#print(all_text)
if all_text == '':
showerror(title="Ошибка", message=f'Файл {path_pdf} является картинкой, уберите его и перезапустите программу')
return 1
data = []
if len(re.findall('ЦБ-\\d{9}', all_text)) != 0:
data.append(re.findall('ЦБ-\\d{9}', all_text)[0])
else:
data.append('ЗН ' + re.findall('Заказ-наряд \\d{12}', all_text)[0][11:])
if len(re.findall('\\b\\d{6}\\b', all_text.split('SN')[1].split('Дата')[0])) != 0:
data.append(re.findall('\\b\\d{6}\\b', all_text.split('SN')[1].split('Дата')[0])[0])
else:
data.append(re.findall('\\b\\d{5}\\b', all_text.split('SN')[1].split('Дата')[0])[0])
data.append(re.findall('\\d\\d\\.\\d\\d\\.\\d{4}', all_text.split('Дата')[1])[0].replace('.', ''))
pdf.close()
return data
def get_pdf():
filenames = os.listdir('.')
return filenames
def main():
config()
for i in get_pdf():
if i[-3:] == 'pdf':
work(os.path.abspath(i))
for i in get_pdf():
if i[-3:] == 'pdf' and i[0:2] == 'ЦБ':
webbrowser.open_new_tab(os.path.abspath(i))
main()

View file

@ -0,0 +1 @@
DeleteOld=0

54
cataloger3000/Cargo.lock generated Normal file
View file

@ -0,0 +1,54 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aho-corasick"
version = "1.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916"
dependencies = [
"memchr",
]
[[package]]
name = "cataloger3000"
version = "0.1.0"
dependencies = [
"regex",
]
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "regex"
version = "1.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "368758f23274712b504848e9d5a6f010445cc8b87a7cdb4d7cbee666c1288da3"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"

7
cataloger3000/Cargo.toml Normal file
View file

@ -0,0 +1,7 @@
[package]
name = "cataloger3000"
version = "0.1.0"
edition = "2021"
[dependencies]
regex = "1"

142
cataloger3000/src/main.rs Normal file
View file

@ -0,0 +1,142 @@
use std::fs;
use std::fs::{copy, remove_file};
use std::io::{self, Write};
use std::path::PathBuf;
use regex::Regex;
use std::process::Command;
fn get_entries_in_directory(path: &str) -> io::Result<Vec<PathBuf>> {
Ok(fs::read_dir(path)?
.filter_map(|entry| entry.ok().map(|e| e.path()))
.collect())
}
fn find_sn_pattern(file_path: &PathBuf) -> Option<String> {
let file_name = file_path.file_name()?.to_str()?;
let re = Regex::new(r"SN (\d{5,6})").unwrap();
if let Some(captures) = re.captures(file_name) {
return Some(captures[1].to_string());
}
None
}
fn find_dir_by_number(root_path: &str, number: &str) -> io::Result<Option<PathBuf>> {
let re = Regex::new(&format!(r"{}", number)).unwrap();
let entries = fs::read_dir(root_path)?;
for entry in entries {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
let dir_name = path.file_name().and_then(|os_str| os_str.to_str());
if let Some(name) = dir_name {
if re.is_match(name) {
return Ok(Some(path.to_path_buf())); // Возвращаем путь к родительской директории
}
}
}
}
Ok(None) // Ничего не найдено
}
fn open_folder(path: &PathBuf) {
Command::new( "explorer" )
.arg( path.to_string_lossy().replace("/", "\\")) // <- Specify the directory you'd like to open.
.spawn( )
.unwrap( );
}
fn main() -> io::Result<()> {
let files = get_entries_in_directory("Сортировка")?; // "." - текущая директория
let mut letter = String::new();
print!("Какая буква у диска: ");
io::stdout().flush().unwrap(); // Очищаем буфер вывода
io::stdin().read_line(&mut letter).expect("Failed to read line");
let letter = letter.trim();
let mut openned_dir : Vec<PathBuf> = Vec::new();
for file in files{
if file.is_file(){
if let Some(sn) = find_sn_pattern(&file) {
// Обрабатываем Result и Option
let dir_msc = find_dir_by_number(&(letter.to_owned() + ":/Москва/"), &sn).ok().and_then(|opt| opt);
//let result_msc = find_dir_by_number(&(letter.to_owned() + ":/Москва/"), &sn);
let dir_oth = find_dir_by_number(&( letter.to_owned() + ":/Заказ Наряды/"), &sn).ok().and_then(|opt| opt);
//let result_oth = find_dir_by_number(&( letter.to_owned() + ":/Заказ Наряды/"), &sn);
if let Some(dir_msc) = dir_msc { // Извлекаем PathBuf из Option
let file_name = file.file_name().expect("File name is None");
let file_name_str = file_name.to_str().expect("File name is not valid UTF-8");
let new_path = dir_msc.join(file_name_str); // Теперь dir_msc имеет тип PathBuf
copy(&file, &new_path).expect("Failed to copy file");
println!("\nLOG: Файл {} перемещён в {}" , file.display(), new_path.display());
remove_file(&file).expect("Failed to remove original file");
if !(openned_dir.contains(&dir_msc)){
open_folder(&dir_msc);
openned_dir.push(dir_msc);
}
}
else if let Some(dir_oth) = dir_oth { // Извлекаем PathBuf из Option
let file_name = file.file_name().expect("File name is None");
let file_name_str = file_name.to_str().expect("File name is not valid UTF-8");
let new_path = dir_oth.join(file_name_str); // Теперь dir_msc имеет тип PathBuf
copy(&file, &new_path).expect("Failed to copy file");
println!("\nLOG: Файл {} перемещён в {}" , file.display(), new_path.display());
remove_file(&file).expect("Failed to remove original file");
if !(openned_dir.contains(&dir_oth)){
open_folder(&dir_oth);
openned_dir.push(dir_oth);
}
}
else{
println!("Каталог не найден для файла: {}", file.display());
print!("Где создать папку для файла ? 1 - Москва, 2 - Заказ Наряды? (1/2): ");
io::stdout().flush().unwrap(); // Очищаем буфер вывода
let mut choice = String::new();
io::stdin().read_line(&mut choice).expect("Failed to read line");
let choice = choice.trim();
let base_path = match choice {
"1" => PathBuf::from(&( letter.to_owned() + ":/Москва/")),
"2" => PathBuf::from(&( letter.to_owned() + ":/Заказ Наряды/")),
_ => {
println!("Invalid choice.");
continue; // Переходим к следующему файлу
}
};
print!("Введите название для новой папки: ");
io::stdout().flush().unwrap();
let mut folder_name = String::new();
io::stdin().read_line(&mut folder_name).expect("Failed to read line");
let folder_name = folder_name.trim();
let new_dir = base_path.join(folder_name);
fs::create_dir_all(&new_dir).expect("Failed to create directory"); // Создаем директорию
let file_name = file.file_name().expect("File name is None");
let file_name_str = file_name.to_str().expect("File name is not valid UTF-8");
let new_path = new_dir.join(file_name_str);
copy(&file, &new_path).expect("Failed to copy file");
println!("\nLOG: Файл {} перемещён в {}" , file.display(), new_path.display());
remove_file(&file).expect("Failed to remove original file");
if !(openned_dir.contains(&new_dir)){
open_folder(&new_dir);
openned_dir.push(new_dir);
}
}
}
}
}
println!("Press any key to exit...");
io::stdin().read_line(&mut String::new()).unwrap();
Ok(())
}