Spaces:
Sleeping
Sleeping
File size: 31,448 Bytes
27818c1 |
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 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 |
import streamlit as st
import plotly.graph_objects as go
import plotly.express as px
import pandas as pd
from streamlit_extras.badges import badge
import numpy as np
import pathlib
import streamlit.components.v1 as components
# Set page configuration
st.set_page_config(
page_title="Tech4Humans Projects | CV Journey",
page_icon="πΌ",
layout="wide",
initial_sidebar_state="expanded",
)
# Title and introduction
st.header("πΌ Tech4Humans - Industry Applications of CV")
st.markdown(
"""
### Professional Experience in Machine Learning Engineering
I joined Tech4Humans initially as an ML Engineering intern in mid-2024 and was later hired as a full-time
Machine Learning Engineer. My work focuses on customizing and creating AI models for real-world applications,
with a strong emphasis on computer vision solutions.
This section showcases two significant CV projects I've worked on at Tech4Humans:
"""
)
# Project tabs
projects_tab = st.tabs(["Signature Detection", "Document Information Extraction"])
# Signature Detection Project
with projects_tab[0]:
st.subheader("Open-Source Signature Detection Model")
col1, col2 = st.columns([1, 1])
with col1:
html_content = """
<div style="
display: flex;
gap: 24px;
margin: 2em 0;
line-height: 1.6;
">
<!-- Left Column - Text -->
<div style="flex: 1; padding-right: 16px;">
<p style="font-size: 1.1rem; margin-bottom: 1em;">
This article presents an <strong>open-source project</strong> for automated signature detection in document processing, structured into four key phases:
</p>
<ul style="padding-left: 20px; margin-bottom: 1em; font-size: 1rem;">
<li><strong>Dataset Engineering:</strong> Curation of a hybrid dataset through aggregation of two public collections.</li>
<li><strong>Architecture Benchmarking:</strong> Systematic evaluation of state-of-the-art object detection architectures (<em>YOLO series, DETR variants, and YOLOS</em>), focusing on accuracy, computational efficiency, and deployment constraints.</li>
<li><strong>Model Optimization:</strong> Leveraged Optuna for hyperparameter tuning, yielding a 7.94% F1-score improvement over baseline configurations.</li>
<li><strong>Production Deployment:</strong> Utilized Triton Inference Server for OpenVINO CPU-optimized inference.</li>
</ul>
<p style="font-size: 1.1rem; margin-top: 1em;">
Experimental results demonstrate a robust balance between precision, recall, and inference speed, validating the solution's practicality for real-world applications.
</p>
</div>
<!-- Right Column - Images -->
<div style="
flex: 1;
display: flex;
flex-direction: column;
gap: 12px;
">
<img src="https://cdn-uploads.huggingface.co/production/uploads/666b9ef5e6c60b6fc4156675/6AnC1ut7EOLa6EjibXZXY.webp"
style="max-width: 100%; height: auto; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
<div style="display: flex; gap: 12px;">
<img src="https://cdn-uploads.huggingface.co/production/uploads/666b9ef5e6c60b6fc4156675/jWxcAUZPt8Bzup8kL-bor.webp"
style="flex: 1; max-width: 50%; height: auto; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
<img src="https://cdn-uploads.huggingface.co/production/uploads/666b9ef5e6c60b6fc4156675/tzK0lJz7mI2fazpY9pB1w.webp"
style="flex: 1; max-width: 50%; height: auto; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.1);">
</div>
</div>
</div>
"""
st.html(html_content)
# Dataset section
st.markdown("---")
st.markdown("### Dataset Engineering")
col1, col2 = st.columns([2, 1])
with col1:
st.markdown(
"""
#### Dataset Composition & Preprocessing
The dataset was constructed by merging two publicly available benchmarks:
- **[Tobacco800](https://paperswithcode.com/dataset/tobacco-800):** Scanned documents with signature annotations.
- **[Signatures-XC8UP](https://universe.roboflow.com/roboflow-100/signatures-xc8up):** Part of the Roboflow 100 benchmark with handwritten signature images.
**Preprocessing & Augmentation (using [Roboflow](https://roboflow.com/)):**
- **Split:** Training (70%), Validation (15%), Test (15%) from 2,819 total images.
- **Preprocessing:** Auto-orientation, resize to 640x640px.
- **Augmentation:** Rotation, shear, brightness/exposure changes, blur, noise to enhance model robustness.
The final dataset combines diverse document types and signature styles.
"""
)
with col2:
st.image(
"https://cdn-uploads.huggingface.co/production/uploads/666b9ef5e6c60b6fc4156675/_o4PZzTyj17qhUYMLM2Yn.png",
caption="Figure 10: Annotated document samples (Source: Signature Detection Article)",
use_container_width=True,
)
st.caption(
"The dataset includes various document types with annotated signatures and logos."
)
# Architecture evaluation
st.markdown("---")
st.markdown("### Architecture Evaluation")
st.markdown(
"""
We systematically evaluated multiple state-of-the-art object detection architectures (YOLO series, DETR variants, YOLOS)
to find the optimal balance between accuracy (mAP), inference speed (CPU ONNX), and training time.
The results below are based on training for 35 epochs.
"""
)
# Actual model performance comparison data from Article Table 3
model_data = {
"Model": [
"rtdetr-l",
"yolos-base",
"yolos-tiny",
"conditional-detr",
"detr",
"yolov8x",
"yolov8l",
"yolov8m",
"yolov8s",
"yolov8n",
"yolo11x",
"yolo11l",
"yolo11m",
"yolo11s",
"yolo11n",
"yolov10x",
"yolov10l",
"yolov10b",
"yolov10m",
"yolov10s",
"yolov10n",
"yolo12n",
"yolo12s",
"yolo12m",
"yolo12l",
"yolo12x",
],
"mAP@50 (%)": [
92.71,
90.12,
86.98,
93.65,
88.89,
79.42,
80.03,
87.53,
87.47,
81.61,
66.71,
70.74,
80.96,
83.56,
81.38,
68.10,
72.68,
78.98,
78.77,
66.39,
73.43,
75.86,
66.66,
61.96,
54.92,
51.16,
],
"Inference Time (ms)": [
583.6,
1706.5,
265.3,
476.8,
425.6,
1259.5,
871.3,
401.2,
216.6,
110.4,
1016.7,
518.1,
381.7,
179.8,
106.7,
821.2,
580.8,
473.1,
320.1,
150.1,
73.9,
90.4,
166.6,
372.8,
505.7,
1022.8,
],
"mAP@50-95 (%)": [ # Added for hover data
62.24,
58.36,
46.91,
65.33,
57.94,
55.29,
59.40,
66.55,
65.46,
62.40,
48.23,
49.91,
60.08,
63.88,
61.75,
47.45,
52.27,
57.89,
58.13,
47.39,
55.27,
55.87,
48.54,
45.62,
41.00,
35.42,
],
}
model_df = pd.DataFrame(model_data)
model_df = model_df.sort_values(
"Inference Time (ms)"
) # Sort for better visualization
# Create a scatter plot for model comparison (based on Article Figure 11)
fig = px.scatter(
model_df,
x="Inference Time (ms)",
y="mAP@50 (%)",
color="Model", # Color by model
hover_name="Model",
hover_data=["mAP@50-95 (%)"], # Show mAP50-95 on hover
text="Model", # Display model names on points (optional, can be cluttered)
title="Model Architecture Comparison (CPU ONNX Inference)",
)
fig.update_traces(textposition="top center") # Adjust text position if displayed
fig.update_layout(
xaxis_title="Inference Time (ms) - lower is better",
yaxis_title="mAP@50 (%) - higher is better",
height=600, # Increased height for clarity
margin=dict(l=20, r=20, t=50, b=20),
legend_title_text="Model Variant",
)
# Optional: Add annotations for key models if needed
# fig.add_annotation(x=216.6, y=87.47, text="YOLOv8s", showarrow=True, arrowhead=1)
# fig.add_annotation(x=73.9, y=73.43, text="YOLOv10n (Fastest)", showarrow=True, arrowhead=1)
# fig.add_annotation(x=476.8, y=93.65, text="Conditional DETR (Highest mAP@50)", showarrow=True, arrowhead=1)
st.plotly_chart(fig, use_container_width=True)
st.markdown(
"""
**Model Selection:**
While `conditional-detr-resnet-50` achieved the highest mAP@50 (93.65%), and `yolov10n` had the lowest CPU inference time (73.9 ms), **YOLOv8s** was selected for further optimization.
**Rationale for YOLOv8s:**
- **Strong Balance:** Offered a competitive mAP@50 (87.47%) and mAP@50-95 (65.46%) with a reasonable inference time (216.6 ms).
- **Efficiency:** Convolutional architectures like YOLO generally showed faster inference and training times compared to transformer models in this experiment.
- **Export & Ecosystem:** Excellent support for various export formats (ONNX, OpenVINO, TensorRT) facilitated by the Ultralytics library, simplifying deployment.
- **Community & Development:** Active development and large community support.
"""
)
# Hyperparameter tuning
st.markdown("---")
st.markdown("### Hyperparameter Optimization")
col1, col2 = st.columns([2, 1]) # Keep ratio
with col1:
st.markdown(
"""
Using **Optuna**, we performed hyperparameter tuning on the selected **YOLOv8s** model over 20 trials, optimizing for the F1-score on the test set.
**Key Parameters Explored:**
- `dropout`: (0.0 to 0.5)
- `lr0` (Initial Learning Rate): (1e-5 to 1e-1, log scale)
- `box` (Box Loss Weight): (3.0 to 7.0)
- `cls` (Class Loss Weight): (0.5 to 1.5)
- `optimizer`: (AdamW, RMSProp)
**Optimization Objective:**
Maximize F1-score, balancing precision and recall, crucial for signature detection where both false positives and false negatives are problematic.
**Results:**
The best trial (#10) significantly improved performance compared to the baseline YOLOv8s configuration, notably increasing Recall.
"""
)
with col2:
# Data from Article Table 4
hp_results = {
"Model": ["YOLOv8s (Base)", "YOLOv8s (Tuned)"],
"F1-score (%)": [85.42, 93.36],
"Precision (%)": [97.23, 95.61],
"Recall (%)": [76.16, 91.21],
"mAP@50 (%)": [87.47, 95.75],
"mAP@50-95 (%)": [65.46, 66.26],
}
hp_df = pd.DataFrame(hp_results)
# Create bar chart comparing F1 scores
fig_hp = px.bar(
hp_df,
x="Model",
y="F1-score (%)",
color="Model",
title="F1-Score Improvement After HPO",
text="F1-score (%)",
color_discrete_sequence=px.colors.qualitative.Pastel,
labels={"F1-score (%)": "F1-Score (%)"},
hover_data=["Precision (%)", "Recall (%)", "mAP@50 (%)", "mAP@50-95 (%)"],
)
fig_hp.update_traces(texttemplate="%{text:.2f}%", textposition="outside")
fig_hp.update_layout(
yaxis_range=[0, 100], # Set y-axis from 0 to 100
height=400, # Adjusted height
margin=dict(l=20, r=20, t=40, b=20),
showlegend=False,
)
st.plotly_chart(fig_hp, use_container_width=True)
st.markdown(
f"The tuning resulted in a **{hp_df.loc[1, 'F1-score (%)'] - hp_df.loc[0, 'F1-score (%)']:.2f}% absolute improvement** in F1-score."
)
# Production deployment
st.markdown("---")
st.markdown("### Production Deployment")
st.markdown(
"""
The final, optimized YOLOv8s model was deployed using a production-ready inference pipeline designed for efficiency and scalability.
**Key Components:**
- **Model Format:** Exported to **ONNX** for broad compatibility and optimized CPU inference with **OpenVINO**. TensorRT format also available for GPU inference.
- **Inference Server:** **Triton Inference Server** used for serving the model, chosen for its flexibility and performance.
- **Deployment:** Containerized using **Docker** for reproducible environments. A custom Docker image including only necessary backends (Python, ONNX, OpenVINO) was built to reduce size.
- **Ensemble Model:** A Triton Ensemble Model integrates preprocessing (Python), inference (ONNX/OpenVINO), and postprocessing (Python, including NMS) into a single server-side pipeline, minimizing latency.
**Final Performance Metrics (Test Set):**
- **Precision:** 94.74%
- **Recall:** 89.72%
- **F1-score:** 93.36% (derived from Precision/Recall or Table 4)
- **mAP@50:** 94.50%
- **mAP@50-95:** 67.35%
- **Inference Latency:**
- CPU (ONNX Runtime): **~171.6 ms**
- GPU (TensorRT on T4): **~7.7 ms**
"""
)
# Architecture diagram
st.markdown("### Deployment Architecture (Triton Ensemble)")
# Mermaid diagram for the Ensemble Model (based on Article Figure 14)
mermaid_code = """
flowchart TB
subgraph "Triton Inference Server"
direction TB
subgraph "Ensemble Model Pipeline"
direction TB
subgraph Input
raw["raw_image
(UINT8, [-1])"]
conf["confidence_threshold
(FP16, [1])"]
iou["iou_threshold
(FP16, [1])"]
end
subgraph "Preprocess Py-Backend"
direction TB
pre1["Decode Image
BGR to RGB"]
pre2["Resize (640x640)"]
pre3["Normalize (/255.0)"]
pre4["Transpose
[H,W,C]->[C,H,W]"]
pre1 --> pre2 --> pre3 --> pre4
end
subgraph "YOLOv8 Model ONNX Backend"
yolo["Inference YOLOv8s"]
end
subgraph "Postproces Python Backend"
direction TB
post1["Transpose
Outputs"]
post2["Filter Boxes (confidence_threshold)"]
post3["NMS (iou_threshold)"]
post4["Format Results [x,y,w,h,score]"]
post1 --> post2 --> post3 --> post4
end
subgraph Output
result["detection_result
(FP16, [-1,5])"]
end
raw --> pre1
pre4 --> |"preprocessed_image (FP32, [3,-1,-1])"| yolo
yolo --> |"output0"| post1
conf --> post2
iou --> post3
post4 --> result
end
end
subgraph Client
direction TB
client_start["Client Application"]
response["Detections Result
[x,y,w,h,score]"]
end
client_start -->|"HTTP/gRPC Request
with raw image
confidence_threshold
iou_threshold"| raw
result -->|"HTTP/gRPC Response with detections"| response
"""
# Check if streamlit_mermaid is available
try:
from streamlit_mermaid import st_mermaid
st_mermaid(mermaid_code)
except ImportError:
st.warning(
"`streamlit-mermaid` not installed. Displaying Mermaid code instead."
)
st.code(mermaid_code, language="mermaid")
# Project resources
st.markdown("---")
st.markdown("### Project Resources")
st.markdown(
"""
| Resource | Links / Badges | Details |
|----------|----------------|---------|
| **Article** | [](https://huggingface.co/blog/samuellimabraz/signature-detection-model) | A detailed community article covering the full development process of the project |
| **Model Files** | [](https://huggingface.co/tech4humans/yolov8s-signature-detector) | **Available formats:** [](https://pytorch.org/) [](https://onnx.ai/) [](https://developer.nvidia.com/tensorrt) |
| **Dataset β Original** | [](https://universe.roboflow.com/tech-ysdkk/signature-detection-hlx8j) | 2,819 document images annotated with signature coordinates |
| **Dataset β Processed** | [](https://huggingface.co/datasets/tech4humans/signature-detection) | Augmented and pre-processed version (640px) for model training |
| **Notebooks β Model Experiments** | [](https://colab.research.google.com/drive/1wSySw_zwyuv6XSaGmkngI4dwbj-hR4ix) [](https://api.wandb.ai/links/samuel-lima-tech4humans/30cmrkp8) | Complete training and evaluation pipeline with selection among different architectures (yolo, detr, rt-detr, conditional-detr, yolos) |
| **Notebooks β HP Tuning** | [](https://colab.research.google.com/drive/1wSySw_zwyuv6XSaGmkngI4dwbj-hR4ix) [](https://api.wandb.ai/links/samuel-lima-tech4humans/31a6zhb1) | Optuna trials for optimizing the precision/recall balance |
| **Inference Server** | [](https://github.com/tech4ai/t4ai-signature-detect-server) | Complete deployment and inference pipeline with Triton Inference Server<br> [](https://docs.openvino.ai/2025/index.html) [](https://www.docker.com/) [](https://developer.nvidia.com/triton-inference-server) |
| **Live Demo** | [](https://huggingface.co/spaces/tech4humans/signature-detection) | Graphical interface with real-time inference<br> [](https://www.gradio.app/) [](https://plotly.com/python/) |
""",
unsafe_allow_html=True,
)
# Live demo using iframe
st.markdown("### Live Demo")
st.components.v1.iframe(
"https://tech4humans-signature-detection.hf.space", height=1000, scrolling=True
)
# Project impact
st.markdown("---")
st.markdown("### Project Impact")
col1, col2 = st.columns(2)
with col1:
st.markdown(
"""
#### Community Recognition
This project gained visibility in the ML community:
- +100 upvote in Community Articles
- Shared by [Merve Noyan](https://huggingface.co/merve) on LinkedIn
- Served as a reference for end-to-end computer vision projects
"""
)
with col2:
st.markdown(
"""
#### Business Impact
The model has been integrated into document processing pipelines, resulting in:
- **Automation:** Reduction in manual verification steps
- **Accuracy:** Fewer missed signatures and false positives
- **Speed:** Faster document processing throughput
"""
)
# Document Data Extraction Project
with projects_tab[1]:
st.subheader("Fine-tuning Vision-Language Models for Structured Document Extraction")
st.markdown("""
### Project Goal: Extracting Structured Data from Brazilian Documents
This project explores fine-tuning open-source Vision-Language Models (VLMs) to extract structured data (JSON format) from images of Brazilian documents (National IDs - RG, Driver's Licenses - CNH, Invoices - NF) based on user-defined schemas.
The objective wasn't to replace existing solutions immediately but to validate the capabilities of smaller, fine-tuned VLMs and our ability to train and deploy them efficiently.
""")
# --- Dataset Section ---
st.markdown("---")
st.markdown("### 1. Dataset Refinement and Preparation")
st.markdown("""
Building upon public datasets, we initially faced inconsistencies in annotations and data standardization.
**Refinement Process:**
- Manually selected and re-annotated 170 examples each for CNH and RG.
- Selected high-quality Invoice (Nota Fiscal - NF) samples.
- **Split:** 70% Training, 15% Validation, 15% Test, maintaining class balance using Roboflow. ([Dataset Link](https://universe.roboflow.com/tech-ysdkk/brazilian-document-extration))
- **Augmentation:** Used Roboflow to apply image transformations (e.g., rotations, noise) to the training set, tripling its size.
- **Preprocessing:** Resized images to a maximum of 640x640 (maintaining aspect ratio) for evaluation and training. Initially avoided complex preprocessing like grayscale conversion to prevent model bias.
The final dataset provides a robust foundation for evaluating and fine-tuning models on specific Brazilian document types.
""")
# --- Evaluation Section ---
st.markdown("---")
st.markdown("### 2. Base Model Evaluation")
st.markdown("""
We benchmarked several open-source VLMs (1B to 10B parameters, suitable for L4 GPU) using the [Open VLM Leaderboard](https://huggingface.co/spaces/opencompass/open_vlm_leaderboard) as a reference. Key architectures considered include Qwen-VL, InternVL, Ovis, MiniCPM, DeepSeek-VL, Phi-3.5-Vision, etc.
**Efficient Inference with vLLM:**
- Utilized **vLLM** for optimized inference, leveraging its support for various vision models and features like structured output generation (though not used in the final fine-tuned evaluations). This significantly accelerated prediction compared to standard Transformers pipelines.
**Metrics:**
- Developed custom Python functions to calculate field similarity between predicted and ground truth JSONs.
- Normalized values (dates, numbers, case, special characters) and used **rapidfuzz** (based on Indel distance) for string similarity scoring (0-100).
- Calculated overall accuracy and field coverage.
""")
# --- Finetuning Section ---
st.markdown("---")
st.markdown("### 3. Fine-tuning Experiments")
st.markdown("""
We fine-tuned promising architectures using parameter-efficient techniques (LoRA) to improve performance on our specific dataset.
**Frameworks & Tools:**
- **Unsloth:** Leveraged for optimized training kernels, initially exploring Qwen2.5 but settling on **Qwen2-VL (2B, 7B)** due to better stability and merge compatibility with vLLM.
- **MS-Swift:** Adopted this comprehensive framework from ModelScope (Alibaba) for its broad support of architectures and fine-tuning methods. Tuned **InternVL-2.5-MPO (1B, 4B)**, **Qwen2.5-VL (3B)**, and **DeepSeek-VL2**.
- **LoRA:** Employed low-rank adaptation (ranks 2 and 4) with RSLora decay strategy.
**Fine-tuning Results:**
Fine-tuning demonstrated significant accuracy improvements, especially for smaller models, making them competitive with larger base models.
""")
# --- Embed Performance by Category Plot ---
st.markdown("#### Performance Comparison: Base vs. Fine-tuned (by Category)")
try:
# Construct path relative to the current script file
current_dir = pathlib.Path(__file__).parent
perf_cat_path = current_dir.parent / "assets/model_performance_by_category.html"
if perf_cat_path.is_file():
with open(perf_cat_path, 'r', encoding='utf-8') as f:
perf_cat_html = f.read()
components.html(perf_cat_html, height=700, scrolling=True)
else:
st.warning(f"Performance by category plot file not found at `{perf_cat_path}`")
except NameError:
# Handle case where __file__ is not defined
st.warning("Cannot determine file path automatically. Make sure `assets/model_performance_by_category.html` exists relative to the execution directory.")
except Exception as e:
st.error(f"Error loading performance by category plot: {e}")
# --- Embed Heatmap Plot ---
st.markdown("#### Accuracy Heatmap (Base Models)")
try:
# Construct path relative to the current script file
current_dir = pathlib.Path(__file__).parent
heatmap_path = current_dir.parent / "assets/heatmap_accuracy.html"
if heatmap_path.is_file():
with open(heatmap_path, 'r', encoding='utf-8') as f:
heatmap_html = f.read()
components.html(heatmap_html, height=600, scrolling=True)
else:
st.warning(f"Heatmap plot file not found at `{heatmap_path}`")
except NameError:
# Handle case where __file__ is not defined (e.g. interactive environment)
st.warning("Cannot determine file path automatically. Make sure `assets/heatmap_accuracy.html` exists relative to the execution directory.")
except Exception as e:
st.error(f"Error loading heatmap plot: {e}")
st.markdown("""
**Key Fine-tuning Observations:**
- **Small Models (1-3B):** Showed the largest relative gains (e.g., `InternVL2_5-1B-MPO-tuned` +28% absolute accuracy, reaching 83% overall). Fine-tuned small models outperformed larger base models.
- **Medium Models (~4B):** Also improved significantly (e.g., `InternVL2_5-4B-MPO-tuned` +18%, reaching 87% overall, with >90% on CNH).
- **Large Models (7B+):** Showed more modest gains (+13-14%), suggesting diminishing returns for fine-tuning very large models on this dataset/task.
- **Efficiency:** Fine-tuning often slightly *reduced* inference time, potentially because structured output guidance (used in base eval) was removed for tuned models as they performed better without it.
- **Challenge:** Extracting data from Invoices (NF) remained the most difficult task, even after tuning (max ~77% accuracy).
""")
# --- Generalization Section ---
st.markdown("---")
st.markdown("### 4. Generalization Analysis (Ongoing)")
st.markdown("""
To assess if fine-tuning caused the models to "forget" how to handle different document types, we are evaluating their performance on an out-of-distribution dataset.
**Methodology:**
- Used the English-language [`getomni-ai/ocr-benchmark`](https://huggingface.co/datasets/getomni-ai/ocr-benchmark) dataset.
- Selected samples from 8 document types with varying layouts and relatively simple JSON schemas.
- Focus is on the *relative* performance drop between the base model and its fine-tuned version on these unseen documents, rather than absolute accuracy.
**Preliminary Results:**
This plot compares the performance of base vs. fine-tuned models on the original Brazilian dataset vs. the English benchmark dataset. (*Note: Evaluation is ongoing*)
""")
# --- Embed Generalization Plot ---
st.markdown("#### Generalization Performance: Original vs. English Benchmark")
try:
# Construct path relative to the current script file
current_dir = pathlib.Path(__file__).parent
gen_path = current_dir.parent / "assets/generic_eval_all.html"
if gen_path.is_file():
with open(gen_path, 'r', encoding='utf-8') as f:
gen_html = f.read()
components.html(gen_html, height=850, scrolling=True)
else:
st.warning(f"Generalization plot file not found at `{gen_path}`")
except NameError:
# Handle case where __file__ is not defined
st.warning("Cannot determine file path automatically. Make sure `assets/generic_eval_all.html` exists relative to the execution directory.")
except Exception as e:
st.error(f"Error loading generalization plot: {e}")
# --- Conclusions & Next Steps ---
st.markdown("---")
st.markdown("### Conclusions & Next Steps")
st.markdown("""
**Key Insights:**
- Fine-tuned open-source VLMs (even smaller ones) can achieve high accuracy on specific document extraction tasks, rivaling larger models.
- Parameter-efficient fine-tuning (LoRA) with tools like Unsloth and MS-Swift is effective and feasible on standard hardware (e.g., L4 GPU).
- vLLM significantly optimizes inference speed for VLMs.
- There's a trade-off: Fine-tuning boosts performance on target domains but may reduce generalization to unseen document types (analysis ongoing).
**Ongoing Work:**
- Completing the generalization evaluation.
- Implementing a production-ready inference pipeline using optimized fine-tuned models.
- Exploring few-shot adaptation techniques for new document types.
- Investigating model distillation to potentially create even smaller, efficient models.
""")
# Additional career highlights
st.markdown("---")
st.subheader("Additional ML Engineering Experience at Tech4Humans")
st.markdown(
"""
Beyond the computer vision projects detailed above, my role at Tech4Humans has involved:
- **MLOps Pipeline Development:** Building robust training and deployment pipelines for ML models
- **Performance Optimization:** Tuning models for efficient inference in resource-constrained environments
- **Data Engineering:** Creating pipelines for data acquisition, cleaning, and annotation
- **Model Monitoring:** Implementing systems to track model performance and detect drift
- **Client Consulting:** Working directly with clients to understand requirements and translate them into ML solutions
"""
)
|