Skip to content

A curated collection of practical AI projects implementing OCR systems, RAG, AI agents, and other AI use cases.

Fix CodeRabbit comments: sanitize inputs, cap workers, fix stream error handling, fix page config, fix pdf_filler all-pages scan, fix llm buffer reset, fix run.cmd directory anchor

Tiioluwanif65f17eeff55
diff --git a/ai_agents/agentic-form-filler/.env.example b/ai_agents/agentic-form-filler/.env.example
index 26cc390..17a86bb 100644
--- a/ai_agents/agentic-form-filler/.env.example
+++ b/ai_agents/agentic-form-filler/.env.example
@@ -1,2 +1,2 @@
-VISION_AGENT_API_KEY=your_landing_ai_key_here
-MINIMAX_API_KEY=your_minimax_api_key_here
+VISION_AGENT_API_KEY=your_landing_ai_key_here
+MINIMAX_API_KEY=your_minimax_api_key_here
diff --git a/ai_agents/agentic-form-filler/app.py b/ai_agents/agentic-form-filler/app.py
index b0dc5c6..13d40da 100644
--- a/ai_agents/agentic-form-filler/app.py
+++ b/ai_agents/agentic-form-filler/app.py
@@ -1,9 +1,13 @@
import streamlit as st
+
+st.set_page_config(page_title="Form-Fill AI", layout="wide")
+
import os
from dotenv import load_dotenv
load_dotenv()
+import re
import json
import time
import base64
@@ -24,8 +28,12 @@ from pdf_filler import (
SESSION_DIR = "sessions"
os.makedirs(SESSION_DIR, exist_ok=True)
+def _sanitize_sid(sid: str) -> str:
+ """Strip any path separators or dots to prevent directory traversal."""
+ return re.sub(r'[^a-zA-Z0-9_-]', '', sid)
+
def save_session():
- sid = st.session_state.get("session_id")
+ sid = _sanitize_sid(st.session_state.get("session_id", ""))
if not sid:
return
pdf_b64 = None
@@ -131,7 +139,6 @@ for k, v in defaults.items():
# ─────────────────────────────────────────────
# PAGE CONFIG & STYLE
# ─────────────────────────────────────────────
-st.set_page_config(page_title="Form-Fill AI", layout="wide")
st.markdown("""
<style>
.stChatFloatingInputContainer { bottom: 20px; }
@@ -156,7 +163,8 @@ with st.sidebar:
if uploaded_file:
os.makedirs("temp_forms", exist_ok=True)
- temp_path = f"temp_forms/{uploaded_file.name}"
+ safe_name = re.sub(r'[^a-zA-Z0-9_.-]', '_', uploaded_file.name)
+ temp_path = f"temp_forms/{safe_name}"
with open(temp_path, "wb") as f:
f.write(uploaded_file.getbuffer())
st.session_state.target_pdf_path = temp_path
@@ -175,7 +183,8 @@ with st.sidebar:
temp_source_paths = []
os.makedirs("temp_sources", exist_ok=True)
for sf in source_files:
- spath = f"temp_sources/{sf.name}"
+ safe_sname = re.sub(r'[^a-zA-Z0-9_.-]', '_', sf.name)
+ spath = f"temp_sources/{safe_sname}"
with open(spath, "wb") as f:
f.write(sf.getbuffer())
temp_source_paths.append(spath)
@@ -191,7 +200,7 @@ with st.sidebar:
progress_bar = st.progress(0, text="Starting extraction (parallel)...")
results = {}
- with ThreadPoolExecutor(max_workers=total) as executor:
+ with ThreadPoolExecutor(max_workers=min(total, 4)) as executor:
futures = {executor.submit(extract_form_data, p): p for p in all_paths}
completed = 0
for future in as_completed(futures):
@@ -462,22 +471,26 @@ else:
st.session_state.pdf_field_names,
)
- for kind, content in stream:
- if kind == "TEXT":
- full_response += content
- placeholder.markdown(full_response + "▌")
- elif kind == "FIELD_UPDATE":
- st.session_state.registry.update(content)
- elif kind == "SIGNAL" and content == "READY_TO_FILL":
- st.session_state.ready_to_fill = True
- elif kind == "DONE":
- cleaned = content.replace("[READY_TO_FILL]", "").strip()
- placeholder.markdown(cleaned)
- st.session_state.chat_history.append({"role": "assistant", "content": cleaned})
- if st.session_state.step == 3:
- st.session_state.step = 4
- save_session()
- st.rerun()
+ try:
+ for kind, content in stream:
+ if kind == "TEXT":
+ full_response += content
+ placeholder.markdown(full_response + "▌")
+ elif kind == "FIELD_UPDATE":
+ st.session_state.registry.update(content)
+ elif kind == "SIGNAL" and content == "READY_TO_FILL":
+ st.session_state.ready_to_fill = True
+ elif kind == "DONE":
+ cleaned = content.replace("[READY_TO_FILL]", "").strip()
+ placeholder.markdown(cleaned)
+ st.session_state.chat_history.append({"role": "assistant", "content": cleaned})
+ if st.session_state.step == 3:
+ st.session_state.step = 4
+ save_session()
+ st.rerun()
+ except Exception as e:
+ st.error(f"Stream error: {e}")
+ save_session()
if prompt := st.chat_input(
"Provide missing details or say 'leave blank' for any field...",
diff --git a/ai_agents/agentic-form-filler/llm.py b/ai_agents/agentic-form-filler/llm.py
index 8d49ae2..04cf885 100644
--- a/ai_agents/agentic-form-filler/llm.py
+++ b/ai_agents/agentic-form-filler/llm.py
@@ -120,13 +120,14 @@ def chat_and_update_fields_stream(history: list, markdown: str, source_markdown:
yield ("SIGNAL", "READY_TO_FILL")
buffer = buffer.replace("[READY_TO_FILL]", "")
+ # 3. Handle standard REPLY: text streaming
# 3. Handle standard REPLY: text streaming
if "REPLY:" in buffer:
parts = buffer.split("REPLY:")
if len(parts) > 1:
text_chunk = parts[1]
yield ("TEXT", text_chunk)
- buffer = ""
+ buffer = parts[1]
# Clean up reasoning blocks at the very end if any leaked
final_clean = re.sub(r'<think>.*?</think>', '', full_content, flags=re.DOTALL).strip()
diff --git a/ai_agents/agentic-form-filler/pdf_filler.py b/ai_agents/agentic-form-filler/pdf_filler.py
index 7c7752f..9154134 100644
--- a/ai_agents/agentic-form-filler/pdf_filler.py
+++ b/ai_agents/agentic-form-filler/pdf_filler.py
@@ -79,23 +79,23 @@ def build_semantic_field_map(pdf_path: str) -> dict:
"""
try:
doc = fitz.open(pdf_path)
- page = doc[0]
- spans = []
- for b in page.get_text("dict")["blocks"]:
- if b["type"] == 0:
- for line in b["lines"]:
- for span in line["spans"]:
- t = span["text"].strip()
- if t:
- spans.append((span["bbox"], t))
-
field_labels = {}
- for widget in (page.widgets() or []):
- wr = widget.rect
- # Tight column-above search: same x-column as widget, 22px above
- tight_above = fitz.Rect(wr.x0 - 5, wr.y0 - 22, wr.x1 + 5, wr.y0 - 1)
- matches = [s[1] for s in spans if fitz.Rect(s[0]).intersects(tight_above)]
- field_labels[widget.field_name] = " ".join(matches)
+ for page in doc:
+ spans = []
+ for b in page.get_text("dict")["blocks"]:
+ if b["type"] == 0:
+ for line in b["lines"]:
+ for span in line["spans"]:
+ t = span["text"].strip()
+ if t:
+ spans.append((span["bbox"], t))
+
+ for widget in (page.widgets() or []):
+ wr = widget.rect
+ # Tight column-above search: same x-column as widget, 22px above
+ tight_above = fitz.Rect(wr.x0 - 5, wr.y0 - 22, wr.x1 + 5, wr.y0 - 1)
+ matches = [s[1] for s in spans if fitz.Rect(s[0]).intersects(tight_above)]
+ field_labels[widget.field_name] = " ".join(matches)
doc.close()
return field_labels
diff --git a/ai_agents/agentic-form-filler/run.cmd b/ai_agents/agentic-form-filler/run.cmd
index a00756b..d1375b8 100644
--- a/ai_agents/agentic-form-filler/run.cmd
+++ b/ai_agents/agentic-form-filler/run.cmd
@@ -1,4 +1,5 @@
@echo off
+cd /d "%~dp0"
echo Starting Streamlit Form Filling App...
call .venv\Scripts\activate.bat
-streamlit run app.py
+streamlit run app.py
\ No newline at end of file