import gradio as gr import hashlib import qrcode from PIL import Image, ImageDraw import os from PIL import Image import numpy as np # Function to hash image data def hash_image(image): image_data = image.tobytes() image_hash = hashlib.sha256(image_data).hexdigest() return image_hash # Function to generate QR code def generate_qr_code(data): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10, border=4, ) qr.add_data(data) qr.make(fit=True) qr_img = qr.make_image(fill='black', back_color='white') return qr_img def embed_qr_code(image, qr_img): if isinstance(image, np.ndarray): image = Image.fromarray(image.astype('uint8')) # Convert NumPy array to PIL Image image.paste(qr_img, (10, 10)) # Adjust position as needed return image # Function to save hash to file def save_hash(hash_code, description=""): with open("hash.txt", "a") as file: file.write(f"{hash_code}: {description}\n") # Function to check image authenticity def check_authenticity(image): hash_code = hash_image(image) try: with open("hash.txt", "r") as file: hashes = file.readlines() for line in hashes: parts = line.strip().split(': ', 1) if len(parts) == 2: saved_hash, description = parts if saved_hash == hash_code: return f"Image is authentic. Description: {description}" else: # Handle the case where there is no ':' or description saved_hash = parts[0] if saved_hash == hash_code: return "Image is authentic, but no description provided." except FileNotFoundError: return "Hash file not found. Please process an image first." return "Image is new or modified." def process_image(image, description): hash_code1 = hash_image(image) qr_img = generate_qr_code(hash_code1) qr_img = qr_img.resize((100, 100)) # Resize QR code as needed image_with_qr = embed_qr_code(image, qr_img) save_hash(hash_code1, description) hash_code2 = hash_image(image_with_qr) save_hash(hash_code2) return image_with_qr, "Image processed and hashes stored." # Update Gradio interface setup to handle the tuple output properly with gr.Blocks() as app: with gr.Tab("Upload and Process Image"): with gr.Row(): image_input = gr.Image(label="Upload Image") description_input = gr.Textbox(label="Description") submit_button = gr.Button("Process Image") image_output = gr.Image(label="Processed Image") message_output = gr.Textbox(label="Status Message") submit_button.click( process_image, inputs=[image_input, description_input], outputs=[image_output, message_output] ) with gr.Tab("Check Image Authenticity"): with gr.Row(): image_check_input = gr.Image(label="Upload Image to Verify") check_button = gr.Button("Check Authenticity") authenticity_output = gr.Textbox(label="Result") check_button.click(check_authenticity, inputs=[image_check_input], outputs=authenticity_output) # Launch the application app.launch()