-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerator.py
More file actions
267 lines (207 loc) · 7 KB
/
Copy pathgenerator.py
File metadata and controls
267 lines (207 loc) · 7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
import csv
import os
import re
from dotenv import load_dotenv
import random
import ast
import mysql.connector
from datetime import datetime
from tqdm import tqdm
load_dotenv()
DB_USER = os.getenv("DB_USER")
DB_PASSWORD = os.getenv("DB_PASSWORD")
DB_HOST = os.getenv("DB_HOST")
DB_PORT = os.getenv("DB_PORT")
DB_NAME = os.getenv("DB_NAME")
# =========================
# CONFIG
# =========================
DB_CONFIG = {
'host': DB_HOST,
'port': int(DB_PORT) if DB_PORT else 3306,
'user': DB_USER,
'password': DB_PASSWORD,
'database': DB_NAME
}
CSV_FILE = 'books.csv'
# =========================
# DB
# =========================
conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor()
# =========================
# ISBN GENERATOR
# =========================
used_isbns = set()
def generate_isbn():
while True:
isbn = "96" + "".join([str(random.randint(0, 9)) for _ in range(11)])
if isbn not in used_isbns:
used_isbns.add(isbn)
return isbn
def fix_isbn(isbn):
if not isbn or isbn.strip() == "" or isbn == "9999999999999" or not isbn.isdigit():
return generate_isbn()
if isbn in used_isbns:
return generate_isbn()
used_isbns.add(isbn)
return isbn
# =========================
# HELPERS
# =========================
def parse_list_field(value):
if not value:
return []
try:
return ast.literal_eval(value.strip())
except:
return [value]
def get_or_create_publisher(name):
name = name[:45]
cursor.execute("SELECT publisher_id FROM publisher WHERE name=%s", (name,))
res = cursor.fetchone()
if res:
return res[0]
cursor.execute("INSERT INTO publisher (name) VALUES (%s)", (name,))
conn.commit()
return cursor.lastrowid
def clean_author_name(name):
# usuwa nawiasy typu (Preface), (Editor), itp.
name = re.sub(r"\(.*?\)", "", name)
# usuwa podwójne spacje
name = " ".join(name.split())
return name.strip()
def parse_authors(value):
if not value:
return []
try:
parsed = ast.literal_eval(value)
if isinstance(parsed, list):
value = ",".join(parsed)
else:
value = str(parsed)
except:
pass
parts = value.split(",")
authors = []
for p in parts:
p = clean_author_name(p)
if len(p) < 2:
continue
if p.lower() in ["none", "unknown"]:
continue
authors.append(p)
return list(dict.fromkeys(authors))
def get_or_create_author(full_name):
parts = full_name.strip().split(" ")
first = parts[0][:45]
last = " ".join(parts[1:])[:45] if len(parts) > 1 else "Unknown"
cursor.execute(
"SELECT author_id FROM author WHERE first_name=%s AND last_name=%s",
(first, last)
)
res = cursor.fetchone()
if res:
return res[0]
cursor.execute(
"INSERT INTO author (first_name, last_name) VALUES (%s, %s)",
(first, last)
)
conn.commit()
return cursor.lastrowid
def get_or_create_category(name):
name = name[:45]
cursor.execute("SELECT category_id FROM category WHERE name=%s", (name,))
res = cursor.fetchone()
if res:
return res[0]
cursor.execute("INSERT IGNORE INTO category (name) VALUES (%s)", (name,))
conn.commit()
cursor.execute("SELECT category_id FROM category WHERE name=%s", (name,))
return cursor.fetchone()[0]
def extract_year(date_str):
try:
return datetime.strptime(date_str, "%m/%d/%y").year
except:
return random.randint(1990, 2020)
# =========================
# LIBRARIES
# =========================
libraries_data = [
("Biblioteka Nad Odrą", "Dolnośląskie", "Wrocław", "50-001", "ul. Mostowa", 12),
("Centrum Książki Aurora", "Mazowieckie", "Warszawa", "00-950", "ul. Świętokrzyska", 45),
("Biblioteka Morska", "Pomorskie", "Gdańsk", "80-001", "ul. Długa", 22),
("Krakowska Czytelnia Publiczna", "Małopolskie", "Kraków", "30-001", "ul. Grodzka", 8),
("Biblioteka Zachodnia", "Wielkopolskie", "Poznań", "60-001", "ul. Półwiejska", 19),
]
library_ids = []
for name, district, city, postal, street, house in libraries_data:
cursor.execute("""
INSERT INTO address (district, location, postal_code, street, house_number)
VALUES (%s, %s, %s, %s, %s)
""", (district, city, postal, street, house))
address_id = cursor.lastrowid
cursor.execute("""
INSERT INTO library (name, address_id)
VALUES (%s, %s)
""", (name, address_id))
library_ids.append(cursor.lastrowid)
conn.commit()
# =========================
# COUNT ROWS
# =========================
with open(CSV_FILE, encoding='utf-8') as f:
total_rows = sum(1 for _ in f) - 1
# =========================
# PROCESS CSV
# =========================
with open(CSV_FILE, newline='', encoding='utf-8') as f:
reader = csv.DictReader(f, delimiter=',', quotechar='"')
for row in tqdm(reader, total=total_rows, desc="Importing books"):
try:
title = (row['title'] or "Unknown")[:45]
isbn = fix_isbn((row['isbn'] or "").strip())
pages = int(row['pages']) if row['pages'] and row['pages'].isdigit() else None
publisher_name = (row['publisher'] or "Unknown")[:45]
year = extract_year(row['publishDate'])
rental_rate = round(random.uniform(5, 20), 2)
publisher_id = get_or_create_publisher(publisher_name)
# BOOK
cursor.execute("""
INSERT IGNORE INTO book (title, publication_year, pages, isbn, rental_rate, publisher_id)
VALUES (%s, %s, %s, %s, %s, %s)
""", (title, year, pages, isbn, rental_rate, publisher_id))
conn.commit()
cursor.execute("SELECT book_id FROM book WHERE isbn=%s", (isbn,))
res = cursor.fetchone()
if not res:
continue
book_id = res[0]
# AUTHORS
for a in parse_authors(row['author']):
author_id = get_or_create_author(a)
cursor.execute("""
INSERT IGNORE INTO book_author (book_id, author_id)
VALUES (%s, %s)
""", (book_id, author_id))
# CATEGORIES
for g in parse_list_field(row['genres']):
category_id = get_or_create_category(g)
cursor.execute("""
INSERT IGNORE INTO book_category (book_id, category_id)
VALUES (%s, %s)
""", (book_id, category_id))
# COPIES
for _ in range(random.randint(10, 100)):
lib_id = random.choice(library_ids)
cursor.execute("""
INSERT INTO copy (status, book_id, library_id)
VALUES ('available', %s, %s)
""", (book_id, lib_id))
conn.commit()
except Exception as e:
print("Error:", e)
continue
cursor.close()
conn.close()
print("DONE ✅")