nadish1210 commited on
Commit
a6bbdf8
·
verified ·
1 Parent(s): 1dabb82

Create model.py

Browse files
Files changed (1) hide show
  1. model.py +167 -0
model.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # model.py
2
+ from PIL import Image, ImageEnhance
3
+ import tempfile
4
+ import os
5
+ import cv2
6
+ import numpy as np
7
+ from PyPDF2 import PdfMerger, PdfReader, PdfWriter
8
+ import csv
9
+ import subprocess
10
+ import shutil
11
+ import pandas as pd
12
+ from typing import List, Tuple
13
+
14
+ # ---------------- IMAGE ENHANCEMENT & SCALING ---------------- #
15
+ def enhance_image(image: Image.Image, quality_level: str) -> Image.Image:
16
+ if image.mode != "RGB":
17
+ image = image.convert("RGB")
18
+
19
+ quality_map = {
20
+ "Low": (1.0, 1.0),
21
+ "Medium": (1.1, 1.05),
22
+ "High": (1.25, 1.1),
23
+ "Maximum": (1.4, 1.2)
24
+ }
25
+ sharp, contrast = quality_map.get(quality_level, (1.2, 1.1))
26
+
27
+ image = ImageEnhance.Sharpness(image).enhance(sharp)
28
+ image = ImageEnhance.Contrast(image).enhance(contrast)
29
+ return image
30
+
31
+ def compress_with_opencv(pil_img, quality=40):
32
+ img = np.array(pil_img)[:, :, ::-1] # PIL → BGR
33
+ encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), quality]
34
+ _, enc = cv2.imencode('.jpg', img, encode_param)
35
+ dec = cv2.imdecode(enc, cv2.IMREAD_COLOR)
36
+ return Image.fromarray(cv2.cvtColor(dec, cv2.COLOR_BGR2RGB))
37
+
38
+ # ---------------- IMAGE → PDF ---------------- #
39
+ def images_to_pdf(images, page_size: str, orientation: str, quality_level: str, compression: bool = True):
40
+ if not images:
41
+ return None, "⚠️ Please upload at least one image."
42
+
43
+ page_sizes = {
44
+ "A4": (2480, 3508),
45
+ "Letter": (2550, 3300),
46
+ "Legal": (2550, 4200),
47
+ "Original": None
48
+ }
49
+
50
+ processed = []
51
+ target_size = page_sizes.get(page_size)
52
+
53
+ for img_file in images:
54
+ if isinstance(img_file, str):
55
+ img = Image.open(img_file)
56
+ else:
57
+ img = Image.open(img_file.name) if hasattr(img_file, 'name') else img_file
58
+
59
+ img = enhance_image(img, quality_level)
60
+
61
+ if target_size:
62
+ if orientation == "Landscape":
63
+ target_size = (target_size[1], target_size[0])
64
+
65
+ bg = Image.new("RGB", target_size, (255, 255, 255))
66
+ img.thumbnail(target_size, Image.Resampling.LANCZOS)
67
+ offset = ((target_size[0] - img.width) // 2, (target_size[1] - img.height) // 2)
68
+ bg.paste(img, offset)
69
+ img = bg
70
+
71
+ if compression:
72
+ img = compress_with_opencv(img, quality=40)
73
+
74
+ processed.append(img)
75
+
76
+ output_path = os.path.join(tempfile.gettempdir(), "Nadish_Converted_File.pdf")
77
+ processed[0].save(output_path, "PDF", save_all=True, append_images=processed[1:], resolution=100)
78
+
79
+ size_mb = os.path.getsize(output_path) / (1024 * 1024)
80
+ return output_path, f"✅ PDF Created | Size: {size_mb:.2f} MB"
81
+
82
+ # ---------------- PDF MERGE ---------------- #
83
+ def merge_pdfs(pdf_files):
84
+ if not pdf_files:
85
+ return None, "⚠️ Please upload PDFs."
86
+
87
+ merger = PdfMerger()
88
+ for pdf in pdf_files:
89
+ merger.append(pdf.name if hasattr(pdf, 'name') else pdf)
90
+
91
+ output_path = os.path.join(tempfile.gettempdir(), "Nadish_Merged_File.pdf")
92
+ merger.write(output_path)
93
+ merger.close()
94
+
95
+ size_mb = os.path.getsize(output_path) / (1024 * 1024)
96
+ return output_path, f"✅ Merged {len(pdf_files)} PDFs | Size: {size_mb:.2f} MB"
97
+
98
+ # ---------------- PDF COMPRESSION ---------------- #
99
+ compression_map = {
100
+ "Maximum Compression (Smallest Size)": "screen",
101
+ "Balanced (Good Quality + Small Size)": "ebook",
102
+ "High Quality (Larger Size)": "printer",
103
+ "Original Quality (Least Compression)": "prepress"
104
+ }
105
+
106
+ def compress_pdf(pdf_file, compression_level: str):
107
+ if not pdf_file:
108
+ return None, "⚠️ Upload a PDF.", None
109
+
110
+ gs_level = compression_map[compression_level]
111
+
112
+ original_copy = os.path.join(tempfile.gettempdir(), "Nadish_Original.pdf")
113
+ shutil.copy(pdf_file.name if hasattr(pdf_file, 'name') else pdf_file, original_copy)
114
+
115
+ output_path = os.path.join(tempfile.gettempdir(), f"Nadish_Compressed_{gs_level}.pdf")
116
+
117
+ original_size = os.path.getsize(original_copy) / (1024 * 1024)
118
+
119
+ gs_command = [
120
+ "gs", "-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.4",
121
+ f"-dPDFSETTINGS=/{gs_level}",
122
+ "-dNOPAUSE", "-dQUIET", "-dBATCH",
123
+ "-dDetectDuplicateImages=true",
124
+ "-dCompressFonts=true",
125
+ "-dSubsetFonts=true",
126
+ f"-sOutputFile={output_path}", original_copy
127
+ ]
128
+
129
+ try:
130
+ subprocess.run(gs_command, check=True, capture_output=True)
131
+ new_size = os.path.getsize(output_path) / (1024 * 1024)
132
+ reduction = ((original_size - new_size) / original_size) * 100 if original_size > 0 else 0
133
+
134
+ table = f"""
135
+ | Metric | Value |
136
+ |-----------------------|----------------|
137
+ | Original Size (MB) | {original_size:.2f} |
138
+ | Compressed Size (MB) | {new_size:.2f} |
139
+ | Reduction (%) | {reduction:.1f}% |
140
+ """
141
+ return output_path, f"✅ Compression Successful!", table
142
+ except Exception as e:
143
+ return None, f"❌ Ghostscript Error: {str(e)}", None
144
+
145
+ # ---------------- FEEDBACK ---------------- #
146
+ def save_feedback(name_or_email: str, feedback_text: str, rating: str):
147
+ if not rating:
148
+ return "⚠️ Please select a rating."
149
+
150
+ file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "feedback.csv")
151
+ file_exists = os.path.isfile(file_path)
152
+
153
+ with open(file_path, mode="a", newline="", encoding="utf-8") as f:
154
+ writer = csv.writer(f)
155
+ if not file_exists:
156
+ writer.writerow(["Name", "Feedback", "Rating"])
157
+ writer.writerow([name_or_email or "Anonymous", feedback_text or "N/A", rating])
158
+
159
+ return "✅ Feedback saved! Thank you."
160
+
161
+ def show_feedback():
162
+ file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "feedback.csv")
163
+ if not os.path.isfile(file_path):
164
+ return "⚠️ No feedback yet."
165
+
166
+ df = pd.read_csv(file_path)
167
+ return df.to_markdown(index=False)