Spaces:
Sleeping
Sleeping
Elvis Claude Opus 4.5 commited on
Commit ·
abd1771
1
Parent(s): 292612f
Add EXIF metadata reading and dynamic tone curve analysis
Browse files- Read actual camera settings (focal length, aperture, ISO, shutter) from EXIF
- Fall back to estimation with "(estimated)" label when EXIF unavailable
- Display camera make/model and lens info when available
- Add EXIF/Estimated badge to CameraPanel
- Generate tone curve from image histogram analysis
- Render dynamic SVG curve based on actual tonal distribution
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Files changed (3)
12341 unmodified line6789101118 unmodified lines303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677295 unmodified lines3733743753763773781 unmodified line380381382383384385386387from PIL import Imageimport numpy as npfrom io import BytesIOfrom colorthief import ColorThief1 unmodified lineclass ImageAnalyzer:def analyze(self, image_bytes: BytesIO) -> dict:image = Image.open(image_bytes)image_bytes.seek(0)18 unmodified lineswidth, height = image.sizeaspect_ratio = width / heightimg_array = np.array(image.convert("L"))# Estimate focal length based on perspective distortion analysisfocal_estimate, sensor_hint = self._estimate_focal_length(img_array, width, height)edges = np.abs(np.diff(img_array.astype(float), axis=0))edge_variance = np.var(edges)if edge_variance > 2000:aperture = "f/5.6 - f/8 (Deep DoF)"dof = "Deep"elif edge_variance > 1000:aperture = "f/2.8 - f/4"dof = "Medium"else:aperture = "f/1.4 - f/2.0 (Shallow DoF)"dof = "Shallow"brightness = np.mean(img_array)if brightness > 150:iso = "Low (100-400)"elif brightness > 80:iso = "Medium (400-1600)"else:iso = "Higher (1600+)"motion_blur = self._detect_motion_blur(img_array)if motion_blur > 0.7:shutter = "Slow (1/30s or slower)"elif motion_blur > 0.4:shutter = "~1/60s - 1/125s"else:shutter = "Fast (1/250s+)"return {"focalLength": focal_estimate,"aperture": aperture,"depthOfField": dof,"iso": iso,"shutterSpeed": shutter,"sensorSize": sensor_hint,"aspectRatio": f"{width}:{height}",}def _detect_motion_blur(self, gray_image: np.ndarray) -> float:laplacian = np.abs(295 unmodified lineselse:saturation = "Desaturated"return {"palette": palette_hex,"temperature": temp,1 unmodified line"saturation": saturation,"shadows": f"Lifted, {shadow_tint}","highlights": highlight_tint,}def _generate_summary(self, camera: dict, lighting: dict, color: dict) -> str:return (f"This appears to be a {camera['depthOfField'].lower()} depth of field shot, "123451 unmodified line789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616218 unmodified lines81828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217295 unmodified lines5135145155165175185195205211 unmodified line523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582from PIL import Imagefrom PIL.ExifTags import TAGS, GPSTAGSimport numpy as npfrom io import BytesIOfrom colorthief import ColorThief1 unmodified lineclass ImageAnalyzer:# Common EXIF tag IDsEXIF_FOCAL_LENGTH = 37386EXIF_FOCAL_LENGTH_35MM = 41989EXIF_FNUMBER = 33437EXIF_ISO = 34855EXIF_EXPOSURE_TIME = 33434EXIF_MAKE = 271EXIF_MODEL = 272EXIF_LENS_MODEL = 42036def _extract_exif(self, image: Image.Image) -> dict:"""Extract EXIF metadata from image."""exif_data = {}try:exif = image._getexif()if exif:for tag_id, value in exif.items():tag = TAGS.get(tag_id, tag_id)exif_data[tag] = valueexif_data[tag_id] = value # Also store by ID for reliable lookupexcept (AttributeError, KeyError, TypeError):passreturn exif_datadef _format_exposure_time(self, exposure) -> str:"""Format exposure time as a fraction."""if exposure is None:return Nonetry:# Handle IFDRational or tupleif hasattr(exposure, 'numerator'):num, den = exposure.numerator, exposure.denominatorelif isinstance(exposure, tuple):num, den = exposureelse:val = float(exposure)if val >= 1:return f"{val:.1f}s"return f"1/{int(1/val)}s"if num == 0:return Noneif den == 1:return f"{num}s"# Simplify fractionif num == 1:return f"1/{den}s"return f"{num}/{den}s"except (TypeError, ValueError, ZeroDivisionError):return Nonedef analyze(self, image_bytes: BytesIO) -> dict:image = Image.open(image_bytes)image_bytes.seek(0)18 unmodified lineswidth, height = image.sizeaspect_ratio = width / height# First, try to extract EXIF dataexif = self._extract_exif(image)has_exif = len(exif) > 0img_array = np.array(image.convert("L"))# Focal Length - prefer EXIFfocal_exif = exif.get(self.EXIF_FOCAL_LENGTH) or exif.get('FocalLength')focal_35mm = exif.get(self.EXIF_FOCAL_LENGTH_35MM) or exif.get('FocalLengthIn35mmFilm')if focal_exif:try:focal_val = float(focal_exif)if focal_35mm:focal_estimate = f"{focal_val:.0f}mm ({float(focal_35mm):.0f}mm equiv)"else:focal_estimate = f"{focal_val:.0f}mm"# Determine sensor hint based on focal lengthif focal_val < 24:sensor_hint = "Ultra-wide angle lens"elif focal_val < 35:sensor_hint = "Wide angle lens"elif focal_val < 50:sensor_hint = "Wide-normal lens"elif focal_val < 85:sensor_hint = "Standard lens"elif focal_val < 135:sensor_hint = "Portrait/Short telephoto"else:sensor_hint = "Telephoto lens"except (TypeError, ValueError):focal_estimate, sensor_hint = self._estimate_focal_length(img_array, width, height)else:focal_estimate, sensor_hint = self._estimate_focal_length(img_array, width, height)# Aperture - prefer EXIFfnumber = exif.get(self.EXIF_FNUMBER) or exif.get('FNumber')if fnumber:try:f_val = float(fnumber)aperture = f"f/{f_val:.1f}"if f_val <= 2.0:dof = "Shallow"elif f_val <= 5.6:dof = "Medium"else:dof = "Deep"except (TypeError, ValueError):aperture, dof = self._estimate_aperture(img_array)else:aperture, dof = self._estimate_aperture(img_array)# ISO - prefer EXIFiso_exif = exif.get(self.EXIF_ISO) or exif.get('ISOSpeedRatings')if iso_exif:try:# ISO can be a single value or a tupleif isinstance(iso_exif, (list, tuple)):iso_val = int(iso_exif[0])else:iso_val = int(iso_exif)iso = f"ISO {iso_val}"except (TypeError, ValueError, IndexError):iso = self._estimate_iso(img_array)else:iso = self._estimate_iso(img_array)# Shutter Speed - prefer EXIFexposure = exif.get(self.EXIF_EXPOSURE_TIME) or exif.get('ExposureTime')shutter = self._format_exposure_time(exposure)if not shutter:shutter = self._estimate_shutter(img_array)# Camera/Lens infocamera_make = exif.get(self.EXIF_MAKE) or exif.get('Make', '')camera_model = exif.get(self.EXIF_MODEL) or exif.get('Model', '')lens_model = exif.get(self.EXIF_LENS_MODEL) or exif.get('LensModel', '')camera_info = Noneif camera_make or camera_model:camera_info = f"{camera_make} {camera_model}".strip()result = {"focalLength": focal_estimate,"aperture": aperture,"depthOfField": dof,"iso": iso,"shutterSpeed": shutter,"sensorSize": sensor_hint,"aspectRatio": f"{width}:{height}","hasExif": has_exif,}if camera_info:result["camera"] = camera_infoif lens_model:result["lens"] = str(lens_model)return resultdef _estimate_aperture(self, img_array: np.ndarray) -> tuple:"""Estimate aperture from edge variance when EXIF not available."""edges = np.abs(np.diff(img_array.astype(float), axis=0))edge_variance = np.var(edges)if edge_variance > 2000:return "f/5.6 - f/8 (estimated)", "Deep"elif edge_variance > 1000:return "f/2.8 - f/4 (estimated)", "Medium"else:return "f/1.4 - f/2.0 (estimated)", "Shallow"def _estimate_iso(self, img_array: np.ndarray) -> str:"""Estimate ISO from brightness when EXIF not available."""brightness = np.mean(img_array)if brightness > 150:return "Low ISO (estimated)"elif brightness > 80:return "Medium ISO (estimated)"else:return "High ISO (estimated)"def _estimate_shutter(self, img_array: np.ndarray) -> str:"""Estimate shutter speed from motion blur when EXIF not available."""motion_blur = self._detect_motion_blur(img_array)if motion_blur > 0.7:return "Slow shutter (estimated)"elif motion_blur > 0.4:return "~1/60s - 1/125s (estimated)"else:return "Fast shutter (estimated)"def _detect_motion_blur(self, gray_image: np.ndarray) -> float:laplacian = np.abs(295 unmodified lineselse:saturation = "Desaturated"# Analyze tone curve from image histogramtone_curve = self._analyze_tone_curve(gray)return {"palette": palette_hex,"temperature": temp,1 unmodified line"saturation": saturation,"shadows": f"Lifted, {shadow_tint}","highlights": highlight_tint,"toneCurve": tone_curve,}def _analyze_tone_curve(self, gray: np.ndarray) -> list:"""Analyze the image's tonal distribution and return control points for a tone curve.Returns a list of [x, y] points where x is input (0-100) and y is output (0-100)."""# Compute histogramhist, _ = np.histogram(gray.flatten(), bins=256, range=(0, 256))# Compute cumulative distribution function (CDF)cdf = hist.cumsum()cdf_normalized = cdf / cdf[-1] # Normalize to 0-1# Sample the CDF at key points to create curve control points# We sample at shadows, quarter-tones, midtones, three-quarter-tones, highlightssample_points = [0, 32, 64, 96, 128, 160, 192, 224, 255]curve_points = []for input_val in sample_points:# The CDF tells us what percentage of pixels are at or below this value# We use this to derive the "output" value for the curveoutput_val = cdf_normalized[input_val] * 100input_normalized = (input_val / 255) * 100curve_points.append([round(input_normalized, 1), round(output_val, 1)])# Analyze characteristics for additional curve shaping# Check if shadows are lifted (black point is raised)black_point = np.percentile(gray, 2)white_point = np.percentile(gray, 98)# Adjust curve based on actual tonal rangeif black_point > 20: # Lifted shadows# Raise the shadow portion of the curvefor i, pt in enumerate(curve_points):if pt[0] < 25:lift_amount = (black_point / 255) * 100 * 0.5curve_points[i][1] = min(100, pt[1] + lift_amount * (1 - pt[0]/25))if white_point < 235: # Crushed highlights# Lower the highlight portionfor i, pt in enumerate(curve_points):if pt[0] > 75:crush_amount = ((255 - white_point) / 255) * 100 * 0.5curve_points[i][1] = max(0, pt[1] - crush_amount * ((pt[0] - 75) / 25))# Ensure curve is valid (monotonically increasing, within bounds)for i, pt in enumerate(curve_points):curve_points[i][1] = max(0, min(100, pt[1]))# Convert to list of floats for JSON serializationreturn [[float(p[0]), float(p[1])] for p in curve_points]def _generate_summary(self, camera: dict, lighting: dict, color: dict) -> str:return (f"This appears to be a {camera['depthOfField'].lower()} depth of field shot, "
14 unmodified lines1516171819203 unmodified lines24252627282914 unmodified lines{ label: 'Sensor Size', value: camera.sensorSize, icon: '📷' },]return (<div className="p-6 bg-slate-800/50 rounded-xl border border-slate-700/50"><div className="flex items-center gap-2 mb-4">3 unmodified lines</svg></div><h3 className="text-lg font-semibold text-white">Camera Settings</h3></div><div className="space-y-3">14 unmodified lines15161718192021222324252627283 unmodified lines32333435363738394041424344454614 unmodified lines{ label: 'Sensor Size', value: camera.sensorSize, icon: '📷' },]// Add camera/lens info if available from EXIFif (camera.camera) {items.unshift({ label: 'Camera', value: camera.camera, icon: '📷' })}if (camera.lens) {items.splice(camera.camera ? 1 : 0, 0, { label: 'Lens', value: camera.lens, icon: '🔍' })}return (<div className="p-6 bg-slate-800/50 rounded-xl border border-slate-700/50"><div className="flex items-center gap-2 mb-4">3 unmodified lines</svg></div><h3 className="text-lg font-semibold text-white">Camera Settings</h3>{camera.hasExif ? (<span className="ml-auto text-xs px-2 py-0.5 rounded-full bg-green-500/20 text-green-400 border border-green-500/30">EXIF Data</span>) : (<span className="ml-auto text-xs px-2 py-0.5 rounded-full bg-amber-500/20 text-amber-400 border border-amber-500/30">Estimated</span>)}</div><div className="space-y-3">
15 unmodified lines16171819202138 unmodified lines606162636465666768697071727374757615 unmodified lines{ label: 'Highlights', value: color.highlights },]return (<div className="p-6 bg-slate-800/50 rounded-xl border border-slate-700/50"><div className="flex items-center justify-between mb-4">38 unmodified lines<stop offset="100%" stopColor="#ea580c" stopOpacity="0.3" /></linearGradient></defs><line x1="0" y1="100" x2="100" y2="0" stroke="#374151" strokeWidth="0.5" strokeDasharray="2,2" /><pathd="M 0 95 Q 15 85, 30 70 T 60 40 T 100 5"fill="none"stroke="url(#curveGradient)"strokeWidth="2"/><pathd="M 0 95 Q 15 85, 30 70 T 60 40 T 100 5 L 100 100 L 0 100 Z"fill="url(#curveGradient)"/></svg><div className="absolute bottom-2 left-2 text-xs text-slate-500">Shadows</div><div className="absolute top-2 right-2 text-xs text-slate-500">Highlights</div>15 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051525354555638 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312415 unmodified lines{ label: 'Highlights', value: color.highlights },]// Generate SVG path from tone curve points// Points are [x, y] where x and y are 0-100, y needs to be flipped for SVG coordinatesconst generateCurvePath = (points) => {if (!points || points.length < 2) {// Fallback to linear curvereturn "M 0 100 L 100 0"}// Convert points to SVG coordinates (flip Y axis)const svgPoints = points.map(([x, y]) => [x, 100 - y])// Create a smooth curve through the points using quadratic bezierlet path = `M ${svgPoints[0][0]} ${svgPoints[0][1]}`for (let i = 1; i < svgPoints.length; i++) {const prev = svgPoints[i - 1]const curr = svgPoints[i]// Use quadratic bezier for smooth curveconst cpX = (prev[0] + curr[0]) / 2const cpY = prev[1]if (i === 1) {path += ` Q ${cpX} ${cpY}, ${curr[0]} ${curr[1]}`} else {path += ` T ${curr[0]} ${curr[1]}`}}return path}const curvePath = generateCurvePath(color.toneCurve)const fillPath = curvePath + " L 100 100 L 0 100 Z"return (<div className="p-6 bg-slate-800/50 rounded-xl border border-slate-700/50"><div className="flex items-center justify-between mb-4">38 unmodified lines<stop offset="100%" stopColor="#ea580c" stopOpacity="0.3" /></linearGradient></defs>{/* Reference diagonal line (linear response) */}<line x1="0" y1="100" x2="100" y2="0" stroke="#374151" strokeWidth="0.5" strokeDasharray="2,2" />{/* Actual tone curve from image analysis */}<pathd={curvePath}fill="none"stroke="url(#curveGradient)"strokeWidth="2"/><pathd={fillPath}fill="url(#curveGradient)"/>{/* Control points visualization */}{color.toneCurve?.map(([x, y], i) => (<circlekey={i}cx={x}cy={100 - y}r="1.5"fill="#f59e0b"opacity="0.6"/>))}</svg><div className="absolute bottom-2 left-2 text-xs text-slate-500">Shadows</div><div className="absolute top-2 right-2 text-xs text-slate-500">Highlights</div>
backend/app/services/analyzer.py+219-24
frontend/src/components/CameraPanel.jsx+17
frontend/src/components/ColorPanel.jsx+50-2