fantos commited on
Commit
32b5c3d
·
verified ·
1 Parent(s): e1f7ceb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -44
app.py CHANGED
@@ -1,45 +1,139 @@
 
 
1
  import gradio as gr
2
- import utils
3
-
4
- def choose_encode(inp_im, inp_mark, cho):
5
- if cho == "stegan":
6
- out_im, out_msg = utils.encode(inp_im, inp_mark)
7
- return out_im, out_msg
8
- if cho == "pnginfo":
9
- out_im, out_msg = utils.png_encode(inp_im, inp_mark)
10
- return out_im, out_msg
11
-
12
- css = """
13
- footer {
14
- visibility: hidden;
15
- }
16
- """
17
-
18
- with gr.Blocks(css=css) as app:
19
- gr.HTML("""<a href="https://visitorbadge.io/status?path=https%3A%2F%2Ffantos-watermark3.hf.space">
20
- <img src="https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Ffantos-watermark3.hf.space&countColor=%23263759" />
21
- </a>""")
22
-
23
- with gr.Tab("Add Watermark"):
24
- cho = gr.Radio(choices=["stegan", "pnginfo"], value="stegan")
25
- with gr.Row():
26
- with gr.Column():
27
- inp_im = gr.Image(label="Input Image", type="filepath")
28
- inp_mark = gr.Textbox(label="Watermark")
29
- mark_btn = gr.Button("Add Watermark")
30
- msg_box = gr.Textbox(label="System Message")
31
- with gr.Column():
32
- out_im = gr.Image(label="Watermarked Image")
33
-
34
- with gr.Tab("Detect Watermark"):
35
- with gr.Row():
36
- with gr.Column():
37
- det_im = gr.Image(label="Watermarked Image", type="filepath")
38
- det_btn = gr.Button("Detect")
39
- with gr.Column():
40
- det_msg = gr.Textbox(label="Detected Watermark", lines=6, max_lines=50)
41
-
42
- mark_btn.click(choose_encode, [inp_im, inp_mark, cho], [out_im, msg_box])
43
- det_btn.click(utils.decode, [det_im], det_msg)
44
-
45
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+
3
  import gradio as gr
4
+ from utils import WatermarkProcessor
5
+ import json
6
+ import tempfile
7
+ import os
8
+ from datetime import datetime
9
+ import cv2
10
+ from PIL import Image
11
+ import numpy as np
12
+
13
+ class WatermarkGUI:
14
+ def __init__(self):
15
+ self.processor = WatermarkProcessor()
16
+ self.create_interface()
17
+
18
+ def process_watermark(self, image, watermark_text, author, purpose, opacity):
19
+ """Process watermark with metadata"""
20
+ if image is None or watermark_text.strip() == "":
21
+ return None, "Please provide both image and watermark text"
22
+
23
+ metadata = {
24
+ "author": author,
25
+ "purpose": purpose,
26
+ "opacity": opacity
27
+ }
28
+
29
+ # Save temporary image
30
+ temp_path = tempfile.mktemp(suffix='.png')
31
+ Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)).save(temp_path)
32
+
33
+ # Add watermark
34
+ result_path, message = self.processor.encode(temp_path, watermark_text, metadata)
35
+
36
+ if "Error" in message:
37
+ return None, message
38
+
39
+ # Generate quality report
40
+ quality_report = self.processor.analyze_quality(temp_path, result_path)
41
+ quality_data = json.loads(quality_report)
42
+
43
+ # Create formatted report
44
+ report = f"""
45
+ ### Watermark Quality Report
46
+ - Quality Score: {quality_data['quality_score']}%
47
+ - PSNR: {quality_data['psnr']} dB
48
+ - Histogram Similarity: {quality_data['histogram_similarity'] * 100:.2f}%
49
+ - Modified Pixels: {quality_data['modified_pixels']:,}
50
+
51
+ ### Metadata
52
+ - Author: {author}
53
+ - Purpose: {purpose}
54
+ - Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
55
+ """
56
+
57
+ os.remove(temp_path)
58
+ return cv2.imread(result_path), report
59
+
60
+ def detect_watermark(self, image):
61
+ """Detect and extract watermark"""
62
+ if image is None:
63
+ return "Please provide an image"
64
+
65
+ # Save temporary image
66
+ temp_path = tempfile.mktemp(suffix='.png')
67
+ Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)).save(temp_path)
68
+
69
+ # Extract watermark
70
+ result = self.processor.decode(temp_path)
71
+ os.remove(temp_path)
72
+
73
+ try:
74
+ # Parse JSON result
75
+ data = json.loads(result)
76
+ report = f"""
77
+ ### Extracted Watermark
78
+ Text: {data['text']}
79
+
80
+ ### Metadata
81
+ - Timestamp: {data['timestamp']}
82
+ - Author: {data['metadata'].get('author', 'N/A')}
83
+ - Purpose: {data['metadata'].get('purpose', 'N/A')}
84
+ """
85
+ return report
86
+ except:
87
+ return result
88
+
89
+ def create_interface(self):
90
+ """Create Gradio interface"""
91
+ with gr.Blocks(css="footer {visibility: hidden}") as self.interface:
92
+ gr.Markdown("# Enhanced Image Watermarking System")
93
+
94
+ with gr.Tabs():
95
+ # Add Watermark Tab
96
+ with gr.Tab("Add Watermark"):
97
+ with gr.Row():
98
+ with gr.Column():
99
+ input_image = gr.Image(label="Input Image", type="numpy")
100
+ watermark_text = gr.Textbox(label="Watermark Text")
101
+ author = gr.Textbox(label="Author", placeholder="Enter author name")
102
+ purpose = gr.Textbox(label="Purpose", placeholder="Enter watermark purpose")
103
+ opacity = gr.Slider(minimum=0.1, maximum=1.0, value=0.3,
104
+ label="Watermark Opacity")
105
+
106
+ with gr.Row():
107
+ process_btn = gr.Button("Add Watermark", variant="primary")
108
+
109
+ with gr.Column():
110
+ result_image = gr.Image(label="Watermarked Image")
111
+ quality_report = gr.Markdown(label="Quality Report")
112
+
113
+ # Detect Watermark Tab
114
+ with gr.Tab("Detect Watermark"):
115
+ with gr.Row():
116
+ detect_image = gr.Image(label="Input Image", type="numpy")
117
+ detect_result = gr.Markdown(label="Detected Watermark")
118
+ detect_btn = gr.Button("Detect Watermark")
119
+
120
+ # Event handlers
121
+ process_btn.click(
122
+ fn=self.process_watermark,
123
+ inputs=[input_image, watermark_text, author, purpose, opacity],
124
+ outputs=[result_image, quality_report]
125
+ )
126
+
127
+ detect_btn.click(
128
+ fn=self.detect_watermark,
129
+ inputs=[detect_image],
130
+ outputs=detect_result
131
+ )
132
+
133
+ def launch(self, *args, **kwargs):
134
+ """Launch the interface"""
135
+ self.interface.launch(*args, **kwargs)
136
+
137
+ if __name__ == "__main__":
138
+ app = WatermarkGUI()
139
+ app.launch()