Spaces:
Running
Running
Muhammad Risqi Firdaus commited on
Commit Β·
ec196c2
1
Parent(s): 9dbe87e
feat: cover letter--schengen
Browse files- src/document_generator_models.py +50 -31
- src/pages/03_Document_Generator.py +484 -309
src/document_generator_models.py
CHANGED
|
@@ -8,9 +8,10 @@ from enum import StrEnum
|
|
| 8 |
# Each value must match the string the backend expects.
|
| 9 |
|
| 10 |
class DocumentType(StrEnum):
|
| 11 |
-
|
| 12 |
-
#
|
| 13 |
-
#
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
# ββ Field & schema descriptors βββββββββββββββββββββββββββββ
|
|
@@ -64,36 +65,36 @@ class DocumentSchema(BaseModel):
|
|
| 64 |
# To add a new document type:
|
| 65 |
# 1. Add its value to DocumentType above.
|
| 66 |
# 2. Add a DocumentSchema entry here.
|
| 67 |
-
#
|
| 68 |
-
# The backend receives `document_name` and generates the SQL via LLM.
|
| 69 |
|
| 70 |
DOCUMENT_REGISTRY: Dict[str, DocumentSchema] = {
|
| 71 |
-
DocumentType.
|
| 72 |
-
document_type=DocumentType.
|
| 73 |
title="Schengen Visa Cover Letter",
|
| 74 |
icon="π",
|
| 75 |
sections={
|
| 76 |
"trip": "π Trip Details",
|
| 77 |
-
"applicant": "π€ Applicant Details",
|
| 78 |
"contact": "π Contact & Financials",
|
| 79 |
},
|
| 80 |
fields=[
|
| 81 |
# ββ Trip section βββββββββββββββββββββββββββββββ
|
| 82 |
-
|
| 83 |
-
FieldSchema(widget_key="
|
| 84 |
-
FieldSchema(widget_key="
|
| 85 |
-
FieldSchema(widget_key="
|
| 86 |
-
FieldSchema(widget_key="
|
| 87 |
-
FieldSchema(widget_key="
|
| 88 |
-
FieldSchema(widget_key="
|
| 89 |
-
FieldSchema(widget_key="
|
| 90 |
-
FieldSchema(widget_key="
|
|
|
|
| 91 |
# ββ Applicant section (nested under personal_details) ββ
|
| 92 |
-
FieldSchema(widget_key="cl_pd_name", data_key="name", label="Full Name", placeholder="e.g. John Doe",
|
| 93 |
-
FieldSchema(widget_key="cl_pd_dob", data_key="dob", label="Date of Birth", placeholder="e.g. 1st Jan 1990",
|
| 94 |
-
FieldSchema(widget_key="cl_pd_nationality", data_key="nationality", label="Nationality", placeholder="e.g. Indonesian",
|
| 95 |
-
FieldSchema(widget_key="cl_pd_occupation", data_key="occupation", label="Occupation", placeholder="e.g. Engineer",
|
| 96 |
-
FieldSchema(widget_key="cl_pd_passport_number", data_key="passport_number", label="Passport Number", placeholder="e.g. A1234567",
|
| 97 |
# ββ Contact section ββββββββββββββββββββββββββββ
|
| 98 |
FieldSchema(widget_key="cl_trip_highlight", data_key="trip_highlight", label="Trip Highlight", placeholder="Key highlights of your trip...", field_type="text_area", section="contact"),
|
| 99 |
FieldSchema(widget_key="cl_contact_email", data_key="contact_email", label="Contact Email", placeholder="e.g. john@email.com", section="contact"),
|
|
@@ -111,12 +112,12 @@ DOCUMENT_REGISTRY: Dict[str, DocumentSchema] = {
|
|
| 111 |
|
| 112 |
class PrefillDocumentRequest(BaseModel):
|
| 113 |
"""
|
| 114 |
-
Sent to /prefill-document.
|
| 115 |
-
|
| 116 |
-
|
| 117 |
"""
|
| 118 |
application_id: int
|
| 119 |
-
|
| 120 |
|
| 121 |
|
| 122 |
class GenerateDocumentRequest(BaseModel):
|
|
@@ -132,13 +133,31 @@ class GenerateDocumentRequest(BaseModel):
|
|
| 132 |
|
| 133 |
|
| 134 |
class DocChatRequest(BaseModel):
|
| 135 |
-
"""Sent to /generate-document/chat."""
|
| 136 |
query: str
|
| 137 |
history: List[Dict[str, str]]
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
|
| 143 |
|
| 144 |
# ββ Shared sub-models (used for type hints / validation internally) ββ
|
|
|
|
| 8 |
# Each value must match the string the backend expects.
|
| 9 |
|
| 10 |
class DocumentType(StrEnum):
|
| 11 |
+
COVER_LETTER_SCHENGEN = "cover_letter_schengen"
|
| 12 |
+
# COVER_LETTER_UK = "cover_letter_uk"
|
| 13 |
+
# INVITATION_LETTER = "invitation_letter"
|
| 14 |
+
# BANK_REFERENCE = "bank_reference"
|
| 15 |
|
| 16 |
|
| 17 |
# ββ Field & schema descriptors βββββββββββββββββββββββββββββ
|
|
|
|
| 65 |
# To add a new document type:
|
| 66 |
# 1. Add its value to DocumentType above.
|
| 67 |
# 2. Add a DocumentSchema entry here.
|
| 68 |
+
# The frontend auto-generates a tab and form from the schema β no UI code needed.
|
|
|
|
| 69 |
|
| 70 |
DOCUMENT_REGISTRY: Dict[str, DocumentSchema] = {
|
| 71 |
+
DocumentType.COVER_LETTER_SCHENGEN: DocumentSchema(
|
| 72 |
+
document_type=DocumentType.COVER_LETTER_SCHENGEN,
|
| 73 |
title="Schengen Visa Cover Letter",
|
| 74 |
icon="π",
|
| 75 |
sections={
|
| 76 |
"trip": "π Trip Details",
|
| 77 |
+
"applicant": "π€ Main Applicant Details",
|
| 78 |
"contact": "π Contact & Financials",
|
| 79 |
},
|
| 80 |
fields=[
|
| 81 |
# ββ Trip section βββββββββββββββββββββββββββββββ
|
| 82 |
+
# data_key matches the prefill response keys returned by /prefill-document
|
| 83 |
+
FieldSchema(widget_key="cl_country", data_key="country", label="Country of Embassy", placeholder="e.g. Germany", section="trip"),
|
| 84 |
+
FieldSchema(widget_key="cl_city", data_key="city", label="City of Application", placeholder="e.g. Jakarta", section="trip"),
|
| 85 |
+
FieldSchema(widget_key="cl_purpose", data_key="purpose", label="Purpose of Trip", placeholder="e.g. tourism", section="trip"),
|
| 86 |
+
FieldSchema(widget_key="cl_main_dest", data_key="main_dest", label="Main Destination", placeholder="e.g. Germany", section="trip"),
|
| 87 |
+
FieldSchema(widget_key="cl_event", data_key="event", label="Event", placeholder="e.g. personal vacation", section="trip"),
|
| 88 |
+
FieldSchema(widget_key="cl_other_dest", data_key="other_dest", label="Other Destinations", placeholder="e.g. France and Italy", section="trip"),
|
| 89 |
+
FieldSchema(widget_key="cl_start", data_key="start", label="Travel Start Date", placeholder="e.g. 2026-05-01", section="trip"),
|
| 90 |
+
FieldSchema(widget_key="cl_end", data_key="end", label="Travel End Date", placeholder="e.g. 2026-05-14", section="trip"),
|
| 91 |
+
FieldSchema(widget_key="cl_duration", data_key="duration", label="Duration", placeholder="e.g. 14 days", section="trip"),
|
| 92 |
# ββ Applicant section (nested under personal_details) ββ
|
| 93 |
+
FieldSchema(widget_key="cl_pd_name", data_key="name", label="Full Name", placeholder="e.g. John Doe", section="applicant", nested_under="personal_details"),
|
| 94 |
+
FieldSchema(widget_key="cl_pd_dob", data_key="dob", label="Date of Birth", placeholder="e.g. 1st Jan 1990", section="applicant", nested_under="personal_details"),
|
| 95 |
+
FieldSchema(widget_key="cl_pd_nationality", data_key="nationality", label="Nationality", placeholder="e.g. Indonesian", section="applicant", nested_under="personal_details"),
|
| 96 |
+
FieldSchema(widget_key="cl_pd_occupation", data_key="occupation", label="Occupation", placeholder="e.g. Engineer", section="applicant", nested_under="personal_details"),
|
| 97 |
+
FieldSchema(widget_key="cl_pd_passport_number", data_key="passport_number", label="Passport Number", placeholder="e.g. A1234567", section="applicant", nested_under="personal_details"),
|
| 98 |
# ββ Contact section ββββββββββββββββββββββββββββ
|
| 99 |
FieldSchema(widget_key="cl_trip_highlight", data_key="trip_highlight", label="Trip Highlight", placeholder="Key highlights of your trip...", field_type="text_area", section="contact"),
|
| 100 |
FieldSchema(widget_key="cl_contact_email", data_key="contact_email", label="Contact Email", placeholder="e.g. john@email.com", section="contact"),
|
|
|
|
| 112 |
|
| 113 |
class PrefillDocumentRequest(BaseModel):
|
| 114 |
"""
|
| 115 |
+
Sent to /prefill-document (structure mode).
|
| 116 |
+
`structure` describes the fields the LLM should map from DB data.
|
| 117 |
+
Returns a flat dict of { field_key: value_or_null, ..., "_missing_required": [...] }.
|
| 118 |
"""
|
| 119 |
application_id: int
|
| 120 |
+
structure: List[Dict[str, Any]]
|
| 121 |
|
| 122 |
|
| 123 |
class GenerateDocumentRequest(BaseModel):
|
|
|
|
| 133 |
|
| 134 |
|
| 135 |
class DocChatRequest(BaseModel):
|
| 136 |
+
"""Sent to /generate-document/chat (new stateless draft-revision flow)."""
|
| 137 |
query: str
|
| 138 |
history: List[Dict[str, str]]
|
| 139 |
+
session_uuid: Optional[str] = None
|
| 140 |
+
current_document_content: str = ""
|
| 141 |
+
structure: Optional[List[Dict[str, Any]]] = None
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class GenerateDraftRequest(BaseModel):
|
| 145 |
+
"""
|
| 146 |
+
Sent to /generate-document/draft.
|
| 147 |
+
Generates a Markdown draft without creating a Google Doc.
|
| 148 |
+
`doc_type` and `structure` are stored on the frontend for later handover to the core API.
|
| 149 |
+
"""
|
| 150 |
+
doc_type: str
|
| 151 |
+
data: Dict[str, Any]
|
| 152 |
+
structure: Optional[List[Dict[str, Any]]] = None # field definitions for core API handover
|
| 153 |
+
session_uuid: Optional[str] = None
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class ExportDocumentRequest(BaseModel):
|
| 157 |
+
"""Sent to /export-document once the user is satisfied with the draft."""
|
| 158 |
+
document_content: str
|
| 159 |
+
title: Optional[str] = None
|
| 160 |
+
export_format: str = "gdocs"
|
| 161 |
|
| 162 |
|
| 163 |
# ββ Shared sub-models (used for type hints / validation internally) ββ
|
src/pages/03_Document_Generator.py
CHANGED
|
@@ -11,10 +11,12 @@ from dotenv import load_dotenv
|
|
| 11 |
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
|
| 12 |
from src.document_generator_models import (
|
| 13 |
DocumentType,
|
|
|
|
| 14 |
DOCUMENT_REGISTRY,
|
| 15 |
PrefillDocumentRequest,
|
| 16 |
-
GenerateDocumentRequest,
|
| 17 |
DocChatRequest,
|
|
|
|
|
|
|
| 18 |
)
|
| 19 |
|
| 20 |
load_dotenv()
|
|
@@ -22,97 +24,111 @@ load_dotenv()
|
|
| 22 |
API_BASE_URL = os.getenv("URL_CE_BOT", "http://localhost:5000")
|
| 23 |
TODAY = datetime.date.today()
|
| 24 |
|
|
|
|
| 25 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
-
#
|
|
|
|
| 27 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
|
| 29 |
-
|
| 30 |
-
|
|
|
|
| 31 |
|
| 32 |
|
| 33 |
-
def
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
-
|
| 50 |
|
| 51 |
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
def
|
| 54 |
-
"""
|
| 55 |
-
for key in
|
| 56 |
st.session_state.pop(key, None)
|
| 57 |
|
| 58 |
|
| 59 |
-
def
|
| 60 |
-
if data is
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
st.session_state
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
st.session_state
|
| 92 |
-
st.session_state
|
| 93 |
-
st.session_state
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
try:
|
| 100 |
-
|
| 101 |
-
if application_id:
|
| 102 |
-
try:
|
| 103 |
-
app_id_int = int(application_id)
|
| 104 |
-
except (ValueError, TypeError):
|
| 105 |
-
pass
|
| 106 |
-
request = DocChatRequest(
|
| 107 |
query=query,
|
| 108 |
history=history,
|
| 109 |
session_uuid=session_uuid,
|
| 110 |
-
|
| 111 |
-
|
| 112 |
)
|
| 113 |
resp = requests.post(
|
| 114 |
f"{API_BASE_URL}/generate-document/chat",
|
| 115 |
-
json=
|
| 116 |
timeout=120,
|
| 117 |
)
|
| 118 |
resp.raise_for_status()
|
|
@@ -121,87 +137,238 @@ def call_doc_chat_api(query, history, application_id, session_uuid, doc_data=Non
|
|
| 121 |
return None, str(e)
|
| 122 |
|
| 123 |
|
| 124 |
-
def
|
| 125 |
-
"""
|
| 126 |
-
`document_name` tells the backend which SQL to generate (via LLM).
|
| 127 |
-
`form_data` is forwarded as `doc_data` for the backend to merge on top of DB data.
|
| 128 |
-
"""
|
| 129 |
try:
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
)
|
| 135 |
resp = requests.post(
|
| 136 |
-
f"{API_BASE_URL}/generate-document",
|
| 137 |
-
json=
|
| 138 |
timeout=120,
|
| 139 |
)
|
| 140 |
resp.raise_for_status()
|
| 141 |
return resp.json(), None
|
| 142 |
-
except (ValueError, TypeError) as e:
|
| 143 |
-
return None, f"Invalid application_id: {e}"
|
| 144 |
except Exception as e:
|
| 145 |
return None, str(e)
|
| 146 |
|
| 147 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
|
| 150 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 151 |
-
#
|
| 152 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
-
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 163 |
-
# TAB 1: COVER LETTER (undo/redo + chat, data from DB)
|
| 164 |
-
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
-
# ββ Application ID row ββ
|
| 171 |
load_c1, load_c2, load_c3 = st.columns([2, 1, 3])
|
| 172 |
with load_c1:
|
| 173 |
app_id_input = st.text_input(
|
| 174 |
"Application ID",
|
| 175 |
-
value=st.session_state
|
| 176 |
placeholder="Enter Application ID (e.g. 5786)",
|
| 177 |
-
key="
|
| 178 |
label_visibility="collapsed",
|
| 179 |
)
|
| 180 |
with load_c2:
|
| 181 |
-
load_clicked = st.button(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
with load_c3:
|
| 183 |
-
if st.session_state
|
| 184 |
info_c, clear_c = st.columns([4, 1])
|
| 185 |
with info_c:
|
| 186 |
-
st.caption(f"β
Loaded: Application ID **{st.session_state
|
| 187 |
with clear_c:
|
| 188 |
-
if st.button("β", key="
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
st.session_state
|
| 192 |
-
st.session_state
|
| 193 |
-
st.session_state
|
| 194 |
-
st.session_state
|
| 195 |
-
st.session_state
|
| 196 |
-
st.session_state
|
|
|
|
|
|
|
|
|
|
| 197 |
st.rerun()
|
| 198 |
|
|
|
|
| 199 |
if load_clicked:
|
| 200 |
if app_id_input:
|
| 201 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
prefill_req = PrefillDocumentRequest(
|
| 203 |
application_id=int(app_id_input),
|
| 204 |
-
|
| 205 |
)
|
| 206 |
resp = requests.post(
|
| 207 |
f"{API_BASE_URL}/prefill-document",
|
|
@@ -209,15 +376,25 @@ with tab1:
|
|
| 209 |
timeout=60,
|
| 210 |
)
|
| 211 |
if resp.status_code == 200:
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
st.session_state
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
st.success(f"β
Loaded data for Application ID: {app_id_input}")
|
| 222 |
st.rerun()
|
| 223 |
else:
|
|
@@ -235,205 +412,203 @@ with tab1:
|
|
| 235 |
|
| 236 |
st.divider()
|
| 237 |
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
st.markdown(msg["content"])
|
| 242 |
-
|
| 243 |
-
if not st.session_state.cl_data and not st.session_state.cl_chat_messages:
|
| 244 |
-
st.info("π Enter an Application ID above to load data from the database, or use the chat below to describe your cover letter needs.")
|
| 245 |
-
|
| 246 |
-
# ββ Generated document URL ββ
|
| 247 |
-
if st.session_state.cl_doc_url:
|
| 248 |
-
st.success("π Document Generated!")
|
| 249 |
-
if "docs.google.com" in st.session_state.cl_doc_url:
|
| 250 |
-
st.link_button("π Open in Google Docs", st.session_state.cl_doc_url, use_container_width=True)
|
| 251 |
-
else:
|
| 252 |
-
st.markdown(f"[π View Document]({st.session_state.cl_doc_url})")
|
| 253 |
|
| 254 |
-
# ββ Editable form
|
| 255 |
-
|
| 256 |
-
data = st.session_state.cl_data
|
| 257 |
-
updated_data = copy.deepcopy(data)
|
| 258 |
-
form_changed = False
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
)
|
| 272 |
-
if trip_type != cur_trip:
|
| 273 |
-
updated_data["trip_type"] = trip_type
|
| 274 |
-
form_changed = True
|
| 275 |
-
|
| 276 |
-
col1, col2 = st.columns(2)
|
| 277 |
-
|
| 278 |
-
with col1:
|
| 279 |
-
st.subheader("π Trip Details")
|
| 280 |
-
for wk, dk, label, ph in [
|
| 281 |
-
("cl_country", "country", "Country of Embassy", "e.g. Germany"),
|
| 282 |
-
("cl_city", "city_of_application", "City of Application", "e.g. Jakarta"),
|
| 283 |
-
("cl_purpose", "purpose", "Purpose of Trip", "e.g. tourism"),
|
| 284 |
-
("cl_main_dest", "destination_country", "Main Destination", "e.g. Germany"),
|
| 285 |
-
("cl_event", "event", "Event", "e.g. personal vacation"),
|
| 286 |
-
("cl_other_dest", "other_dest", "Other Destinations", "e.g. France and Italy"),
|
| 287 |
-
("cl_start", "start_date", "Travel Start Date", "e.g. 2026-05-01"),
|
| 288 |
-
("cl_end", "end_date", "Travel End Date", "e.g. 2026-05-14"),
|
| 289 |
-
("cl_duration", "duration", "Duration", "e.g. 14 days"),
|
| 290 |
-
]:
|
| 291 |
-
cur = data.get(dk, "") or ""
|
| 292 |
-
new = st.text_input(label, value=cur, placeholder=ph, key=wk)
|
| 293 |
-
if new != cur:
|
| 294 |
-
updated_data[dk] = new
|
| 295 |
-
form_changed = True
|
| 296 |
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
("
|
| 302 |
-
("
|
| 303 |
-
("cl_pd_nationality", "nationality", "Nationality", "e.g. Indonesian"),
|
| 304 |
-
("cl_pd_occupation", "occupation", "Occupation", "e.g. Engineer"),
|
| 305 |
-
("cl_pd_passport_number", "passport_number", "Passport Number", "e.g. A1234567"),
|
| 306 |
-
]:
|
| 307 |
-
cur = pd_data.get(fk, "") or ""
|
| 308 |
-
new = st.text_input(label, value=cur, placeholder=ph, key=wk)
|
| 309 |
-
if new != cur:
|
| 310 |
-
if updated_data.get("personal_details") is None:
|
| 311 |
-
updated_data["personal_details"] = copy.deepcopy(pd_data)
|
| 312 |
-
updated_data["personal_details"][fk] = new
|
| 313 |
-
form_changed = True
|
| 314 |
-
|
| 315 |
-
st.subheader("π Contact & Financials")
|
| 316 |
-
for wk, dk, label, ph, is_area in [
|
| 317 |
-
("cl_trip_highlight", "trip_highlight", "Trip Highlight", "Key highlights of your trip...", True),
|
| 318 |
-
("cl_contact_email", "contact_email", "Contact Email", "e.g. john@email.com", False),
|
| 319 |
-
("cl_contact_phone", "contact_phone", "Contact Phone", "e.g. +62 812 345 6789", False),
|
| 320 |
-
("cl_job_commitment", "job_commitment", "Job Commitment", "e.g. returning to work on...", False),
|
| 321 |
-
("cl_financial_status", "financial_status", "Financial Status", "e.g. sufficient funds", False),
|
| 322 |
-
]:
|
| 323 |
-
cur = data.get(dk, "") or ""
|
| 324 |
-
new = (st.text_area if is_area else st.text_input)(label, value=cur, placeholder=ph, key=wk)
|
| 325 |
-
if new != cur:
|
| 326 |
-
updated_data[dk] = new
|
| 327 |
-
form_changed = True
|
| 328 |
-
|
| 329 |
-
# Group members table
|
| 330 |
-
if trip_type == "Group":
|
| 331 |
-
st.subheader("π₯ Group Members")
|
| 332 |
-
gm_list = data.get("group_members", []) or []
|
| 333 |
-
gm_df = pd.DataFrame(
|
| 334 |
-
gm_list or [{"relationship": "", "name": "", "dob": "", "occupation": "", "nationality": "", "passport_number": ""}],
|
| 335 |
-
columns=["relationship", "name", "dob", "occupation", "nationality", "passport_number"],
|
| 336 |
)
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
|
| 349 |
-
|
|
|
|
| 350 |
st.divider()
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
with
|
| 359 |
-
st.
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
)
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 371 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
|
| 373 |
-
if
|
| 374 |
-
|
| 375 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 376 |
else:
|
| 377 |
-
|
| 378 |
-
result, err = call_generate_document(
|
| 379 |
-
st.session_state.cl_app_id,
|
| 380 |
-
DocumentType.COVER_LETTER,
|
| 381 |
-
st.session_state.cl_data,
|
| 382 |
-
)
|
| 383 |
-
if err:
|
| 384 |
-
st.error(f"β Error: {err}")
|
| 385 |
-
elif result and result.get("url"):
|
| 386 |
-
st.session_state.cl_doc_url = result["url"]
|
| 387 |
-
st.rerun()
|
| 388 |
-
else:
|
| 389 |
-
st.error("β Failed to generate document (no URL returned).")
|
| 390 |
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
else "Describe your cover letter needs, or mention an Application ID to load data..."
|
| 397 |
-
)
|
| 398 |
-
chat_c1, chat_c2 = st.columns([5, 1])
|
| 399 |
-
with chat_c1:
|
| 400 |
-
chat_text = st.text_input(
|
| 401 |
-
"Chat", placeholder=placeholder_text,
|
| 402 |
-
key="cl_chat_input", label_visibility="collapsed",
|
| 403 |
)
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
st.session_state.cl_session_uuid,
|
| 419 |
-
doc_data=st.session_state.cl_data,
|
| 420 |
)
|
| 421 |
|
| 422 |
-
if
|
| 423 |
-
st.session_state.
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
st.
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
|
| 12 |
from src.document_generator_models import (
|
| 13 |
DocumentType,
|
| 14 |
+
DocumentSchema,
|
| 15 |
DOCUMENT_REGISTRY,
|
| 16 |
PrefillDocumentRequest,
|
|
|
|
| 17 |
DocChatRequest,
|
| 18 |
+
GenerateDraftRequest,
|
| 19 |
+
ExportDocumentRequest,
|
| 20 |
)
|
| 21 |
|
| 22 |
load_dotenv()
|
|
|
|
| 24 |
API_BASE_URL = os.getenv("URL_CE_BOT", "http://localhost:5000")
|
| 25 |
TODAY = datetime.date.today()
|
| 26 |
|
| 27 |
+
|
| 28 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
+
# GENERIC SESSION STATE
|
| 30 |
+
# Keys: doc_{doc_type}_{suffix} (one set per registered doc type)
|
| 31 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
|
| 33 |
+
def _sk(doc_type: str, suffix: str) -> str:
|
| 34 |
+
"""Compose a session-state key from doc type + suffix."""
|
| 35 |
+
return f"doc_{doc_type}_{suffix}"
|
| 36 |
|
| 37 |
|
| 38 |
+
def _init_all_doc_states():
|
| 39 |
+
"""Initialize session-state slots for every registered document type."""
|
| 40 |
+
for doc_type in DOCUMENT_REGISTRY:
|
| 41 |
+
defaults = {
|
| 42 |
+
_sk(doc_type, "data"): None,
|
| 43 |
+
_sk(doc_type, "chat_messages"): [],
|
| 44 |
+
_sk(doc_type, "api_history"): [],
|
| 45 |
+
_sk(doc_type, "history_stack"): [],
|
| 46 |
+
_sk(doc_type, "redo_stack"): [],
|
| 47 |
+
_sk(doc_type, "session_uuid"): str(uuid.uuid4()),
|
| 48 |
+
_sk(doc_type, "app_id"): "",
|
| 49 |
+
_sk(doc_type, "draft_content"): "",
|
| 50 |
+
_sk(doc_type, "draft_generated"): False,
|
| 51 |
+
_sk(doc_type, "doc_structure"): None,
|
| 52 |
+
_sk(doc_type, "doc_url"): None,
|
| 53 |
+
}
|
| 54 |
+
for key, val in defaults.items():
|
| 55 |
+
if key not in st.session_state:
|
| 56 |
+
st.session_state[key] = val
|
| 57 |
|
| 58 |
|
| 59 |
+
_init_all_doc_states()
|
| 60 |
|
| 61 |
|
| 62 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
+
# UNDO / REDO
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
|
| 66 |
+
def _clear_widget_keys(doc_type: str):
|
| 67 |
+
"""Pop all widget keys for a doc type so widgets reset from value= on next render."""
|
| 68 |
+
for key in DOCUMENT_REGISTRY[doc_type].widget_keys():
|
| 69 |
st.session_state.pop(key, None)
|
| 70 |
|
| 71 |
|
| 72 |
+
def push_history(doc_type: str, data):
|
| 73 |
+
if data is None:
|
| 74 |
+
return
|
| 75 |
+
st.session_state[_sk(doc_type, "history_stack")].append({
|
| 76 |
+
"data": copy.deepcopy(data),
|
| 77 |
+
"chat": copy.deepcopy(st.session_state[_sk(doc_type, "chat_messages")]),
|
| 78 |
+
"api": copy.deepcopy(st.session_state[_sk(doc_type, "api_history")]),
|
| 79 |
+
})
|
| 80 |
+
st.session_state[_sk(doc_type, "redo_stack")].clear()
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def do_undo(doc_type: str):
|
| 84 |
+
history = st.session_state[_sk(doc_type, "history_stack")]
|
| 85 |
+
if not history:
|
| 86 |
+
return
|
| 87 |
+
st.session_state[_sk(doc_type, "redo_stack")].append({
|
| 88 |
+
"data": copy.deepcopy(st.session_state[_sk(doc_type, "data")]),
|
| 89 |
+
"chat": copy.deepcopy(st.session_state[_sk(doc_type, "chat_messages")]),
|
| 90 |
+
"api": copy.deepcopy(st.session_state[_sk(doc_type, "api_history")]),
|
| 91 |
+
})
|
| 92 |
+
prev = history.pop()
|
| 93 |
+
st.session_state[_sk(doc_type, "data")] = prev["data"]
|
| 94 |
+
st.session_state[_sk(doc_type, "chat_messages")] = prev["chat"]
|
| 95 |
+
st.session_state[_sk(doc_type, "api_history")] = prev["api"]
|
| 96 |
+
_clear_widget_keys(doc_type)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def do_redo(doc_type: str):
|
| 100 |
+
redo = st.session_state[_sk(doc_type, "redo_stack")]
|
| 101 |
+
if not redo:
|
| 102 |
+
return
|
| 103 |
+
st.session_state[_sk(doc_type, "history_stack")].append({
|
| 104 |
+
"data": copy.deepcopy(st.session_state[_sk(doc_type, "data")]),
|
| 105 |
+
"chat": copy.deepcopy(st.session_state[_sk(doc_type, "chat_messages")]),
|
| 106 |
+
"api": copy.deepcopy(st.session_state[_sk(doc_type, "api_history")]),
|
| 107 |
+
})
|
| 108 |
+
nxt = redo.pop()
|
| 109 |
+
st.session_state[_sk(doc_type, "data")] = nxt["data"]
|
| 110 |
+
st.session_state[_sk(doc_type, "chat_messages")] = nxt["chat"]
|
| 111 |
+
st.session_state[_sk(doc_type, "api_history")] = nxt["api"]
|
| 112 |
+
_clear_widget_keys(doc_type)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 116 |
+
# API HELPERS (doc-type-agnostic)
|
| 117 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 118 |
+
|
| 119 |
+
def call_doc_chat_api(query, history, session_uuid, current_document_content="", structure=None):
|
| 120 |
+
"""POST /generate-document/chat β stateless revision."""
|
| 121 |
try:
|
| 122 |
+
req = DocChatRequest(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
query=query,
|
| 124 |
history=history,
|
| 125 |
session_uuid=session_uuid,
|
| 126 |
+
current_document_content=current_document_content,
|
| 127 |
+
structure=structure,
|
| 128 |
)
|
| 129 |
resp = requests.post(
|
| 130 |
f"{API_BASE_URL}/generate-document/chat",
|
| 131 |
+
json=req.model_dump(exclude_none=True),
|
| 132 |
timeout=120,
|
| 133 |
)
|
| 134 |
resp.raise_for_status()
|
|
|
|
| 137 |
return None, str(e)
|
| 138 |
|
| 139 |
|
| 140 |
+
def call_generate_draft(schema: DocumentSchema, form_data, session_uuid=None):
|
| 141 |
+
"""POST /generate-document/draft β returns Markdown, no Google Doc created."""
|
|
|
|
|
|
|
|
|
|
| 142 |
try:
|
| 143 |
+
structure = [
|
| 144 |
+
{"key": f.data_key, "label": f.label, "required": False}
|
| 145 |
+
for f in schema.fields
|
| 146 |
+
]
|
| 147 |
+
req = GenerateDraftRequest(
|
| 148 |
+
doc_type=str(schema.document_type),
|
| 149 |
+
data=form_data or {},
|
| 150 |
+
structure=structure,
|
| 151 |
+
session_uuid=session_uuid,
|
| 152 |
)
|
| 153 |
resp = requests.post(
|
| 154 |
+
f"{API_BASE_URL}/generate-document/draft",
|
| 155 |
+
json=req.model_dump(exclude_none=True),
|
| 156 |
timeout=120,
|
| 157 |
)
|
| 158 |
resp.raise_for_status()
|
| 159 |
return resp.json(), None
|
|
|
|
|
|
|
| 160 |
except Exception as e:
|
| 161 |
return None, str(e)
|
| 162 |
|
| 163 |
|
| 164 |
+
def call_export_document(document_content, title=None):
|
| 165 |
+
"""POST /export-document β converts Markdown to Google Doc."""
|
| 166 |
+
try:
|
| 167 |
+
req = ExportDocumentRequest(document_content=document_content, title=title)
|
| 168 |
+
resp = requests.post(
|
| 169 |
+
f"{API_BASE_URL}/export-document",
|
| 170 |
+
json=req.model_dump(exclude_none=True),
|
| 171 |
+
timeout=120,
|
| 172 |
+
)
|
| 173 |
+
resp.raise_for_status()
|
| 174 |
+
return resp.json(), None
|
| 175 |
+
except Exception as e:
|
| 176 |
+
return None, str(e)
|
| 177 |
|
| 178 |
|
| 179 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 180 |
+
# FORM RENDERING (driven by DocumentSchema metadata)
|
| 181 |
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 182 |
|
| 183 |
+
def _get_field_value(data: dict, field) -> str:
|
| 184 |
+
"""Read a field's current value, respecting nested_under."""
|
| 185 |
+
if field.nested_under:
|
| 186 |
+
return (data.get(field.nested_under) or {}).get(field.data_key, "") or ""
|
| 187 |
+
return data.get(field.data_key, "") or ""
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _apply_field_change(updated_data: dict, original_data: dict, field, new_val: str):
|
| 191 |
+
"""Write a changed value into updated_data, respecting nested_under."""
|
| 192 |
+
if field.nested_under:
|
| 193 |
+
if updated_data.get(field.nested_under) is None:
|
| 194 |
+
updated_data[field.nested_under] = copy.deepcopy(
|
| 195 |
+
original_data.get(field.nested_under) or {}
|
| 196 |
+
)
|
| 197 |
+
updated_data[field.nested_under][field.data_key] = new_val
|
| 198 |
+
else:
|
| 199 |
+
updated_data[field.data_key] = new_val
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _render_section(schema: DocumentSchema, section_key: str, data: dict, updated_data: dict) -> bool:
|
| 203 |
+
"""
|
| 204 |
+
Render all fields for one section.
|
| 205 |
+
Returns True if any field value changed.
|
| 206 |
+
"""
|
| 207 |
+
st.subheader(schema.sections[section_key])
|
| 208 |
+
changed = False
|
| 209 |
+
for field in schema.fields_in_section(section_key):
|
| 210 |
+
cur = _get_field_value(data, field)
|
| 211 |
+
widget = st.text_area if field.field_type == "text_area" else st.text_input
|
| 212 |
+
new = widget(field.label, value=cur, placeholder=field.placeholder, key=field.widget_key)
|
| 213 |
+
if new != cur:
|
| 214 |
+
_apply_field_change(updated_data, data, field, new)
|
| 215 |
+
changed = True
|
| 216 |
+
return changed
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def render_doc_form(schema: DocumentSchema):
|
| 220 |
+
"""
|
| 221 |
+
Render the editable form driven entirely by DocumentSchema.
|
| 222 |
|
| 223 |
+
Layout rules:
|
| 224 |
+
- 1 section β full width
|
| 225 |
+
- 2+ sections β first N//2 sections in left column, remainder in right column
|
| 226 |
|
| 227 |
+
Special elements:
|
| 228 |
+
- has_trip_type=True β radio above columns
|
| 229 |
+
- has_group_members=True β data editor below columns (shown when trip_type=="Group"
|
| 230 |
+
or when the schema has no trip_type toggle)
|
| 231 |
+
"""
|
| 232 |
+
doc_type = str(schema.document_type)
|
| 233 |
+
data = st.session_state[_sk(doc_type, "data")]
|
| 234 |
+
updated_data = copy.deepcopy(data)
|
| 235 |
+
form_changed = False
|
| 236 |
+
|
| 237 |
+
st.subheader("βοΈ Edit Details")
|
| 238 |
+
|
| 239 |
+
# ββ Trip type radio ββββββββββββββββββββββββββββββββββ
|
| 240 |
+
trip_type = None
|
| 241 |
+
if schema.has_trip_type:
|
| 242 |
+
opts = ["Individual", "Group"]
|
| 243 |
+
cur = data.get("trip_type", "Individual")
|
| 244 |
+
if cur not in opts:
|
| 245 |
+
cur = "Individual"
|
| 246 |
+
trip_type = st.radio(
|
| 247 |
+
"Trip Type", opts,
|
| 248 |
+
index=opts.index(cur),
|
| 249 |
+
horizontal=True,
|
| 250 |
+
key=f"{doc_type}_trip_type",
|
| 251 |
+
)
|
| 252 |
+
if trip_type != cur:
|
| 253 |
+
updated_data["trip_type"] = trip_type
|
| 254 |
+
form_changed = True
|
| 255 |
+
|
| 256 |
+
# ββ Section columns ββββββββββββββββββββββββββββββββββ
|
| 257 |
+
section_keys = list(schema.sections.keys())
|
| 258 |
+
if len(section_keys) == 1:
|
| 259 |
+
changed = _render_section(schema, section_keys[0], data, updated_data)
|
| 260 |
+
form_changed = form_changed or changed
|
| 261 |
+
else:
|
| 262 |
+
mid = len(section_keys) // 2 # e.g. 3 sections β mid=1 (left:1, right:2)
|
| 263 |
+
left_sections = section_keys[:mid]
|
| 264 |
+
right_sections = section_keys[mid:]
|
| 265 |
+
col1, col2 = st.columns(2)
|
| 266 |
+
with col1:
|
| 267 |
+
for sk in left_sections:
|
| 268 |
+
changed = _render_section(schema, sk, data, updated_data)
|
| 269 |
+
form_changed = form_changed or changed
|
| 270 |
+
with col2:
|
| 271 |
+
for sk in right_sections:
|
| 272 |
+
changed = _render_section(schema, sk, data, updated_data)
|
| 273 |
+
form_changed = form_changed or changed
|
| 274 |
+
|
| 275 |
+
# ββ Group members data editor ββββββββββββββββββββββββ
|
| 276 |
+
if schema.has_group_members:
|
| 277 |
+
show_group = (trip_type == "Group") if schema.has_trip_type else True
|
| 278 |
+
if show_group:
|
| 279 |
+
st.subheader("π₯ Group Members")
|
| 280 |
+
gm_list = data.get("group_members", []) or []
|
| 281 |
+
gm_cols = ["relationship", "name", "dob", "occupation", "nationality", "passport_number"]
|
| 282 |
+
gm_df = pd.DataFrame(
|
| 283 |
+
gm_list or [dict.fromkeys(gm_cols, "")],
|
| 284 |
+
columns=gm_cols,
|
| 285 |
+
)
|
| 286 |
+
edited_gm = st.data_editor(
|
| 287 |
+
gm_df,
|
| 288 |
+
num_rows="dynamic",
|
| 289 |
+
use_container_width=True,
|
| 290 |
+
key=f"{doc_type}_group_members_editor",
|
| 291 |
+
)
|
| 292 |
+
new_gm = edited_gm.to_dict("records")
|
| 293 |
+
if new_gm != gm_list:
|
| 294 |
+
updated_data["group_members"] = new_gm
|
| 295 |
+
form_changed = True
|
| 296 |
+
|
| 297 |
+
# ββ Persist changes ββββββββββββββββββββββββββββββββββ
|
| 298 |
+
if form_changed:
|
| 299 |
+
push_history(doc_type, data)
|
| 300 |
+
st.session_state[_sk(doc_type, "data")] = updated_data
|
| 301 |
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 304 |
+
# FULL TAB RENDERER
|
| 305 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 306 |
+
|
| 307 |
+
def render_document_tab(schema: DocumentSchema):
|
| 308 |
+
"""Render the complete UI for one document type inside its tab."""
|
| 309 |
+
doc_type = str(schema.document_type)
|
| 310 |
+
|
| 311 |
+
def sk(suffix: str) -> str:
|
| 312 |
+
return _sk(doc_type, suffix)
|
| 313 |
+
|
| 314 |
+
st.header(f"{schema.icon} {schema.title}")
|
| 315 |
+
st.caption(
|
| 316 |
+
"Load applicant data by Application ID, edit the fields directly, "
|
| 317 |
+
"chat to revise, then export the Google Doc."
|
| 318 |
+
)
|
| 319 |
|
| 320 |
+
# ββ Application ID row ββββββββββββββββββββββββββββββ
|
| 321 |
load_c1, load_c2, load_c3 = st.columns([2, 1, 3])
|
| 322 |
with load_c1:
|
| 323 |
app_id_input = st.text_input(
|
| 324 |
"Application ID",
|
| 325 |
+
value=st.session_state[sk("app_id")],
|
| 326 |
placeholder="Enter Application ID (e.g. 5786)",
|
| 327 |
+
key=f"{doc_type}_app_id_input",
|
| 328 |
label_visibility="collapsed",
|
| 329 |
)
|
| 330 |
with load_c2:
|
| 331 |
+
load_clicked = st.button(
|
| 332 |
+
"π Load from DB",
|
| 333 |
+
use_container_width=True,
|
| 334 |
+
key=f"{doc_type}_load_btn",
|
| 335 |
+
)
|
| 336 |
with load_c3:
|
| 337 |
+
if st.session_state[sk("data")] is not None and st.session_state[sk("app_id")]:
|
| 338 |
info_c, clear_c = st.columns([4, 1])
|
| 339 |
with info_c:
|
| 340 |
+
st.caption(f"β
Loaded: Application ID **{st.session_state[sk('app_id')]}**")
|
| 341 |
with clear_c:
|
| 342 |
+
if st.button("β", key=f"{doc_type}_clear_btn", help="Clear and start over"):
|
| 343 |
+
push_history(doc_type, st.session_state[sk("data")])
|
| 344 |
+
_clear_widget_keys(doc_type)
|
| 345 |
+
st.session_state[sk("data")] = None
|
| 346 |
+
st.session_state[sk("app_id")] = ""
|
| 347 |
+
st.session_state[sk("doc_url")] = None
|
| 348 |
+
st.session_state[sk("draft_content")] = ""
|
| 349 |
+
st.session_state[sk("draft_generated")] = False
|
| 350 |
+
st.session_state[sk("doc_structure")] = None
|
| 351 |
+
st.session_state[sk("chat_messages")] = []
|
| 352 |
+
st.session_state[sk("api_history")] = []
|
| 353 |
+
st.session_state[sk("session_uuid")] = str(uuid.uuid4())
|
| 354 |
st.rerun()
|
| 355 |
|
| 356 |
+
# ββ Load from DB ββββββββββββββββββββββββββββββββββββ
|
| 357 |
if load_clicked:
|
| 358 |
if app_id_input:
|
| 359 |
try:
|
| 360 |
+
structure = [
|
| 361 |
+
{
|
| 362 |
+
"key": f.data_key,
|
| 363 |
+
"label": f.label,
|
| 364 |
+
"description": f.placeholder,
|
| 365 |
+
"required": False,
|
| 366 |
+
}
|
| 367 |
+
for f in schema.fields
|
| 368 |
+
]
|
| 369 |
prefill_req = PrefillDocumentRequest(
|
| 370 |
application_id=int(app_id_input),
|
| 371 |
+
structure=structure,
|
| 372 |
)
|
| 373 |
resp = requests.post(
|
| 374 |
f"{API_BASE_URL}/prefill-document",
|
|
|
|
| 376 |
timeout=60,
|
| 377 |
)
|
| 378 |
if resp.status_code == 200:
|
| 379 |
+
flat = resp.json()
|
| 380 |
+
# Drop metadata keys (_missing_required, etc.) and reconstruct
|
| 381 |
+
# nested fields (e.g. personal_details.name) from the flat response.
|
| 382 |
+
fetched = {k: v for k, v in flat.items() if not k.startswith("_")}
|
| 383 |
+
for field in schema.fields:
|
| 384 |
+
if field.nested_under and field.data_key in fetched:
|
| 385 |
+
fetched.setdefault(field.nested_under, {})
|
| 386 |
+
fetched[field.nested_under][field.data_key] = fetched.pop(field.data_key)
|
| 387 |
+
push_history(doc_type, st.session_state[sk("data")])
|
| 388 |
+
_clear_widget_keys(doc_type)
|
| 389 |
+
st.session_state[sk("data")] = fetched
|
| 390 |
+
st.session_state[sk("app_id")] = app_id_input
|
| 391 |
+
st.session_state[sk("doc_url")] = None
|
| 392 |
+
st.session_state[sk("draft_content")] = ""
|
| 393 |
+
st.session_state[sk("draft_generated")] = False
|
| 394 |
+
st.session_state[sk("doc_structure")] = None
|
| 395 |
+
st.session_state[sk("chat_messages")] = []
|
| 396 |
+
st.session_state[sk("api_history")] = []
|
| 397 |
+
st.session_state[sk("session_uuid")] = str(uuid.uuid4())
|
| 398 |
st.success(f"β
Loaded data for Application ID: {app_id_input}")
|
| 399 |
st.rerun()
|
| 400 |
else:
|
|
|
|
| 412 |
|
| 413 |
st.divider()
|
| 414 |
|
| 415 |
+
if not st.session_state[sk("data")]:
|
| 416 |
+
st.info("π Enter an Application ID above to load data from the database.")
|
| 417 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
+
# ββ Editable form ββββββββββββββββββββββββββββββββββββ
|
| 420 |
+
render_doc_form(schema)
|
|
|
|
|
|
|
|
|
|
| 421 |
|
| 422 |
+
# ββ Toolbar: Undo / Redo / Generate Draft βββββββββββ
|
| 423 |
+
st.divider()
|
| 424 |
+
tb = st.columns([1, 1, 2, 4, 2])
|
| 425 |
+
with tb[0]:
|
| 426 |
+
st.button(
|
| 427 |
+
"β©οΈ Undo",
|
| 428 |
+
on_click=do_undo,
|
| 429 |
+
args=(doc_type,),
|
| 430 |
+
disabled=not st.session_state[sk("history_stack")],
|
| 431 |
+
use_container_width=True,
|
| 432 |
+
key=f"{doc_type}_undo_btn",
|
| 433 |
+
)
|
| 434 |
+
with tb[1]:
|
| 435 |
+
st.button(
|
| 436 |
+
"βͺοΈ Redo",
|
| 437 |
+
on_click=do_redo,
|
| 438 |
+
args=(doc_type,),
|
| 439 |
+
disabled=not st.session_state[sk("redo_stack")],
|
| 440 |
+
use_container_width=True,
|
| 441 |
+
key=f"{doc_type}_redo_btn",
|
| 442 |
+
)
|
| 443 |
+
with tb[2]:
|
| 444 |
+
h = len(st.session_state[sk("history_stack")])
|
| 445 |
+
st.caption(f"π {h} version{'s' if h != 1 else ''}")
|
| 446 |
+
with tb[4]:
|
| 447 |
+
draft_clicked = st.button(
|
| 448 |
+
"π Generate Draft",
|
| 449 |
+
type="primary",
|
| 450 |
+
use_container_width=True,
|
| 451 |
+
key=f"{doc_type}_gen_btn",
|
| 452 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
|
| 454 |
+
if draft_clicked:
|
| 455 |
+
with st.spinner("Generating document draft..."):
|
| 456 |
+
result, err = call_generate_draft(
|
| 457 |
+
schema,
|
| 458 |
+
st.session_state[sk("data")],
|
| 459 |
+
session_uuid=st.session_state[sk("session_uuid")],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
)
|
| 461 |
+
if err:
|
| 462 |
+
st.error(f"β Error generating draft: {err}")
|
| 463 |
+
elif result and result.get("document_content"):
|
| 464 |
+
st.session_state[sk("draft_content")] = result["document_content"]
|
| 465 |
+
st.session_state[sk("draft_generated")] = True
|
| 466 |
+
# Store field structure for future core API handover
|
| 467 |
+
st.session_state[sk("doc_structure")] = [
|
| 468 |
+
{"key": f.data_key, "label": f.label, "required": False}
|
| 469 |
+
for f in schema.fields
|
| 470 |
+
]
|
| 471 |
+
st.session_state[sk("chat_messages")] = []
|
| 472 |
+
st.session_state[sk("api_history")] = []
|
| 473 |
+
st.rerun()
|
| 474 |
+
else:
|
| 475 |
+
st.error("β Failed to generate draft.")
|
| 476 |
|
| 477 |
+
# ββ Draft preview + export βββββββββββββββββββββββββββ
|
| 478 |
+
if st.session_state[sk("draft_generated")]:
|
| 479 |
st.divider()
|
| 480 |
+
st.subheader("π Document Draft")
|
| 481 |
+
st.caption(
|
| 482 |
+
"Data values are **highlighted in bold**. "
|
| 483 |
+
"Use the chat below to revise, or expand the raw editor to edit directly."
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
# Rendered markdown preview (bold highlights are visible here)
|
| 487 |
+
with st.container(border=True):
|
| 488 |
+
st.markdown(st.session_state[sk("draft_content")])
|
| 489 |
+
|
| 490 |
+
# Collapsible raw Markdown editor for direct edits
|
| 491 |
+
with st.expander("βοΈ Edit Raw Markdown"):
|
| 492 |
+
edited_raw = st.text_area(
|
| 493 |
+
"Raw editor",
|
| 494 |
+
value=st.session_state[sk("draft_content")],
|
| 495 |
+
height=420,
|
| 496 |
+
key=f"{doc_type}_draft_editor",
|
| 497 |
+
label_visibility="collapsed",
|
| 498 |
)
|
| 499 |
+
if edited_raw != st.session_state[sk("draft_content")]:
|
| 500 |
+
st.session_state[sk("draft_content")] = edited_raw
|
| 501 |
+
st.rerun()
|
| 502 |
+
|
| 503 |
+
export_col, link_col = st.columns([2, 3])
|
| 504 |
+
with export_col:
|
| 505 |
+
export_clicked = st.button(
|
| 506 |
+
"π Export to Google Docs",
|
| 507 |
+
type="primary",
|
| 508 |
+
use_container_width=True,
|
| 509 |
+
key=f"{doc_type}_export_btn",
|
| 510 |
)
|
| 511 |
+
with link_col:
|
| 512 |
+
if st.session_state[sk("doc_url")]:
|
| 513 |
+
st.link_button(
|
| 514 |
+
"π Open Exported Doc",
|
| 515 |
+
st.session_state[sk("doc_url")],
|
| 516 |
+
use_container_width=True,
|
| 517 |
+
)
|
| 518 |
|
| 519 |
+
if export_clicked:
|
| 520 |
+
data = st.session_state[sk("data")] or {}
|
| 521 |
+
applicant_name = (data.get("personal_details") or {}).get("name") or ""
|
| 522 |
+
doc_label = schema.title
|
| 523 |
+
export_title = (
|
| 524 |
+
f"{doc_label} β {applicant_name}".strip(" β")
|
| 525 |
+
if applicant_name
|
| 526 |
+
else doc_label
|
| 527 |
+
)
|
| 528 |
+
with st.spinner("Exporting to Google Docs..."):
|
| 529 |
+
result, err = call_export_document(
|
| 530 |
+
st.session_state[sk("draft_content")],
|
| 531 |
+
title=export_title,
|
| 532 |
+
)
|
| 533 |
+
if err:
|
| 534 |
+
st.error(f"β Export failed: {err}")
|
| 535 |
+
elif result and result.get("url"):
|
| 536 |
+
st.session_state[sk("doc_url")] = result["url"]
|
| 537 |
+
st.rerun()
|
| 538 |
else:
|
| 539 |
+
st.error("β Export failed (no URL returned).")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 540 |
|
| 541 |
+
# ββ Chat ββββββββββββββββββββββββββββββββββββββββ
|
| 542 |
+
st.divider()
|
| 543 |
+
st.caption(
|
| 544 |
+
"π¬ Chat to revise the draft β "
|
| 545 |
+
"e.g. *'make the second paragraph more formal'* or *'update the passport number to A9876543'*"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 546 |
)
|
| 547 |
+
chat_c1, chat_c2 = st.columns([5, 1])
|
| 548 |
+
with chat_c1:
|
| 549 |
+
chat_text = st.text_input(
|
| 550 |
+
"Chat",
|
| 551 |
+
placeholder="Describe your revision...",
|
| 552 |
+
key=f"{doc_type}_chat_input",
|
| 553 |
+
label_visibility="collapsed",
|
| 554 |
+
)
|
| 555 |
+
with chat_c2:
|
| 556 |
+
send_btn = st.button(
|
| 557 |
+
"Send β€",
|
| 558 |
+
type="primary",
|
| 559 |
+
use_container_width=True,
|
| 560 |
+
key=f"{doc_type}_send_btn",
|
|
|
|
|
|
|
| 561 |
)
|
| 562 |
|
| 563 |
+
if send_btn and chat_text:
|
| 564 |
+
st.session_state[sk("chat_messages")].append({"role": "user", "content": chat_text})
|
| 565 |
+
st.session_state[sk("api_history")].append({"role": "user", "content": chat_text})
|
| 566 |
+
|
| 567 |
+
with st.spinner("π€ Revising document..."):
|
| 568 |
+
result, err = call_doc_chat_api(
|
| 569 |
+
chat_text,
|
| 570 |
+
st.session_state[sk("api_history")],
|
| 571 |
+
st.session_state[sk("session_uuid")],
|
| 572 |
+
current_document_content=st.session_state[sk("draft_content")],
|
| 573 |
+
structure=st.session_state[sk("doc_structure")],
|
| 574 |
+
)
|
| 575 |
+
|
| 576 |
+
if err:
|
| 577 |
+
st.session_state[sk("chat_messages")].append(
|
| 578 |
+
{"role": "assistant", "content": f"β Error: {err}"}
|
| 579 |
+
)
|
| 580 |
+
elif result:
|
| 581 |
+
answer = result.get("answer", "Document updated.")
|
| 582 |
+
st.session_state[sk("chat_messages")].append({"role": "assistant", "content": answer})
|
| 583 |
+
st.session_state[sk("api_history")].append({"role": "assistant", "content": answer})
|
| 584 |
+
if result.get("updated_document_content"):
|
| 585 |
+
st.session_state[sk("draft_content")] = result["updated_document_content"]
|
| 586 |
+
if result.get("structure") is not None:
|
| 587 |
+
st.session_state[sk("doc_structure")] = result["structure"]
|
| 588 |
+
|
| 589 |
+
st.session_state.pop(f"{doc_type}_chat_input", None)
|
| 590 |
+
st.rerun()
|
| 591 |
+
|
| 592 |
+
elif send_btn:
|
| 593 |
+
st.warning("Please type a message first.")
|
| 594 |
+
|
| 595 |
+
# ββ Chat history βββββββββββββββββββββββββββββββββ
|
| 596 |
+
for msg in st.session_state[sk("chat_messages")]:
|
| 597 |
+
with st.chat_message(msg["role"]):
|
| 598 |
+
st.markdown(msg["content"])
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 602 |
+
# PAGE ENTRY POINT
|
| 603 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 604 |
+
|
| 605 |
+
st.set_page_config(page_title="Document Generator", layout="wide")
|
| 606 |
+
st.title("π Document Generator")
|
| 607 |
+
|
| 608 |
+
# Tabs are generated from DOCUMENT_REGISTRY β add a new DocumentSchema to get a new tab
|
| 609 |
+
tab_labels = [f"{schema.icon} {schema.title}" for schema in DOCUMENT_REGISTRY.values()]
|
| 610 |
+
tabs = st.tabs(tab_labels)
|
| 611 |
+
|
| 612 |
+
for tab, (doc_type, schema) in zip(tabs, DOCUMENT_REGISTRY.items()):
|
| 613 |
+
with tab:
|
| 614 |
+
render_document_tab(schema)
|