-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
411 lines (335 loc) · 14.7 KB
/
app.py
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
from flask import Flask, render_template, Response,redirect,request, url_for, send_file
import fitz
import os
import io
import base64
import json
import pandas as pd
from urllib.parse import quote
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from time import sleep
import sys
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = "uploads"
pdffile = None
pdffilepath = None
csvfile = None
csvfilepath = None
img_urls = None
textComps = None
bride_groom_Name = None
driver = None
current = os.path.dirname(os.path.realpath(__file__))
sys.path.append(current)
CHROME_PATH = "/static/public/chromedriver-mac-arm64/chromedriver"
EL_ADDRESS = {
"new_chat_el" : '//div[@title="Search input textbox"]',
"attachment_el" : "//div[@title='Attach']",
"doc_el" : "//input[@accept = '*']",
"send_el" : '//div[@aria-label="Send"]'
}
def get_chrome_driver():
chrome_options = webdriver.ChromeOptions()
# Specify the remote debugging port
chrome_options.add_experimental_option("debuggerAddress", "localhost:9222")
# Initialize the driver
driver = webdriver.Chrome(options=chrome_options)
try:
driver.get("https://web.whatsapp.com")
el = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.XPATH, EL_ADDRESS["new_chat_el"]))
)
except Exception as err:
print("Not connected Whatsapp")
return driver
def savePageImages():
try:
global img_urls
pdf = fitz.open(pdffilepath)
pageCount = len(pdf)
img_urls = []
for i in range(pageCount):
page = pdf[i]
pix = page.get_pixmap()
print("displayed pages' width and height: ", pix.width, pix.height)
img_bytes = pix.tobytes('png')
base64_encoded_img = base64.b64encode(img_bytes).decode('utf-8')
data_url = f"data:image/png;base64,{base64_encoded_img}"
img_urls.append(data_url)
return len(img_urls)>0
except Exception as e:
print("error while getting images ",e)
return False
def csv_to_json(csv_file_path):
# Read CSV file and convert it to a list of dictionaries
data = pd.read_csv(csv_file_path)
json_str = data.to_json(orient='records')
json_obj = json.loads(json_str)
print(data.to_json(orient='values', indent=0))
return json_obj
@app.route('/')
def index():
global pdffile
if(pdffile==None):
print("Invitation file is not selected")
return render_template("uploadFile.html")
else:
isSaved = savePageImages()
if(isSaved):
return render_template('editPdf.html',img_urls=img_urls)
print("PdfFile not saved")
pdffile=None
return render_template("uploadFile.html")
@app.route('/csvUpload')
def csvUpload():
global csvfile
if(csvfile==None):
print("Data file not selected")
return render_template("uploadCsvFile.html")
else:
print("Csv file received", csvfile, csvfilepath)
data = csv_to_json(csvfilepath)
print(data)
data = editPdfs(data)
return render_template("csvContent.html", data=data)
def editPdfs(data):
if textComps:
for i, row in enumerate(data):
pdf = fitz.open(pdffilepath)
name = row['Name']
for (id,textComp) in textComps.items():
print(f"textComp: {textComp}")
# print(f"pdf: {pdf}")
page = pdf.load_page(textComp["page"]-1)
print("Page size of fitz pdf:", page.rect.width, page.rect.height)
# appearent x, y -> 500, 800
# actually x, y -> 446, 697
# (x1, y1) and (x2, y2) to (x1', y1') and (x2', y2')
# x' = x1' + (x - x1)(x2' - x1')/(x2 - x1)
# y' = y1' + (y - y1)(y2' - y1')/(y2 - y1)
# y1 => 0 -> -13 y2 => 802 -> 830
# x1 => 0 -> 0 x2 => 502 -> 520
x1, y1 = 0, 0
x1_new, y1_new = 0, -13
x2, y2 = 544, 840
x2_new, y2_new = 514, 801
x = int(textComp["x"].replace("px",""))
y = int(textComp["y"].replace("px",""))
# print("First x and y", x, y)
x = x1_new + (x - x1)*(x2_new - x1_new)/(x2 - x1)
y = y1_new + (y - y1)*(y2_new - y1_new)/(y2 - y1)
# print("After x and y", x, y)
textHtml = f"<p style='font-weight:bolder; color: {textComp['color']};font-size:{textComp['fontSize'] + 2}px;'>{name}</p>"
page.insert_htmlbox(fitz.Rect(x,y,x+1000,y+1000),textHtml)
print(f"text added : {x} {y}")
os.makedirs(os.path.join(f'{bride_groom_Name}', 'createdPdfs'), exist_ok=True)
page = pdf[-1]
for i in range(1,10):
link = f"<a style='font-size: 15px; color: {textComp['color']} href='https://672c59a63d48ece92d14.appwrite.global?invitee_name={'+'.join(invitee_name.split())}&person_name={'+'.join(name.split())}&num_persons={i}' >{i}</a>"
x1 = 100 + i * 20
y1 = 500
page.insert_htmlbox(fitz.Rect(x1, y1,x1+10,y1+10),link)
pdfPath = os.path.join(f'{bride_groom_Name}/createdPdfs',f'{name}.pdf')
data[i]['filePath'] = pdfPath
pdf.save(f"{bride_groom_Name}/createdPdfs/{name}.pdf")
return data
@app.route('/pdfSubmit', methods=['GET', 'POST'])
def pdfSubmit():
global pdffile, pdffilepath
if(request.method=="POST"):
pdffile = request.files["pdfFile"]
if(pdffile.filename!=""):
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
pdffilepath = os.path.join(app.config['UPLOAD_FOLDER'], pdffile.filename)
pdffile.save(pdffilepath)
else:
pdffile=pdfilepath=None
print(pdffile, pdffilepath)
return redirect("/")
@app.route('/csvSubmit', methods=['GET', 'POST'])
def csvSubmit():
print("Submitting CSV File....")
global csvfile, csvfilepath
if(request.method=="POST"):
print(request)
csvfile = request.files["csvFile"]
if(csvfile.filename!=""):
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
csvfilepath = os.path.join(app.config['UPLOAD_FOLDER'], csvfile.filename)
csvfile.save(csvfilepath)
else:
csvfile=csvfilepath=None
print(csvfile, csvfilepath)
return redirect("/csvUpload")
def generatePdf():
try:
pdf = fitz.open(pdffilepath)
for (id,textComp) in textComps.items():
# print(f"textComp: {textComp}")
# print(f"pdf: {pdf}")
page = pdf.load_page(textComp["page"]-1)
print("Page size of fitz pdf:", page.rect.width, page.rect.height)
# appearent x, y -> 500, 800
# actually x, y -> 446, 697
# (x1, y1) and (x2, y2) to (x1', y1') and (x2', y2')
# x' = x1' + (x - x1)(x2' - x1')/(x2 - x1)
# y' = y1' + (y - y1)(y2' - y1')/(y2 - y1)
# y1 => 0 -> -13 y2 => 802 -> 830
# x1 => 0 -> 0 x2 => 502 -> 520
# needed x = 192, y = 246
# in real x = 199, y = 270
x1, y1 = 0, 0
x1_new, y1_new = -5, -20
x2, y2 = 544, 840
x2_new, y2_new = 460, 700
x = int(textComp["x"].replace("px",""))
y = int(textComp["y"].replace("px",""))
x = x1_new + (x - x1)*(x2_new - x1_new)/(x2 - x1)
y = y1_new + (y - y1)*(y2_new - y1_new)/(y2 - y1)
textHtml = f"<p style='color: {textComp['color']};font-size:{textComp['fontSize'] + 2}px; font-weight: bolder;'>{textComp['textContent']}</p>"
print(textHtml)
page.insert_htmlbox(fitz.Rect(x,y,x+1000,y+1000),textHtml)
print(f"text added : {x} {y}")
os.makedirs(os.path.join(f'{bride_groom_Name}', 'editedSamplePdfs'), exist_ok=True)
page = pdf[-1]
for i in range(1,11):
color = textComp['color']
person_name = quote(textComp['textContent'], safe="")
link = f"https://672c59a63d48ece92d14.appwrite.global?invitee_name={'+'.join(invitee_name.split())}&person_name={'+'.join(person_name.split())}&num_persons={i}"
html_box = f"<a href='{link}' ><p style='color:{color}; text-decoration:none; font-size: 15px; font-weight: bolder;'>{i}</p></a>"
percentage_margin = 20
pwidth, pheight = page.rect.width, page.rect.height
pwidth_eff = pwidth * (1 - 2 * percentage_margin/100)
x_interval = pwidth_eff / (10 - 1)
x_start = pwidth * percentage_margin / 100
x1, y1 = x_start + (i-1) * x_interval, pheight * 0.6
height, width = 50, 50
rect = fitz.Rect(x1, y1, x1 + height, y1 + width)
page.insert_htmlbox(rect, html_box)
pdf.save(f"{bride_groom_Name}/editedSamplePdfs/{textComp['textContent']}.pdf")
return pdf
except Exception as e:
print("exception in generatePdf : ",e)
return None
@app.route('/generatePdf', methods = ['GET', 'POST'])
def createPdf():
name = request.args.get('name')
try:
pdf = fitz.open(pdffilepath)
for (id,textComp) in textComps.items():
# print(f"textComp: {textComp}")
# print(f"pdf: {pdf}")
page = pdf.load_page(textComp["page"]-1)
print("Page size of fitz pdf:", page.rect.width, page.rect.height)
# appearent x, y -> 500, 800
# actually x, y -> 446, 697
# (x1, y1) and (x2, y2) to (x1', y1') and (x2', y2')
# x' = x1' + (x - x1)(x2' - x1')/(x2 - x1)
# y' = y1' + (y - y1)(y2' - y1')/(y2 - y1)
# y1 => 0 -> -13 y2 => 802 -> 830
# x1 => 0 -> 0 x2 => 502 -> 520
# needed x = 192, y = 246
# in real x = 199, y = 270
x1, y1 = 0, 0
x1_new, y1_new = 0, -13
x2, y2 = 544, 840
x2_new, y2_new = 514, 801
x = int(textComp["x"].replace("px",""))
y = int(textComp["y"].replace("px",""))
x = x1_new + (x - x1)*(x2_new - x1_new)/(x2 - x1)
y = y1_new + (y - y1)*(y2_new - y1_new)/(y2 - y1)
textHtml = f"<p style='font-weight:bolder' > <p style='color: {textComp['color']};font-size:{textComp['fontSize'] + 2}px;'>{textComp['textContent']}</p></p>"
page.insert_htmlbox(fitz.Rect(x,y,x+1000,y+1000),textHtml, "font-weight:bolder;")
print(f"text added : {x} {y}")
os.makedirs(os.path.join(f'{bride_groom_Name}', 'editedSamplePdfs'), exist_ok=True)
page = pdf[-1]
for i in range(1,10):
color = textComp['color']
link = f"https://672c59a63d48ece92d14.appwrite.global?invitee_name={'+'.join(invitee_name.split())}&person_name={'+'.join(name.split())}&num_persons={i}"
html_box = f"<a style='font-size: 20px; color: {color}' href='{link}' ><p style='color: {textComp['color']};font-size:{textComp['fontSize'] + 2}px;'>{i}</p></a>"
x1 = 100 + i * 50
y1 = 500
page.insert_htmlbox(fitz.Rect(x1, y1,x1+20,y1+20),html_box)
path =f"{bride_groom_Name}/createdPdfs/{name}.pdf"
pdf.save(path)
return path
except Exception as e:
print("exception in generatePdf : ",e)
return None
@app.route('/textSubmit', methods=['GET', 'POST'])
def textSubmit():
global textComps
if(request.method=="POST"):
textComps = request.form["textComps"]
textComps = json.loads(textComps)
output = generatePdf()
if(output!=None):
outputBuffer = io.BytesIO()
output.save(outputBuffer)
return outputBuffer.getvalue()
return redirect("/")
@app.route('/<path:filepath>', methods = ['GET'])
def download(filepath):
print(filepath)
return send_file(filepath, as_attachment=True)
@app.route('/pdfViewer/<path:filepath>', methods = ['GET','POST'])
def viewPdf(filepath):
print(filepath)
pdf = fitz.open(filepath)
if(pdf != None):
outputBuffer = io.BytesIO()
pdf.save(outputBuffer)
return outputBuffer.getvalue()
return render_template("/csvContent")
def open_attachment(name_or_number):
# driver.find_element_by_xpath(EL_ADDRESS["new_chat_el"]).send_keys(name_or_number,"\n")
# finding new_chat_el and sending details
print("sending to ", name_or_number)
el = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.XPATH, EL_ADDRESS["new_chat_el"]))
)
el.clear()
el.send_keys(name_or_number,"\n")
# print("attach finding")
el = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.XPATH, EL_ADDRESS["attachment_el"]))
)
el.click()
# print("attach clicked")
def send_pdf(saved_name, send_to):
print('Sending pdf', saved_name, 'to', send_to)
open_attachment(send_to)
# print("doc finding")
doc_el = WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.XPATH, EL_ADDRESS["doc_el"]))
)
doc_el.send_keys(saved_name)
# print("doc done")
print("send btn finding")
el = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, EL_ADDRESS["send_el"]))
)
el.click()
print("send clicked")
sleep(1)
@app.route('/sendFile', methods = ['GET','POST'])
def sendFile():
file = request.args.get('file', type=str)
number = request.args.get('to', type=str)
send_pdf(current + '/' + file, number)
return render_template('/csvContent.html')
if __name__ == '__main__':
# Example usage
# driver = get_chrome_driver()
os.makedirs('local', exist_ok=True)
global invitee_name
invitee_name = "Tilak Tejani"
bride_groom_Name = 'local/kaushalBhikadiya'
os.makedirs(bride_groom_Name, exist_ok=True)
app.config['UPLOAD_FOLDER'] = os.path.join(bride_groom_Name, "uploads")
app.run(debug=True)
driver.close()
# generatePdf()