mfallahian commited on
Commit
65718bf
·
1 Parent(s): b4134c6

initial commit

Browse files
Files changed (3) hide show
  1. .gitignore +173 -0
  2. app.py +138 -0
  3. config.py +78 -0
.gitignore ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ #uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+
110
+ # pdm
111
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
112
+ #pdm.lock
113
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
114
+ # in version control.
115
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
116
+ .pdm.toml
117
+ .pdm-python
118
+ .pdm-build/
119
+
120
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
121
+ __pypackages__/
122
+
123
+ # Celery stuff
124
+ celerybeat-schedule
125
+ celerybeat.pid
126
+
127
+ # SageMath parsed files
128
+ *.sage.py
129
+
130
+ # Environments
131
+ .env
132
+ .venv
133
+ env/
134
+ venv/
135
+ ENV/
136
+ env.bak/
137
+ venv.bak/
138
+
139
+ # Spyder project settings
140
+ .spyderproject
141
+ .spyproject
142
+
143
+ # Rope project settings
144
+ .ropeproject
145
+
146
+ # mkdocs documentation
147
+ /site
148
+
149
+ # mypy
150
+ .mypy_cache/
151
+ .dmypy.json
152
+ dmypy.json
153
+
154
+ # Pyre type checker
155
+ .pyre/
156
+
157
+ # pytype static type analyzer
158
+ .pytype/
159
+
160
+ # Cython debug symbols
161
+ cython_debug/
162
+
163
+ # PyCharm
164
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
165
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
166
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
167
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
168
+ .idea/
169
+
170
+ # PyPI configuration file
171
+ .pypirc
172
+
173
+ .DS_Store
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ from enum import Enum
3
+ from typing import Iterator
4
+ from langchain_core.output_parsers import PydanticOutputParser
5
+ from langchain_core.prompts import ChatPromptTemplate
6
+ from langchain_openai import ChatOpenAI
7
+ from pydantic import BaseModel, Field
8
+ from config import SYSTEM_PROMPT
9
+ import json
10
+ import time
11
+
12
+
13
+ class Eligibility(str, Enum):
14
+ ELIGIBLE = "Eligible"
15
+ INELIGIBLE = "Ineligible"
16
+ RESUBMIT = "Re-submit"
17
+
18
+
19
+ # class Response(BaseModel):
20
+ # eligibility: Eligibility = Field(description="The status of eligibility One of: 'Eligible', 'Ineligible', 'Re-submit'.")
21
+ # justification: str = Field(
22
+ # description="A detailed, itemized, and numbered Markdown list of all findings that support the eligibility status. For 'Ineligible', list all violations. For 'Re-submit', list all points of uncertainty. For 'Eligible', state that no violations were found and note any movable items observed."
23
+ # )
24
+ # instruction: str = Field(
25
+ # description="A clear, actionable, and numbered Markdown list of steps the homeowner must take. Each instruction must directly correspond to a finding in the 'justification' field. For 'Eligible' status, this provides a confirmation and reminders for movable items."
26
+ # )
27
+
28
+ class Response(BaseModel):
29
+ """
30
+ Schema for the AI Inspector’s output.
31
+
32
+ • eligibility – Overall result.
33
+ • justification – Numbered Markdown list explaining that result.
34
+ • instruction – Numbered Markdown list of next steps that map
35
+ one-to-one to the justification list.
36
+ """
37
+
38
+ eligibility: Eligibility = Field(
39
+ ...,
40
+ description=(
41
+ "Overall inspection outcome.\n\n"
42
+ " • 'Eligible' – No violations observed in visible areas.\n"
43
+ " • 'Ineligible' – ≥1 confirmed violation detected.\n"
44
+ " • 'Re-submit' – No clear violations, but ≥1 point of "
45
+ "uncertainty prevents a confident decision."
46
+ ),
47
+ )
48
+
49
+ justification: str = Field(
50
+ ...,
51
+ description=(
52
+ "A *Markdown* numbered list detailing findings that back up "
53
+ "the chosen eligibility value.\n\n"
54
+ "Formatting rules:\n"
55
+ " • Each item starts with '1.', '2.', …\n"
56
+ " • For 'Eligible': a single sentence stating no violations "
57
+ " plus any movable combustibles noted.\n"
58
+ " • For 'Ineligible': each item describes one specific, "
59
+ " observable violation.\n"
60
+ " • For 'Re-submit': each item describes one uncertainty "
61
+ " that must be resolved (e.g., blurry photo, hidden area)."
62
+ ),
63
+ min_length=1,
64
+ )
65
+
66
+ instruction: str = Field(
67
+ ...,
68
+ description=(
69
+ "A *Markdown* numbered list of homeowner actions that map "
70
+ "directly, in order, to the items in 'justification'.\n\n"
71
+ " • For 'Eligible': give a short confirmation plus reminders "
72
+ " to relocate any listed movable items during Red Flag "
73
+ " Warnings or extended absences.\n"
74
+ " • For 'Ineligible': give a clear, actionable fix for each "
75
+ " violation.\n"
76
+ " • For 'Re-submit': specify exactly what the homeowner must "
77
+ " provide or clarify (e.g., new close-up photo, daylight "
78
+ " image, measurement)."
79
+ ),
80
+ min_length=1,
81
+ )
82
+
83
+ class LLMHandler:
84
+ def __init__(self, model_name="gpt-4.1-2025-04-14", temperature=0.3):
85
+ self.llm = ChatOpenAI(model=model_name, temperature=temperature, streaming=True)
86
+ self.parser = PydanticOutputParser(pydantic_object=Response)
87
+ self.prompt = ChatPromptTemplate.from_messages(
88
+ [
89
+ ("system", SYSTEM_PROMPT),
90
+ ("user", [
91
+ {
92
+ "type": "image_url",
93
+ "image_url": "data:image/jpeg;base64,{image_data}"
94
+ }
95
+ ])
96
+ ]
97
+ ).partial(format_instructions=self.parser.get_format_instructions())
98
+ self.chain = self.prompt | self.llm
99
+
100
+ def process_image(self, image_path: str) -> Iterator[str]:
101
+ with open(image_path, "rb") as img_file:
102
+ image_data = base64.b64encode(img_file.read()).decode("utf-8")
103
+
104
+ response = self.chain.invoke(
105
+ {
106
+ "image_data": image_data,
107
+ "image_mime_type": "image/jpeg",
108
+ "cache_type": "ephemeral",
109
+ }
110
+ )
111
+ return response.text()
112
+
113
+ import gradio as gr
114
+
115
+ llm_handler = LLMHandler()
116
+
117
+
118
+ def process_and_display(image):
119
+ if image is None:
120
+ return "Please upload an image."
121
+
122
+ image_path = image
123
+
124
+ llm_output = json.loads(llm_handler.process_image(image_path))
125
+
126
+ return llm_output["justification"], llm_output["instruction"]
127
+
128
+ demo = gr.Interface(
129
+ fn=process_and_display,
130
+ inputs=gr.Image(type="filepath", label="Upload Photo", height=500),
131
+ outputs=[gr.Textbox(label="Inspection Result", info="The list of potential violations", lines=8),
132
+ gr.Textbox(label="LLM Response", info="The instruction for how to fix the potential violations or what new evidence to provide." , lines=8)],
133
+ title="Wildfire Prepared Home Eligibility Inspector",
134
+ description="Upload a photo of all four sides of their home (one by one), showcasing the 0- to 5-foot noncombustible zone.",
135
+ flagging_mode="never",
136
+ )
137
+
138
+ demo.launch()
config.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SYSTEM_PROMPT = """
2
+ You are **Wildfire Prepared Home’s virtual pre-inspection consultant**.
3
+ Your job is to study homeowner-supplied photos and decide whether the
4
+ **0–5 ft non-combustible zone** around the house passes, fails, or
5
+ needs clarification.
6
+
7
+ --------------------------------------------------------------------------
8
+ 📋 1. Program Goal
9
+ --------------------------------------------------------------------------
10
+ Create and maintain a continuous 5-foot buffer of **non-combustible
11
+ material** (rock, gravel, concrete, bare mineral soil, etc.) around
12
+ every exterior wall of the building.
13
+
14
+ --------------------------------------------------------------------------
15
+ 🔍 2. Your Inspection Workflow
16
+ --------------------------------------------------------------------------
17
+ 1. **Map the Zone** – Visually estimate the area that lies ≤ 5 ft from
18
+ the home’s foundation in every direction.
19
+ 2. **Detect Findings** – List **every** violation *or* uncertainty you
20
+ observe **in that zone**.
21
+ • Include items that overhang the zone (e.g., tree limbs).
22
+ • Group identical issues only when they share the same remedy.
23
+ 3. **Recommend Actions** – For each finding, give one clear,
24
+ homeowner-friendly step that fixes or clarifies the issue.
25
+
26
+ --------------------------------------------------------------------------
27
+ 🛑 3. Detailed Pass/Fail Rules & Examples
28
+ --------------------------------------------------------------------------
29
+ • **Vegetation** – 100 % removed to bare soil.
30
+ ✗ Dry lawn touching siding ✗ Flower bed against wall ✗ Pine-needle layer
31
+
32
+ • **Trees** – No trunk, limb, or branch may be inside or overhanging the
33
+ zone.
34
+ ✗ Trunk 3 ft from wall ✗ Branch extends over eaves
35
+
36
+ • **Ground-cover** – Only non-combustible material allowed.
37
+ ✗ Wood/rubber mulch ✗ Pine straw ✓ Gravel, rock, pavers, concrete
38
+
39
+ • **Fences / Retaining Walls** – Combustible portions must be outside
40
+ the 5-ft zone.
41
+ ✗ Wood fence attached to house ✗ Timber retaining wall
42
+
43
+ • **Stored Combustibles** – Remove everything that can burn.
44
+ ✗ Firewood, lumber, cardboard, plastic bins, wicker furniture, etc.
45
+
46
+ --------------------------------------------------------------------------
47
+ 📤 4. How to Write Your Response (JSON)
48
+ --------------------------------------------------------------------------
49
+ Return **one** JSON object with the keys **eligibility, justification,
50
+ instruction**.
51
+
52
+ 1. **Eligibility** – one of `"Eligible"`, `"Ineligible"`, `"Re-submit"`.
53
+ 2. **Justification** – a **Markdown numbered list** (`"1. …"`)
54
+ * `Eligible` ➜ “No violations observed …” and list any movable
55
+ combustibles seen (e.g., “propane BBQ grill on patio”).
56
+ * `Ineligible` ➜ Each list item = one specific violation.
57
+ * `Re-submit` ➜ Each list item = one uncertainty that blocks a
58
+ decision (e.g., “Photo too dark to confirm mulch type at
59
+ entry-walk”).
60
+ 3. **Instruction** – a **Markdown numbered list** mirroring the order of
61
+ `justification`. Each item tells the homeowner exactly how to fix the
62
+ violation **or** what new evidence to provide.
63
+
64
+ --------------------------------------------------------------------------
65
+ 💡 5. Eligibility Logic Cheat-Sheet
66
+ --------------------------------------------------------------------------
67
+ • **Eligible** → No violations seen.
68
+ • **Ineligible** → ≥ 1 confirmed violation.
69
+ • **Re-submit** → 0 confirmed violations **and** ≥ 1 uncertainty that
70
+ prevents a confident pass.
71
+
72
+ --------------------------------------------------------------------------
73
+ 📦 6. Output Schema (do not include this comment block in JSON)
74
+ --------------------------------------------------------------------------
75
+ {format_instructions}
76
+
77
+ --------------------------------------------------------------------------
78
+ """