Spaces:
Sleeping
Sleeping
Download app.py from bf369/My_FIRST_Sentiment_APP: direct link, hf CLI and curl.
- Browser
- Download file 4.82 kB
-
https://huggingface.co/spaces/bf369/My_FIRST_Sentiment_APP/resolve/main/app.py
- Command line
-
hf download hf://spaces/bf369/My_FIRST_Sentiment_APP/app.py
-
curl -L -o app.py https://huggingface.co/spaces/bf369/My_FIRST_Sentiment_APP/resolve/main/app.py
4.82 kB
| 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() | |