File size: 23,037 Bytes
0f5fe41 225070f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 | from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import HTMLResponse
from PIL import Image
from PIL.ExifTags import TAGS
from datetime import datetime
import os
import tempfile
app = FastAPI(title="Image Metadata Extractor", description="Upload an image to extract its metadata including creation timestamp")
def get_image_metadata(image_path):
"""Extract metadata from an image file"""
result = {
"filename": os.path.basename(image_path),
"format": None,
"size": None,
"mode": None,
"exif_data": {},
"creation_date": None,
"file_system_creation_time": None,
"error": None
}
try:
# Open the image
with Image.open(image_path) as img:
result["format"] = img.format
result["size"] = img.size
result["mode"] = img.mode
# Get EXIF data
exif_data = img._getexif()
if exif_data is not None:
exif_dict = {}
for tag_id, value in exif_data.items():
tag = TAGS.get(tag_id, tag_id)
exif_dict[tag] = str(value)
result["exif_data"] = exif_dict
# Try to extract creation date from common EXIF tags
date_tags = ['DateTime', 'DateTimeOriginal', 'DateTimeDigitized']
for tag in date_tags:
# Find the tag ID for the current tag
tag_id = None
for tid, tname in TAGS.items():
if tname == tag:
tag_id = tid
break
if tag_id and tag_id in exif_data:
raw_date = exif_data[tag_id]
try:
# Handle different date formats
if isinstance(raw_date, bytes):
raw_date = raw_date.decode('utf-8')
# Try different date formats
formats_to_try = [
'%Y:%m:%d %H:%M:%S',
'%Y-%m-%d %H:%M:%S',
'%Y/%m/%d %H:%M:%S'
]
creation_date = None
for fmt in formats_to_try:
try:
creation_date = datetime.strptime(str(raw_date), fmt)
break
except ValueError:
continue
if creation_date:
result["creation_date"] = {
"source": tag,
"date": creation_date.isoformat()
}
break
except Exception:
continue
# Fallback: Use file system creation time
stat = os.stat(image_path)
creation_time = stat.st_ctime
result["file_system_creation_time"] = datetime.fromtimestamp(creation_time).isoformat()
except Exception as e:
result["error"] = str(e)
return result
@app.get("/", response_class=HTMLResponse)
async def read_root():
"""Serve the HTML frontend"""
return """
<!DOCTYPE html>
<html>
<head>
<title>Image Metadata Extractor</title>
<style>
:root {
--primary-color: #4361ee;
--secondary-color: #3f37c9;
--accent-color: #4895ef;
--success-color: #4cc9f0;
--light-color: #f8f9fa;
--dark-color: #212529;
--danger-color: #f72585;
--warning-color: #f8961e;
--info-color: #56cfe1;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1000px;
margin: 0 auto;
}
header {
text-align: center;
padding: 30px 0;
color: white;
text-shadow: 0 2px 4px rgba(0,0,0,0.3);
}
h1 {
font-size: 2.5rem;
margin-bottom: 10px;
}
.subtitle {
font-size: 1.2rem;
opacity: 0.9;
}
.card {
background: rgba(255, 255, 255, 0.95);
border-radius: 15px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
padding: 30px;
margin-bottom: 30px;
backdrop-filter: blur(10px);
}
.upload-area {
border: 3px dashed var(--accent-color);
border-radius: 12px;
padding: 40px 20px;
text-align: center;
transition: all 0.3s ease;
background: rgba(72, 149, 239, 0.05);
cursor: pointer;
}
.upload-area:hover {
border-color: var(--primary-color);
background: rgba(67, 97, 238, 0.1);
transform: translateY(-2px);
}
.upload-area.active {
border-color: var(--success-color);
background: rgba(76, 201, 240, 0.1);
}
.upload-icon {
font-size: 4rem;
color: var(--accent-color);
margin-bottom: 20px;
}
.upload-text {
font-size: 1.3rem;
color: var(--dark-color);
margin-bottom: 15px;
}
.upload-hint {
color: #6c757d;
margin-bottom: 20px;
}
.file-input {
display: none;
}
.upload-btn {
background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
color: white;
border: none;
padding: 15px 40px;
font-size: 1.1rem;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(67, 97, 238, 0.3);
}
.upload-btn:hover {
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(67, 97, 238, 0.4);
}
.upload-btn:active {
transform: translateY(0);
}
.result-container {
display: none;
}
.result-header {
text-align: center;
margin-bottom: 25px;
color: var(--dark-color);
}
.metadata-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin-bottom: 30px;
}
.metadata-card {
background: white;
border-radius: 10px;
padding: 20px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
border-left: 4px solid var(--primary-color);
transition: transform 0.3s ease;
}
.metadata-card:hover {
transform: translateY(-5px);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}
.metadata-card.creation {
border-left-color: var(--success-color);
}
.metadata-card.exif {
border-left-color: var(--warning-color);
}
.metadata-card h3 {
color: var(--primary-color);
margin-bottom: 15px;
font-size: 1.3rem;
}
.metadata-card.creation h3 {
color: var(--success-color);
}
.metadata-card.exif h3 {
color: var(--warning-color);
}
.metadata-item {
margin: 12px 0;
padding: 10px;
background: #f8f9fa;
border-radius: 8px;
border-left: 3px solid var(--accent-color);
}
.metadata-item strong {
display: block;
color: var(--dark-color);
margin-bottom: 5px;
}
.metadata-item span {
color: #6c757d;
}
.exif-list {
max-height: 300px;
overflow-y: auto;
}
.exif-item {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #eee;
}
.exif-item:last-child {
border-bottom: none;
}
.exif-key {
font-weight: 500;
color: var(--dark-color);
}
.exif-value {
color: #6c757d;
text-align: right;
max-width: 60%;
word-break: break-word;
}
.error {
background: #ffebee;
border-left-color: var(--danger-color);
color: var(--danger-color);
}
.error strong {
color: var(--danger-color);
}
.actions {
text-align: center;
margin-top: 20px;
}
.reset-btn {
background: transparent;
color: var(--primary-color);
border: 2px solid var(--primary-color);
padding: 12px 30px;
font-size: 1rem;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease;
}
.reset-btn:hover {
background: var(--primary-color);
color: white;
}
footer {
text-align: center;
color: rgba(255, 255, 255, 0.8);
padding: 20px 0;
font-size: 0.9rem;
}
@media (max-width: 768px) {
.metadata-grid {
grid-template-columns: 1fr;
}
h1 {
font-size: 2rem;
}
.card {
padding: 20px;
}
}
</style>
</head>
<body>
<div class="container">
<header>
<h1>📸 Image Metadata Extractor</h1>
<p class="subtitle">Upload any image to extract detailed metadata including creation timestamps</p>
</header>
<main>
<div class="card">
<div class="upload-area" id="upload-area">
<div class="upload-icon">📁</div>
<h2 class="upload-text">Drag & Drop your image here</h2>
<p class="upload-hint">or click to browse files</p>
<input type="file" id="file-input" class="file-input" accept="image/*">
<button class="upload-btn" id="upload-btn">Select Image</button>
</div>
</div>
<div class="card result-container" id="result-container">
<h2 class="result-header">Image Metadata Analysis</h2>
<div class="metadata-grid" id="metadata-content"></div>
<div class="actions">
<button class="reset-btn" id="reset-btn">Analyze Another Image</button>
</div>
</div>
</main>
<footer>
<p>Image Metadata Extractor © 2025 | Extract creation timestamps and EXIF data</p>
</footer>
</div>
<script>
const uploadArea = document.getElementById('upload-area');
const fileInput = document.getElementById('file-input');
const uploadBtn = document.getElementById('upload-btn');
const resultContainer = document.getElementById('result-container');
const metadataContent = document.getElementById('metadata-content');
const resetBtn = document.getElementById('reset-btn');
// Event listeners
uploadBtn.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', handleFileSelect);
uploadArea.addEventListener('dragover', handleDragOver);
uploadArea.addEventListener('dragleave', handleDragLeave);
uploadArea.addEventListener('drop', handleDrop);
resetBtn.addEventListener('click', resetForm);
function handleDragOver(e) {
e.preventDefault();
uploadArea.classList.add('active');
}
function handleDragLeave() {
uploadArea.classList.remove('active');
}
function handleDrop(e) {
e.preventDefault();
uploadArea.classList.remove('active');
if (e.dataTransfer.files.length) {
fileInput.files = e.dataTransfer.files;
processFile(fileInput.files[0]);
}
}
function handleFileSelect() {
if (fileInput.files.length) {
processFile(fileInput.files[0]);
}
}
async function processFile(file) {
if (!file.type.startsWith('image/')) {
alert('Please select an image file');
return;
}
const formData = new FormData();
formData.append('file', file);
try {
// Show loading state
uploadBtn.textContent = 'Processing...';
uploadBtn.disabled = true;
const response = await fetch('/extract-metadata', {
method: 'POST',
body: formData
});
const data = await response.json();
if (response.ok) {
displayMetadata(data);
} else {
showError(data.detail || 'Error processing image');
}
} catch (error) {
showError('Error: ' + error.message);
} finally {
uploadBtn.textContent = 'Select Image';
uploadBtn.disabled = false;
}
}
function displayMetadata(data) {
// Hide upload area and show results
uploadArea.style.display = 'none';
resultContainer.style.display = 'block';
// Generate metadata cards
let html = '';
// Basic info card
html += `
<div class="metadata-card">
<h3>📋 Basic Information</h3>
<div class="metadata-item">
<strong>Filename</strong>
<span>${data.filename}</span>
</div>
<div class="metadata-item">
<strong>Format</strong>
<span>${data.format || 'Unknown'}</span>
</div>
<div class="metadata-item">
<strong>Dimensions</strong>
<span>${data.size ? `${data.size[0]} × ${data.size[1]} pixels` : 'Unknown'}</span>
</div>
<div class="metadata-item">
<strong>Color Mode</strong>
<span>${data.mode || 'Unknown'}</span>
</div>
</div>
`;
// Creation date card
html += `
<div class="metadata-card creation">
<h3>⏱️ Creation Timestamp</h3>
`;
if (data.creation_date) {
const date = new Date(data.creation_date.date);
html += `
<div class="metadata-item">
<strong>Source</strong>
<span>${data.creation_date.source}</span>
</div>
<div class="metadata-item">
<strong>Date & Time</strong>
<span>${date.toLocaleString()}</span>
</div>
`;
} else if (data.file_system_creation_time) {
const date = new Date(data.file_system_creation_time);
html += `
<div class="metadata-item">
<strong>Source</strong>
<span>File System</span>
</div>
<div class="metadata-item">
<strong>Date & Time</strong>
<span>${date.toLocaleString()}</span>
</div>
`;
} else {
html += `
<div class="metadata-item error">
<strong>No Creation Date Found</strong>
<span>Neither EXIF data nor file system timestamps contain creation information</span>
</div>
`;
}
html += `</div>`;
// EXIF data card
html += `
<div class="metadata-card exif">
<h3>🔍 EXIF Metadata</h3>
`;
if (Object.keys(data.exif_data).length > 0) {
html += `<div class="exif-list">`;
for (const [key, value] of Object.entries(data.exif_data)) {
html += `
<div class="exif-item">
<span class="exif-key">${key}</span>
<span class="exif-value">${value}</span>
</div>
`;
}
html += `</div>`;
} else {
html += `
<div class="metadata-item">
<strong>No EXIF Data</strong>
<span>This image doesn't contain EXIF metadata</span>
</div>
`;
}
html += `</div>`;
// Error card (if any)
if (data.error) {
html += `
<div class="metadata-card">
<h3>⚠️ Error</h3>
<div class="metadata-item error">
<strong>Processing Error</strong>
<span>${data.error}</span>
</div>
</div>
`;
}
metadataContent.innerHTML = html;
}
function showError(message) {
// Hide upload area and show results
uploadArea.style.display = 'none';
resultContainer.style.display = 'block';
metadataContent.innerHTML = `
<div class="metadata-card">
<h3>⚠️ Error</h3>
<div class="metadata-item error">
<strong>Processing Failed</strong>
<span>${message}</span>
</div>
</div>
`;
}
function resetForm() {
// Show upload area and hide results
uploadArea.style.display = 'block';
resultContainer.style.display = 'none';
// Reset file input
fileInput.value = '';
}
</script>
</body>
</html>
"""
@app.post("/extract-metadata")
async def extract_metadata(file: UploadFile = File(...)):
"""Endpoint to extract metadata from uploaded image"""
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File must be an image")
# Initialize tmp_file_path to None
tmp_file_path = None
try:
# Read the file content
contents = await file.read()
# Create a temporary file to store the uploaded image
with tempfile.NamedTemporaryFile(delete=False) as tmp_file:
tmp_file.write(contents)
tmp_file_path = tmp_file.name
# Extract metadata
metadata = get_image_metadata(tmp_file_path)
return metadata
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
finally:
# Clean up temporary file
if tmp_file_path and os.path.exists(tmp_file_path):
os.unlink(tmp_file_path)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) |