Spaces:
Sleeping
Sleeping
File size: 4,824 Bytes
8e367ed fad9d58 8e367ed fad9d58 8e367ed a14de15 fad9d58 a14de15 fad9d58 a14de15 fad9d58 8e367ed a14de15 8e367ed a14de15 8e367ed fad9d58 8e367ed fad9d58 a14de15 fad9d58 a14de15 fad9d58 a14de15 fad9d58 8e367ed fad9d58 8e367ed fad9d58 a14de15 fad9d58 8e367ed fad9d58 8e367ed fad9d58 8e367ed fad9d58 8e367ed fad9d58 8e367ed | 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 | import gradio as gr
import torch
import torch.nn.functional as F
from transformers import AutoImageProcessor, AutoModelForImageClassification
import pandas as pd
from PIL import Image
# Experiment Configuration
# Objective: Facial Emotion Recognition using Vision Transformers (ViT)
MODEL_NAME = "dima806/facial_emotions_image_detection"
print(f"[{MODEL_NAME}] Initializing Vision Transformer and Processor...")
processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
print("Initialization complete. Awaiting visual stream.")
def analyze_facial_emotion(image: Image.Image):
"""
Computes forward pass of the ViT model on a given optical input (image).
Extracts the unnormalized logits and applies the Softmax activation function.
"""
if image is None:
return {"Error": 1.0}, "Awaiting visual feed...", pd.DataFrame()
# Optical Discretization (Image to Tensor)
inputs = processor(images=image, return_tensors="pt")
pixel_values = inputs["pixel_values"]
tensor_shape = tuple(pixel_values.shape)
# Calculate base statistical moments of the input tensor representation
pixel_array = pixel_values[0].numpy()
tensor_stats = pd.DataFrame({
"Color Channel": ["Channel 0 (R)", "Channel 1 (G)", "Channel 2 (B)"],
"Mean (μ)": pixel_array.mean(axis=(1, 2)),
"Std Dev (σ)": pixel_array.std(axis=(1, 2))
})
# Forward Propagation
with torch.no_grad():
outputs = model(**inputs)
logits = outputs.logits[0]
# Probabilistic Mapping (Softmax)
probs = F.softmax(logits, dim=-1)
# Map integer classes to semantic labels
labels = model.config.id2label
probs_dict = {labels[i]: float(probs[i]) for i in range(len(labels))}
# Sort logits for systematic logging
sorted_indices = torch.argsort(logits, descending=True)
top_idx = sorted_indices[0].item()
# Construct Mathematical Analysis Log
log_output = f"""
### Scientific Experiment Log
**Subject:** Vision Transformer Logit Extraction & Softmax Formulation
### Vector Normalization
The raw visual feed is processed into a normalized matrix structure optimized for the Transformer's patch embedding layers.
* **Tensor Dimensionality (Batch, Channels, H, W):** `{tensor_shape}`
### Logit Computation
The classification head outputs unnormalized, arbitrary real values (logits, $z$). Below are the top computed logits:
"""
denominator = 0.0
for idx in sorted_indices[:4]:
label = labels[idx.item()]
z_val = float(logits[idx.item()])
e_z = float(torch.exp(logits[idx.item()]))
denominator += e_z
log_output += f"* $z_{{\\text{{{label}}}}}$ = `{z_val:.4f}`\n"
log_output += f"""
### 3. Softmax Distribution
To interpret the logits as a mutually exclusive probability distribution, we apply the Softmax activation function:
$$ P(y_i) = \\frac{{e^{{z_i}}}}{{\\sum e^{{z_j}}}} $$
* **Estimated Normalization Constant ($\\Sigma e^z$ for Top 4):** $\\approx$ `{denominator:.4f}`
* **Primary Classification Hypothesis ($P$):** `{float(probs[top_idx]):.4%}` for class **{labels[top_idx].upper()}**
"""
return probs_dict, log_output, tensor_stats
# Define the User Interface Architecture
with gr.Blocks(theme=gr.themes.Monochrome(), title="Visual Sentiment Analysis") as demo:
gr.Markdown("# Facial Emotion Vision System")
gr.Markdown("**Experiment Date:** August 23, 2026 | **Protocol:** ViT Logit Extraction")
with gr.Row():
with gr.Column(scale=1):
# Input feed: Camera or file upload
vision_input = gr.Image(sources=["webcam", "upload"], type="pil", label="Optical Input Feed")
compute_btn = gr.Button("Execute Forward Pass", variant="primary")
gr.Markdown("### Input Tensor Statistics")
gr.Markdown("Statistical moments (Mean, Standard Deviation) of the normalized tensor prior to network propagation.")
stats_df = gr.Dataframe(headers=["Color Channel", "Mean (μ)", "Std Dev (σ)"], interactive=False)
with gr.Column(scale=1):
# Output Probability Distribution
prob_distribution = gr.Label(label="Computed Probability Distribution (Softmax output)")
# Mathematical Log
math_log = gr.Markdown(
"Awaiting forward pass...",
latex_delimiters=[{"left": "$$", "right": "$$", "display": True}, {"left": "$", "right": "$", "display": False}]
)
compute_btn.click(
fn=analyze_facial_emotion,
inputs=vision_input,
outputs=[prob_distribution, math_log, stats_df]
)
if __name__ == "__main__":
demo.launch()
|