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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import logging
|
| 3 |
+
from roboflow import Roboflow
|
| 4 |
+
from PIL import Image, ImageDraw
|
| 5 |
+
import cv2
|
| 6 |
+
import numpy as np
|
| 7 |
+
import os
|
| 8 |
+
from math import atan2, degrees
|
| 9 |
+
import asyncio
|
| 10 |
+
from pyppeteer import launch
|
| 11 |
+
|
| 12 |
+
# Configure logging
|
| 13 |
+
logging.basicConfig(
|
| 14 |
+
level=logging.DEBUG,
|
| 15 |
+
format='%(asctime)s - %(levelname)s - %(message)s',
|
| 16 |
+
handlers=[
|
| 17 |
+
logging.FileHandler("debug.log"),
|
| 18 |
+
logging.StreamHandler()
|
| 19 |
+
]
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
# Roboflow and model configuration
|
| 23 |
+
ROBOFLOW_API_KEY = "KUP9w62eUcD5PrrRMJsV" # Replace with your API key
|
| 24 |
+
PROJECT_NAME = "model_verification_project"
|
| 25 |
+
VERSION_NUMBER = 2
|
| 26 |
+
# FONT_PATH is no longer used since we generate handwriting via Calligraphr
|
| 27 |
+
# FONT_PATH = "./STEVEHANDWRITING-REGULAR.TTF"
|
| 28 |
+
|
| 29 |
+
# ----------------------------
|
| 30 |
+
# Pyppeteer: Generate handwriting image via Calligraphr
|
| 31 |
+
# ----------------------------
|
| 32 |
+
async def generate_handwriting_text_image(text_prompt, screenshot_path):
|
| 33 |
+
browser = await launch(headless=True, args=['--no-sandbox', '--disable-setuid-sandbox'])
|
| 34 |
+
page = await browser.newPage()
|
| 35 |
+
|
| 36 |
+
# Navigate to Calligraphr (adjust URL if needed)
|
| 37 |
+
await page.goto('https://www.calligraphr.com/en/font/', {'waitUntil': 'networkidle2'})
|
| 38 |
+
|
| 39 |
+
# Wait for the text input to be available and type the text
|
| 40 |
+
await page.waitForSelector('#text-input')
|
| 41 |
+
await page.type('#text-input', text_prompt)
|
| 42 |
+
|
| 43 |
+
# Wait for the page to render the handwriting preview
|
| 44 |
+
await asyncio.sleep(2)
|
| 45 |
+
|
| 46 |
+
# Take a screenshot of the area containing the rendered handwriting text.
|
| 47 |
+
# (Adjust the clip values if needed to capture the correct area.)
|
| 48 |
+
await page.screenshot({
|
| 49 |
+
'path': screenshot_path,
|
| 50 |
+
'clip': {'x': 100, 'y': 200, 'width': 600, 'height': 150}
|
| 51 |
+
})
|
| 52 |
+
|
| 53 |
+
await browser.close()
|
| 54 |
+
logging.debug(f"Calligraphr screenshot saved at {screenshot_path}")
|
| 55 |
+
return screenshot_path
|
| 56 |
+
|
| 57 |
+
# ----------------------------
|
| 58 |
+
# Helper: Detect paper angle within bounding box
|
| 59 |
+
# ----------------------------
|
| 60 |
+
def detect_paper_angle(image, bounding_box):
|
| 61 |
+
x1, y1, x2, y2 = bounding_box
|
| 62 |
+
|
| 63 |
+
# Crop the region of interest (ROI) based on the bounding box
|
| 64 |
+
roi = np.array(image)[y1:y2, x1:x2]
|
| 65 |
+
|
| 66 |
+
# Convert ROI to grayscale
|
| 67 |
+
gray = cv2.cvtColor(roi, cv2.COLOR_RGBA2GRAY)
|
| 68 |
+
|
| 69 |
+
# Apply edge detection
|
| 70 |
+
edges = cv2.Canny(gray, 50, 150)
|
| 71 |
+
|
| 72 |
+
# Detect lines using Hough Line Transformation
|
| 73 |
+
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, threshold=100, minLineLength=50, maxLineGap=10)
|
| 74 |
+
|
| 75 |
+
if lines is not None:
|
| 76 |
+
# Find the longest line (most prominent edge)
|
| 77 |
+
longest_line = max(lines, key=lambda line: np.linalg.norm((line[0][2] - line[0][0], line[0][3] - line[0][1])))
|
| 78 |
+
x1_line, y1_line, x2_line, y2_line = longest_line[0]
|
| 79 |
+
|
| 80 |
+
# Calculate the angle of the line relative to the horizontal axis
|
| 81 |
+
dx = x2_line - x1_line
|
| 82 |
+
dy = y2_line - y1_line
|
| 83 |
+
angle = degrees(atan2(dy, dx))
|
| 84 |
+
return angle # Angle of the paper
|
| 85 |
+
else:
|
| 86 |
+
return 0 # Default to no rotation if no lines are found
|
| 87 |
+
|
| 88 |
+
# ----------------------------
|
| 89 |
+
# Main processing function
|
| 90 |
+
# ----------------------------
|
| 91 |
+
def process_image(image, text):
|
| 92 |
+
try:
|
| 93 |
+
# Initialize Roboflow
|
| 94 |
+
rf = Roboflow(api_key=ROBOFLOW_API_KEY)
|
| 95 |
+
logging.debug("Initialized Roboflow API.")
|
| 96 |
+
project = rf.workspace().project(PROJECT_NAME)
|
| 97 |
+
logging.debug("Accessed project in Roboflow.")
|
| 98 |
+
model = project.version(VERSION_NUMBER).model
|
| 99 |
+
logging.debug("Loaded model from Roboflow.")
|
| 100 |
+
|
| 101 |
+
# Save input image temporarily
|
| 102 |
+
input_image_path = "/tmp/input_image.jpg"
|
| 103 |
+
image.save(input_image_path)
|
| 104 |
+
logging.debug(f"Input image saved to {input_image_path}.")
|
| 105 |
+
|
| 106 |
+
# Perform inference
|
| 107 |
+
logging.debug("Performing inference on the image...")
|
| 108 |
+
prediction = model.predict(input_image_path, confidence=70, overlap=50).json()
|
| 109 |
+
logging.debug(f"Inference result: {prediction}")
|
| 110 |
+
|
| 111 |
+
# Open the image for processing
|
| 112 |
+
pil_image = image.convert("RGBA")
|
| 113 |
+
logging.debug("Converted image to RGBA mode.")
|
| 114 |
+
|
| 115 |
+
# Iterate over detected objects (assumed white papers)
|
| 116 |
+
for obj in prediction['predictions']:
|
| 117 |
+
# Use white paper dimensions from the prediction
|
| 118 |
+
white_paper_width = obj['width']
|
| 119 |
+
white_paper_height = obj['height']
|
| 120 |
+
|
| 121 |
+
# Set padding (adjust percentages as needed)
|
| 122 |
+
padding_x = int(white_paper_width * 0.1)
|
| 123 |
+
padding_y = int(white_paper_height * 0.1)
|
| 124 |
+
|
| 125 |
+
box_width = white_paper_width - 2 * padding_x
|
| 126 |
+
box_height = white_paper_height - 2 * padding_y
|
| 127 |
+
logging.debug(f"Padded white paper dimensions: width={box_width}, height={box_height}.")
|
| 128 |
+
|
| 129 |
+
# Calculate padded coordinates
|
| 130 |
+
x1_padded = int(obj['x'] - white_paper_width / 2 + padding_x)
|
| 131 |
+
y1_padded = int(obj['y'] - white_paper_height / 2 + padding_y)
|
| 132 |
+
x2_padded = int(obj['x'] + white_paper_width / 2 - padding_x)
|
| 133 |
+
y2_padded = int(obj['y'] + white_paper_height / 2 - padding_y)
|
| 134 |
+
|
| 135 |
+
# Detect paper angle
|
| 136 |
+
angle = detect_paper_angle(np.array(image), (x1_padded, y1_padded, x2_padded, y2_padded))
|
| 137 |
+
logging.debug(f"Detected paper angle: {angle} degrees.")
|
| 138 |
+
|
| 139 |
+
# For debugging: draw the bounding box (optional)
|
| 140 |
+
debug_layer = pil_image.copy()
|
| 141 |
+
debug_draw = ImageDraw.Draw(debug_layer)
|
| 142 |
+
debug_draw.rectangle([(x1_padded, y1_padded), (x2_padded, y2_padded)], outline="red", width=3)
|
| 143 |
+
debug_layer.save("/tmp/debug_bounding_box.png")
|
| 144 |
+
logging.debug("Saved bounding box debug image to /tmp/debug_bounding_box.png.")
|
| 145 |
+
|
| 146 |
+
# --------------------------------------------
|
| 147 |
+
# New: Generate handwriting image via Calligraphr
|
| 148 |
+
# --------------------------------------------
|
| 149 |
+
handwriting_path = "/tmp/handwriting.png"
|
| 150 |
+
try:
|
| 151 |
+
# Run the async Pyppeteer function to generate handwriting
|
| 152 |
+
handwriting_path = asyncio.run(generate_handwriting_text_image(text, handwriting_path))
|
| 153 |
+
except Exception as e:
|
| 154 |
+
logging.error(f"Error generating handwriting image: {e}")
|
| 155 |
+
continue # Optionally, you could fall back to another method here
|
| 156 |
+
|
| 157 |
+
# Open the generated handwriting image
|
| 158 |
+
handwriting_img = Image.open(handwriting_path).convert("RGBA")
|
| 159 |
+
# Resize handwriting image to fit the white paper box
|
| 160 |
+
handwriting_img = handwriting_img.resize((box_width, box_height), Image.ANTIALIAS)
|
| 161 |
+
|
| 162 |
+
# Rotate the handwriting image to align with the detected paper angle
|
| 163 |
+
rotated_handwriting = handwriting_img.rotate(-angle, resample=Image.BICUBIC, expand=True)
|
| 164 |
+
|
| 165 |
+
# Composite the rotated handwriting image onto a transparent layer,
|
| 166 |
+
# then overlay it on the original image
|
| 167 |
+
text_layer = Image.new("RGBA", pil_image.size, (255, 255, 255, 0))
|
| 168 |
+
paste_x = int(obj['x'] - rotated_handwriting.size[0] / 2)
|
| 169 |
+
paste_y = int(obj['y'] - rotated_handwriting.size[1] / 2)
|
| 170 |
+
text_layer.paste(rotated_handwriting, (paste_x, paste_y), rotated_handwriting)
|
| 171 |
+
pil_image = Image.alpha_composite(pil_image, text_layer)
|
| 172 |
+
logging.debug("Handwriting layer composited onto the original image.")
|
| 173 |
+
|
| 174 |
+
# Save and return output image path
|
| 175 |
+
output_image_path = "/tmp/output_image.png"
|
| 176 |
+
pil_image.convert("RGB").save(output_image_path)
|
| 177 |
+
logging.debug(f"Output image saved to {output_image_path}.")
|
| 178 |
+
return output_image_path
|
| 179 |
+
|
| 180 |
+
except Exception as e:
|
| 181 |
+
logging.error(f"Error during image processing: {e}")
|
| 182 |
+
return None
|
| 183 |
+
|
| 184 |
+
# ----------------------------
|
| 185 |
+
# Gradio interface function
|
| 186 |
+
# ----------------------------
|
| 187 |
+
def gradio_inference(image, text):
|
| 188 |
+
logging.debug("Starting Gradio inference.")
|
| 189 |
+
result_path = process_image(image, text)
|
| 190 |
+
if result_path:
|
| 191 |
+
logging.debug("Gradio inference successful.")
|
| 192 |
+
return result_path, result_path, "Processing complete! Download the image below."
|
| 193 |
+
logging.error("Gradio inference failed.")
|
| 194 |
+
return None, None, "An error occurred while processing the image. Please check the logs."
|
| 195 |
+
|
| 196 |
+
# ----------------------------
|
| 197 |
+
# Gradio interface definition
|
| 198 |
+
# ----------------------------
|
| 199 |
+
interface = gr.Interface(
|
| 200 |
+
fn=gradio_inference,
|
| 201 |
+
inputs=[
|
| 202 |
+
gr.Image(type="pil", label="Upload an Image"),
|
| 203 |
+
gr.Textbox(label="Enter Text to Overlay")
|
| 204 |
+
],
|
| 205 |
+
outputs=[
|
| 206 |
+
gr.Image(label="Processed Image Preview"), # Preview processed image
|
| 207 |
+
gr.File(label="Download Processed Image"), # Download the image
|
| 208 |
+
gr.Textbox(label="Status") # Status message
|
| 209 |
+
],
|
| 210 |
+
title="Roboflow Detection with Handwriting Overlay",
|
| 211 |
+
description="Upload an image, enter text to overlay. The Roboflow model detects the white paper area, and a handwriting image is generated via Calligraphr using Pyppeteer. The output image is composited accordingly.",
|
| 212 |
+
allow_flagging="never"
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
# Launch the Gradio app
|
| 216 |
+
if __name__ == "__main__":
|
| 217 |
+
logging.debug("Launching Gradio interface.")
|
| 218 |
+
interface.launch(share=True)
|