encrypt / app.py
lyimo's picture
Update app.py
66536af verified
raw
history blame
2.76 kB
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)
with open("hash.txt", "r") as file:
hashes = file.readlines()
for line in hashes:
saved_hash, description = line.strip().split(': ', 1)
if saved_hash == hash_code:
return f"Image is authentic. Description: {description}"
return "Image is new or modified."
# Main processing function
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."
# Gradio interface setup
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")
submit_button.click(process_image, inputs=[image_input, description_input], outputs=image_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()