chrissoria Claude Opus 4.6 commited on
Commit
222a058
·
1 Parent(s): 55bc794

Replace classifier app with unified CatLLM app

Browse files

Unified app supporting all 7 domains (General, Survey, Social Media,
Academic, Policy, Web, Cognitive) and 5 functions (Classify, Extract,
Explore, Summarize, CERAD Score). Free tier with Qwen 2.5 72B.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

README.md CHANGED
@@ -1,5 +1,5 @@
1
  ---
2
- title: CatLLM - Survey Response Classifier
3
  emoji: 🐱
4
  colorFrom: yellow
5
  colorTo: yellow
@@ -8,36 +8,30 @@ sdk_version: "1.32.0"
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
- short_description: Classify survey responses using LLMs
12
  ---
13
 
14
- # CatLLM - Survey Response Classifier
15
 
16
- A web interface for the [catllm](https://github.com/chrissoria/cat-llm) Python package. Classify survey responses into custom categories using various LLM providers.
17
 
18
- ## How to Use
19
-
20
- 1. **Upload Your Data**: Upload a CSV or Excel file containing survey responses
21
- 2. **Select Column**: Choose the column containing the text responses to classify
22
- 3. **Define Categories**: Enter your classification categories (e.g., "Positive", "Negative", "Neutral")
23
- 4. **Choose a Model**: Select your preferred LLM (free models available!)
24
- 5. **Click Classify**: View and download results with category assignments
25
 
26
- ## Supported Models
 
 
 
 
 
 
27
 
28
- | Provider | Models |
29
- |----------|--------|
30
- | **OpenAI** | gpt-4o, gpt-4o-mini |
31
- | **Anthropic** | claude-3-5-sonnet, claude-3-haiku |
32
- | **Google** | gemini-1.5-pro, gemini-1.5-flash |
33
- | **Mistral** | mistral-large-latest |
34
-
35
- ## Privacy
36
 
37
- Your API key is **never stored**. It is only used for the current classification request and is not logged or saved.
 
 
 
38
 
39
- ## Learn More
40
 
41
- - [catllm on PyPI](https://pypi.org/project/cat-llm/)
42
- - [GitHub Repository](https://github.com/chrissoria/cat-llm)
43
- - [Documentation](https://github.com/chrissoria/cat-llm#readme)
 
1
  ---
2
+ title: CatLLM
3
  emoji: 🐱
4
  colorFrom: yellow
5
  colorTo: yellow
 
8
  app_file: app.py
9
  pinned: false
10
  license: mit
11
+ short_description: LLM-powered classification, extraction, and summarization
12
  ---
13
 
14
+ # CatLLM
15
 
16
+ A unified web interface for the [catllm](https://github.com/chrissoria/cat-llm) ecosystem. Classify, extract categories, explore, and summarize text across 7 domains using LLMs.
17
 
18
+ ## Domains
 
 
 
 
 
 
19
 
20
+ - **General** — domain-neutral text analysis
21
+ - **Survey** — survey response classification
22
+ - **Social Media** — Threads, Bluesky, Reddit, Mastodon, YouTube
23
+ - **Academic** — OpenAlex paper analysis
24
+ - **Policy** — legislative/policy document classification
25
+ - **Web** — URL content classification
26
+ - **Cognitive** — CERAD drawing scoring
27
 
28
+ ## How to Use
 
 
 
 
 
 
 
29
 
30
+ 1. Select a **Domain** and **Function** in the sidebar
31
+ 2. Upload data or use the example dataset
32
+ 3. Configure options and select a model
33
+ 4. Click the action button and view results
34
 
35
+ ## Links
36
 
37
+ - [PyPI](https://pypi.org/project/cat-llm/) | [GitHub](https://github.com/chrissoria/cat-llm)
 
 
__pycache__/app.cpython-311.pyc DELETED
Binary file (92.5 kB)
 
app.py CHANGED
The diff for this file is too large to render. See raw diff
 
assets/example_data.csv ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Response
2
+ The weather was just too hot where I lived
3
+ I could no longer afford the rent in my old neighborhood
4
+ My company offered me a promotion but it required relocating
5
+ I wanted to be closer to my aging parents
6
+ The schools in my area were not good enough for my kids
7
+ I got accepted into graduate school across the country
8
+ My apartment had a terrible mold problem that the landlord refused to fix
9
+ I went through a divorce and needed a fresh start
10
+ The crime rate in my neighborhood kept getting worse
11
+ I was tired of the long commute to work every day
12
+ I fell in love with someone who lived in another city
13
+ The cost of living was much lower in the new area
14
+ I needed a bigger house because we were expecting twins
15
+ My doctor recommended a drier climate for my health
16
+ I got laid off and found a new job in a different state
17
+ I wanted to live somewhere with better outdoor recreation
18
+ My lease ended and my landlord decided to sell the building
19
+ I retired and wanted to move somewhere warmer
20
+ The noise from the construction next door was unbearable
21
+ I always dreamed of living near the ocean
assets/logo.png ADDED
components/__init__.py ADDED
File without changes
components/code_generation.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generate reproducible Python code snippets for each task type and domain.
3
+ """
4
+
5
+ # Map domain id -> (import statement, function prefix)
6
+ DOMAIN_IMPORTS = {
7
+ "general": ("import catllm", "catllm"),
8
+ "survey": ("import catllm", "catllm"),
9
+ "social_media": ("import catllm", "catllm"),
10
+ "academic": ("import catllm", "catllm"),
11
+ "policy": ("import catllm", "catllm"),
12
+ "web": ("import catllm", "catllm"),
13
+ "cognitive": ("import catllm", "catllm"),
14
+ }
15
+
16
+ # Map (domain, function) -> function name suffix
17
+ DOMAIN_FUNCTION_NAMES = {
18
+ ("general", "classify"): "classify",
19
+ ("general", "extract"): "extract",
20
+ ("general", "explore"): "explore",
21
+ ("general", "summarize"): "summarize",
22
+ ("survey", "classify"): "classify_survey",
23
+ ("survey", "extract"): "extract_survey",
24
+ ("survey", "explore"): "explore_survey",
25
+ ("survey", "summarize"): "summarize_survey",
26
+ ("social_media", "classify"): "classify_social",
27
+ ("social_media", "extract"): "extract_social",
28
+ ("social_media", "explore"): "explore_social",
29
+ ("academic", "classify"): "classify_academic",
30
+ ("academic", "extract"): "extract_academic",
31
+ ("academic", "explore"): "explore_academic",
32
+ ("academic", "summarize"): "summarize_academic",
33
+ ("policy", "classify"): "classify_policy",
34
+ ("policy", "extract"): "extract_policy",
35
+ ("policy", "explore"): "explore_policy",
36
+ ("policy", "summarize"): "summarize_policy",
37
+ ("web", "classify"): "classify_web",
38
+ ("web", "extract"): "extract_web",
39
+ ("web", "explore"): "explore_web",
40
+ ("web", "summarize"): "summarize_web",
41
+ ("cognitive", "cerad_score"): "cerad_drawn_score",
42
+ }
43
+
44
+
45
+ def _get_fn_call(domain, function):
46
+ """Get the full function call string, e.g. 'catllm.classify_survey'."""
47
+ imp, prefix = DOMAIN_IMPORTS.get(domain, ("import catllm", "catllm"))
48
+ fn_name = DOMAIN_FUNCTION_NAMES.get((domain, function), function)
49
+ return imp, f"{prefix}.{fn_name}"
50
+
51
+
52
+ def generate_classify_code(
53
+ domain, input_type, description, categories, model, model_source,
54
+ mode=None, classify_mode="Single Model", models_list=None,
55
+ consensus_threshold=0.5, model_temperatures=None, ensemble_runs=None,
56
+ domain_kwargs=None,
57
+ ):
58
+ """Generate classification code."""
59
+ imp, fn_call = _get_fn_call(domain, "classify")
60
+ categories_str = ",\n ".join([f'"{cat}"' for cat in categories])
61
+
62
+ if input_type == "text":
63
+ input_placeholder = 'df["your_column"].tolist()'
64
+ load_data = 'import pandas as pd\n\ndf = pd.read_csv("your_data.csv")\n'
65
+ elif input_type == "pdf":
66
+ input_placeholder = '"path/to/your/pdfs/"'
67
+ load_data = ""
68
+ else:
69
+ input_placeholder = '"path/to/your/images/"'
70
+ load_data = ""
71
+
72
+ # Domain-specific kwargs
73
+ extra_params = ""
74
+ if domain_kwargs:
75
+ for k, v in domain_kwargs.items():
76
+ if v is not None and v != "":
77
+ if isinstance(v, str):
78
+ extra_params += f',\n {k}="{v}"'
79
+ else:
80
+ extra_params += f",\n {k}={v}"
81
+
82
+ if classify_mode == "Single Model":
83
+ mode_param = f',\n mode="{mode}"' if mode and input_type == "pdf" else ""
84
+ return f"""{imp}
85
+ {load_data}
86
+ categories = [
87
+ {categories_str}
88
+ ]
89
+
90
+ result = {fn_call}(
91
+ input_data={input_placeholder},
92
+ categories=categories,
93
+ api_key="YOUR_API_KEY",
94
+ description="{description}",
95
+ user_model="{model}"{mode_param}{extra_params}
96
+ )
97
+
98
+ result.to_csv("classified_results.csv", index=False)
99
+ """
100
+ else:
101
+ # Multi-model
102
+ if ensemble_runs:
103
+ model_lines = [f'("{m}", "auto", "YOUR_API_KEY", {{"creativity": {t}}})' for m, t in ensemble_runs]
104
+ elif models_list:
105
+ model_lines = []
106
+ for m in models_list:
107
+ temp = (model_temperatures or {}).get(m)
108
+ if temp is not None:
109
+ model_lines.append(f'("{m}", "auto", "YOUR_API_KEY", {{"creativity": {temp}}})')
110
+ else:
111
+ model_lines.append(f'("{m}", "auto", "YOUR_API_KEY")')
112
+ else:
113
+ model_lines = ['"gpt-4o", "auto", "YOUR_API_KEY"']
114
+
115
+ models_str = ",\n ".join(model_lines)
116
+ mode_param = f',\n mode="{mode}"' if mode and input_type == "pdf" else ""
117
+ threshold_str = "majority" if consensus_threshold == 0.5 else "two-thirds" if consensus_threshold == 0.67 else "unanimous"
118
+ consensus_param = f',\n consensus_threshold="{threshold_str}"' if classify_mode == "Ensemble" else ""
119
+
120
+ return f"""{imp}
121
+ {load_data}
122
+ categories = [
123
+ {categories_str}
124
+ ]
125
+
126
+ models = [
127
+ {models_str}
128
+ ]
129
+
130
+ result = {fn_call}(
131
+ input_data={input_placeholder},
132
+ categories=categories,
133
+ models=models,
134
+ description="{description}"{mode_param}{consensus_param}{extra_params}
135
+ )
136
+
137
+ result.to_csv("classified_results.csv", index=False)
138
+ """
139
+
140
+
141
+ def generate_extract_code(domain, input_type, description, model, model_source, max_categories, mode=None, domain_kwargs=None):
142
+ """Generate extraction code."""
143
+ imp, fn_call = _get_fn_call(domain, "extract")
144
+
145
+ if input_type == "text":
146
+ input_placeholder = 'df["your_column"].tolist()'
147
+ load_data = 'import pandas as pd\n\ndf = pd.read_csv("your_data.csv")\n'
148
+ elif input_type == "pdf":
149
+ input_placeholder = '"path/to/your/pdfs/"'
150
+ load_data = ""
151
+ else:
152
+ input_placeholder = '"path/to/your/images/"'
153
+ load_data = ""
154
+
155
+ mode_param = f',\n mode="{mode}"' if mode else ""
156
+ extra_params = ""
157
+ if domain_kwargs:
158
+ for k, v in domain_kwargs.items():
159
+ if v is not None and v != "":
160
+ extra_params += f',\n {k}="{v}"' if isinstance(v, str) else f",\n {k}={v}"
161
+
162
+ return f"""{imp}
163
+ {load_data}
164
+ result = {fn_call}(
165
+ input_data={input_placeholder},
166
+ api_key="YOUR_API_KEY",
167
+ description="{description}",
168
+ user_model="{model}",
169
+ model_source="{model_source}",
170
+ max_categories={max_categories}{mode_param}{extra_params}
171
+ )
172
+
173
+ print(result["top_categories"])
174
+ """
175
+
176
+
177
+ def generate_summarize_code(domain, input_type, description, model, model_source, focus=None, max_length=None, instructions=None, mode=None, domain_kwargs=None):
178
+ """Generate summarization code."""
179
+ imp, fn_call = _get_fn_call(domain, "summarize")
180
+
181
+ focus_param = f',\n focus="{focus}"' if focus else ""
182
+ length_param = f",\n max_length={max_length}" if max_length else ""
183
+ instructions_param = f',\n instructions="{instructions}"' if instructions else ""
184
+
185
+ extra_params = ""
186
+ if domain_kwargs:
187
+ for k, v in domain_kwargs.items():
188
+ if v is not None and v != "":
189
+ extra_params += f',\n {k}="{v}"' if isinstance(v, str) else f",\n {k}={v}"
190
+
191
+ if input_type == "text":
192
+ input_placeholder = 'df["your_column"].tolist()'
193
+ load_data = 'import pandas as pd\n\ndf = pd.read_csv("your_data.csv")\n'
194
+ else:
195
+ input_placeholder = '"path/to/your/pdfs/"'
196
+ load_data = ""
197
+
198
+ mode_param = f',\n mode="{mode}"' if mode else ""
199
+
200
+ return f"""{imp}
201
+ {load_data}
202
+ result = {fn_call}(
203
+ input_data={input_placeholder},
204
+ api_key="YOUR_API_KEY",
205
+ description="{description}",
206
+ user_model="{model}",
207
+ model_source="{model_source}"{mode_param}{focus_param}{length_param}{instructions_param}{extra_params}
208
+ )
209
+
210
+ result.to_csv("summarized_results.csv", index=False)
211
+ """
components/css.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CatLLM brand CSS theme.
3
+ """
4
+
5
+ import streamlit as st
6
+
7
+
8
+ def inject_css():
9
+ """Inject the CatLLM CSS theme into the page."""
10
+ st.markdown(CSS, unsafe_allow_html=True)
11
+
12
+
13
+ CSS = """
14
+ <style>
15
+ /* Import Garamond font and apply globally */
16
+ @import url('https://fonts.googleapis.com/css2?family=EB+Garamond:wght@400;500;600;700&display=swap');
17
+
18
+ *:not([class*="icon"]):not([data-testid="stIconMaterial"]):not(svg):not(path) {
19
+ font-family: 'EB Garamond', Garamond, Georgia, serif !important;
20
+ font-size: 17px !important;
21
+ }
22
+
23
+ /* Preserve Streamlit icon fonts */
24
+ [data-testid="stIconMaterial"], .material-icons, .material-symbols-rounded {
25
+ font-family: 'Material Symbols Rounded', 'Material Icons' !important;
26
+ font-size: 24px !important;
27
+ }
28
+
29
+ /* Main container styling */
30
+ .main .block-container {
31
+ padding-top: 2rem;
32
+ padding-bottom: 2rem;
33
+ }
34
+
35
+ /* Headers with gradient accent */
36
+ h1 {
37
+ background: linear-gradient(90deg, #E8A33C 0%, #D4872C 100%);
38
+ -webkit-background-clip: text;
39
+ -webkit-text-fill-color: transparent;
40
+ background-clip: text;
41
+ font-weight: 700;
42
+ }
43
+
44
+ /* Card-like sections */
45
+ .stExpander {
46
+ border: 1px solid #E8D5B5;
47
+ border-radius: 12px;
48
+ box-shadow: 0 2px 8px rgba(232, 163, 60, 0.08);
49
+ }
50
+
51
+ /* File uploader styling */
52
+ .stFileUploader {
53
+ border-radius: 12px;
54
+ }
55
+
56
+ .stFileUploader > div > div {
57
+ border: 2px dashed #E8A33C;
58
+ border-radius: 12px;
59
+ background: linear-gradient(135deg, #FEFCF9 0%, #F5EFE6 100%);
60
+ }
61
+
62
+ /* Button styling */
63
+ .stButton > button {
64
+ border-radius: 8px;
65
+ font-weight: 600;
66
+ transition: all 0.2s ease;
67
+ border: 2px solid #E8A33C;
68
+ background: #FEFCF9;
69
+ color: #D4872C;
70
+ }
71
+
72
+ /* Tall button for example dataset (matches file uploader height) */
73
+ .tall-button .stButton > button {
74
+ min-height: 107px;
75
+ border-radius: 12px;
76
+ }
77
+
78
+ .stButton > button:hover {
79
+ transform: translateY(-1px);
80
+ box-shadow: 0 4px 12px rgba(232, 163, 60, 0.3);
81
+ background: #F5EFE6;
82
+ }
83
+
84
+ /* Primary button */
85
+ .stButton > button[kind="primary"] {
86
+ background: linear-gradient(135deg, #E8A33C 0%, #D4872C 100%);
87
+ border: none;
88
+ color: white;
89
+ }
90
+
91
+ /* Success/info messages */
92
+ .stSuccess {
93
+ background-color: #E8F5E9;
94
+ border-left: 4px solid #4CAF50;
95
+ border-radius: 0 8px 8px 0;
96
+ }
97
+
98
+ .stInfo {
99
+ background-color: #FFF8E8;
100
+ border-left: 4px solid #E8A33C;
101
+ border-radius: 0 8px 8px 0;
102
+ }
103
+
104
+ /* Radio buttons */
105
+ .stRadio > div {
106
+ gap: 0.5rem;
107
+ display: flex;
108
+ width: 100%;
109
+ }
110
+
111
+ .stRadio > div > label {
112
+ background: #F5EFE6;
113
+ padding: 0.5rem 1rem;
114
+ border-radius: 20px;
115
+ border: 1px solid transparent;
116
+ transition: all 0.2s ease;
117
+ flex: 1;
118
+ text-align: center;
119
+ justify-content: center;
120
+ }
121
+
122
+ .stRadio > div > label:hover {
123
+ border-color: #E8A33C;
124
+ }
125
+
126
+ /* Text inputs */
127
+ .stTextInput > div > div > input {
128
+ border-radius: 8px;
129
+ border: 1px solid #E8D5B5;
130
+ }
131
+
132
+ .stTextInput > div > div > input:focus {
133
+ border-color: #E8A33C;
134
+ box-shadow: 0 0 0 2px rgba(232, 163, 60, 0.2);
135
+ }
136
+
137
+ /* Select boxes */
138
+ .stSelectbox > div > div {
139
+ border-radius: 8px;
140
+ }
141
+
142
+ /* Dataframe styling */
143
+ .stDataFrame {
144
+ border-radius: 12px;
145
+ overflow: hidden;
146
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
147
+ }
148
+
149
+ /* Progress bar */
150
+ .stProgress > div > div {
151
+ background: linear-gradient(90deg, #E8A33C 0%, #D4872C 100%);
152
+ border-radius: 10px;
153
+ }
154
+
155
+ /* Slider */
156
+ .stSlider > div > div > div {
157
+ background: #E8A33C;
158
+ }
159
+
160
+ /* Divider */
161
+ hr {
162
+ border: none;
163
+ height: 1px;
164
+ background: linear-gradient(90deg, transparent, #E8D5B5, transparent);
165
+ margin: 1.5rem 0;
166
+ }
167
+
168
+ /* Code blocks */
169
+ .stCodeBlock {
170
+ border-radius: 12px;
171
+ border: 1px solid #E8D5B5;
172
+ }
173
+
174
+ /* Metric cards */
175
+ .stMetric {
176
+ background: linear-gradient(135deg, #FEFCF9 0%, #F5EFE6 100%);
177
+ padding: 1rem;
178
+ border-radius: 12px;
179
+ border: 1px solid #E8D5B5;
180
+ }
181
+
182
+ /* Download buttons */
183
+ .stDownloadButton > button {
184
+ background: #F5EFE6;
185
+ border: 1px solid #E8A33C;
186
+ color: #D4872C;
187
+ }
188
+
189
+ .stDownloadButton > button:hover {
190
+ background: #E8A33C;
191
+ color: white;
192
+ }
193
+
194
+ /* Multiselect */
195
+ .stMultiSelect > div > div {
196
+ border-radius: 8px;
197
+ }
198
+
199
+ /* Status indicator */
200
+ .stStatus {
201
+ border-radius: 12px;
202
+ }
203
+
204
+ /* Column gaps */
205
+ [data-testid="column"] {
206
+ padding: 0 0.5rem;
207
+ }
208
+
209
+ /* Logo and title alignment */
210
+ [data-testid="column"]:first-child img {
211
+ border-radius: 8px;
212
+ }
213
+
214
+ /* Sidebar styling */
215
+ [data-testid="stSidebar"] {
216
+ background: linear-gradient(180deg, #FEFCF9 0%, #F5EFE6 100%);
217
+ }
218
+
219
+ [data-testid="stSidebar"] .stSelectbox label,
220
+ [data-testid="stSidebar"] .stRadio label {
221
+ font-weight: 600;
222
+ }
223
+ </style>
224
+ """
components/file_upload.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ File upload panels for CSV/Excel, PDF, and image inputs.
3
+ """
4
+
5
+ import os
6
+ import tempfile
7
+ import pandas as pd
8
+ import streamlit as st
9
+
10
+
11
+ def count_pdf_pages(pdf_path):
12
+ """Count the number of pages in a PDF file."""
13
+ try:
14
+ import fitz
15
+ doc = fitz.open(pdf_path)
16
+ page_count = len(doc)
17
+ doc.close()
18
+ return page_count
19
+ except Exception:
20
+ return 1
21
+
22
+
23
+ def extract_text_from_pdfs(pdf_paths):
24
+ """Extract text from all pages of all PDFs."""
25
+ import fitz
26
+ all_texts = []
27
+ for pdf_path in pdf_paths:
28
+ try:
29
+ doc = fitz.open(pdf_path)
30
+ for page in doc:
31
+ text = page.get_text().strip()
32
+ if text:
33
+ all_texts.append(text)
34
+ doc.close()
35
+ except Exception as e:
36
+ print(f"Error extracting text from {pdf_path}: {e}")
37
+ return all_texts
38
+
39
+
40
+ def extract_pdf_pages(pdf_paths, pdf_name_map, mode="image"):
41
+ """Extract individual pages from PDFs as images or text."""
42
+ import fitz
43
+ pages = []
44
+ for pdf_path in pdf_paths:
45
+ orig_name = pdf_name_map.get(pdf_path, os.path.basename(pdf_path).replace(".pdf", ""))
46
+ try:
47
+ doc = fitz.open(pdf_path)
48
+ for page_num, page in enumerate(doc, 1):
49
+ page_label = f"{orig_name}_p{page_num}"
50
+ if mode == "text":
51
+ text = page.get_text().strip()
52
+ if text:
53
+ pages.append((text, page_label, "text"))
54
+ else:
55
+ pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
56
+ img_path = tempfile.NamedTemporaryFile(delete=False, suffix=".png").name
57
+ pix.save(img_path)
58
+ if mode == "both":
59
+ text = page.get_text().strip()
60
+ pages.append((img_path, page_label, "image", text))
61
+ else:
62
+ pages.append((img_path, page_label, "image"))
63
+ doc.close()
64
+ except Exception as e:
65
+ print(f"Error extracting pages from {pdf_path}: {e}")
66
+ return pages
67
+
68
+
69
+ PDF_MODE_OPTIONS = ["Image (visual documents)", "Text (text-heavy)", "Both (comprehensive)"]
70
+ PDF_MODE_MAP = {
71
+ "Image (visual documents)": "image",
72
+ "Text (text-heavy)": "text",
73
+ "Both (comprehensive)": "both",
74
+ }
75
+
76
+
77
+ def render_csv_upload(key_prefix=""):
78
+ """Render CSV/Excel file upload panel.
79
+
80
+ Returns:
81
+ (input_data, description, original_filename, df) or (None, None, None, None).
82
+ """
83
+ upload_col, example_col = st.columns([3, 1])
84
+ with upload_col:
85
+ uploaded_file = st.file_uploader(
86
+ "Upload Data (CSV or Excel)",
87
+ type=["csv", "xlsx", "xls"],
88
+ key=f"{key_prefix}survey_file",
89
+ )
90
+ with example_col:
91
+ st.markdown("<div style='height: 27px;'></div>", unsafe_allow_html=True)
92
+ st.markdown('<div class="tall-button">', unsafe_allow_html=True)
93
+ if st.button("Try Example Dataset", key=f"{key_prefix}example_btn", use_container_width=True):
94
+ st.session_state.example_loaded = True
95
+ st.markdown("</div>", unsafe_allow_html=True)
96
+
97
+ columns = []
98
+ df = None
99
+ if uploaded_file is not None:
100
+ try:
101
+ if uploaded_file.name.endswith(".csv"):
102
+ df = pd.read_csv(uploaded_file)
103
+ else:
104
+ df = pd.read_excel(uploaded_file)
105
+ columns = df.columns.tolist()
106
+ st.success(f"Loaded {len(df):,} rows")
107
+ except Exception as e:
108
+ st.error(f"Error loading file: {e}")
109
+ elif st.session_state.get("example_loaded"):
110
+ try:
111
+ example_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "assets", "example_data.csv")
112
+ df = pd.read_csv(example_path)
113
+ columns = df.columns.tolist()
114
+ st.success(f"Loaded example dataset ({len(df)} rows)")
115
+ except Exception:
116
+ pass
117
+
118
+ selected_column = st.selectbox(
119
+ "Column to Process",
120
+ options=columns if columns else ["Upload a file first"],
121
+ disabled=not columns,
122
+ key=f"{key_prefix}survey_column",
123
+ )
124
+
125
+ description = selected_column if columns else ""
126
+ original_filename = uploaded_file.name if uploaded_file else "example_data.csv"
127
+
128
+ if df is not None and columns and selected_column in columns:
129
+ return df[selected_column].tolist(), description, original_filename, df
130
+
131
+ return None, description, original_filename, df
132
+
133
+
134
+ def render_pdf_upload(key_prefix=""):
135
+ """Render PDF upload panel.
136
+
137
+ Returns:
138
+ (input_data, description, original_filename, pdf_mode) or (None, ..., ..., ...).
139
+ """
140
+ pdf_files = st.file_uploader(
141
+ "Upload PDF Document(s)",
142
+ type=["pdf"],
143
+ accept_multiple_files=True,
144
+ key=f"{key_prefix}pdf_files",
145
+ )
146
+
147
+ pdf_description = st.text_input(
148
+ "Document Description",
149
+ placeholder="e.g., 'research papers', 'interview transcripts'",
150
+ help="Helps the LLM understand context",
151
+ key=f"{key_prefix}pdf_desc",
152
+ )
153
+
154
+ pdf_mode = st.radio(
155
+ "Processing Mode",
156
+ options=PDF_MODE_OPTIONS,
157
+ key=f"{key_prefix}pdf_mode",
158
+ )
159
+
160
+ if pdf_files:
161
+ input_data = []
162
+ pdf_name_map = {}
163
+ for f in pdf_files:
164
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
165
+ tmp.write(f.read())
166
+ input_data.append(tmp.name)
167
+ pdf_name_map[tmp.name] = f.name.replace(".pdf", "")
168
+ st.session_state.pdf_name_map = pdf_name_map
169
+ description = pdf_description or "document"
170
+ st.success(f"Uploaded {len(pdf_files)} PDF file(s)")
171
+ return input_data, description, "pdf_files", PDF_MODE_MAP.get(pdf_mode, "image")
172
+
173
+ return None, pdf_description or "document", "pdf_files", PDF_MODE_MAP.get(pdf_mode, "image")
174
+
175
+
176
+ def render_image_upload(key_prefix=""):
177
+ """Render image upload panel.
178
+
179
+ Returns:
180
+ (input_data, description, original_filename) or (None, ..., ...).
181
+ """
182
+ image_files = st.file_uploader(
183
+ "Upload Images",
184
+ type=["png", "jpg", "jpeg", "gif", "webp"],
185
+ accept_multiple_files=True,
186
+ key=f"{key_prefix}image_files",
187
+ )
188
+
189
+ image_description = st.text_input(
190
+ "Image Description",
191
+ placeholder="e.g., 'product photos', 'social media posts'",
192
+ help="Helps the LLM understand context",
193
+ key=f"{key_prefix}image_desc",
194
+ )
195
+
196
+ if image_files:
197
+ input_data = []
198
+ for f in image_files:
199
+ suffix = "." + f.name.split(".")[-1]
200
+ with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
201
+ tmp.write(f.read())
202
+ input_data.append(tmp.name)
203
+ description = image_description or "images"
204
+ st.success(f"Uploaded {len(image_files)} image file(s)")
205
+ return input_data, description, "image_files"
206
+
207
+ return None, image_description or "images", "image_files"
components/header.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ App header: logo, title, about section.
3
+ """
4
+
5
+ import os
6
+ import streamlit as st
7
+
8
+
9
+ def render_header():
10
+ """Render the CatLLM logo, title, and about expander."""
11
+ logo_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "assets", "logo.png")
12
+
13
+ col_logo, col_title = st.columns([1, 6])
14
+ with col_logo:
15
+ if os.path.exists(logo_path):
16
+ st.image(logo_path, width=100)
17
+ with col_title:
18
+ st.title("CatLLM")
19
+ st.markdown("LLM-powered classification, extraction, and summarization across domains.")
20
+
21
+ with st.expander("About This App"):
22
+ st.markdown("""
23
+ **Privacy Notice:** When using cloud LLM providers, your data is sent to third-party APIs.
24
+ Do not upload sensitive, confidential, or personally identifiable information (PII).
25
+
26
+ ---
27
+
28
+ **CatLLM** is an open-source ecosystem for processing text, image, and PDF data using Large Language Models.
29
+
30
+ ### Domains
31
+ - **General** -- domain-neutral text analysis
32
+ - **Survey** -- survey response classification with survey-framed prompts
33
+ - **Social Media** -- fetch and classify posts from Threads, Bluesky, Reddit, Mastodon, YouTube
34
+ - **Academic** -- fetch and classify papers from OpenAlex
35
+ - **Policy** -- classify legislative/policy documents from registered sources
36
+ - **Web** -- classify content fetched from URLs
37
+ - **Cognitive** -- CERAD cognitive assessment drawing scoring
38
+
39
+ ### Functions
40
+ - **Classify** -- assign categories (manual or auto-extracted) to text/PDF/images
41
+ - **Extract** -- discover categories from your data
42
+ - **Explore** -- saturation analysis for category discovery
43
+ - **Summarize** -- generate concise summaries
44
+
45
+ ### Links
46
+ - **PyPI**: [pip install cat-llm](https://pypi.org/project/cat-llm/)
47
+ - **GitHub**: [github.com/chrissoria/cat-llm](https://github.com/chrissoria/cat-llm)
48
+
49
+ ### Citation
50
+ ```
51
+ Soria, C. (2025). CatLLM: A Python package for LLM-based text classification. DOI: 10.5281/zenodo.15532316
52
+ ```
53
+ """)
components/model_selection.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Model selection UI: free/paid tier, single/comparison/ensemble modes + API key input.
3
+ """
4
+
5
+ import streamlit as st
6
+ from config import (
7
+ MODEL_CHOICES, PAID_MODEL_CHOICES, FREE_MODELS_MAP, FREE_MODEL_DISPLAY_NAMES,
8
+ HF_ROUTED_MODELS, resolve_api_key, get_model_source,
9
+ )
10
+
11
+
12
+ def render_api_keys_sidebar():
13
+ """Render API key input fields in the sidebar. Updates st.session_state.api_keys."""
14
+ st.sidebar.markdown("### API Keys")
15
+ st.sidebar.caption("Enter keys for the providers you want to use. Keys are stored in session only.")
16
+
17
+ providers = [
18
+ ("openai", "OpenAI"),
19
+ ("anthropic", "Anthropic"),
20
+ ("google", "Google"),
21
+ ("mistral", "Mistral"),
22
+ ("xai", "xAI"),
23
+ ("huggingface", "HuggingFace"),
24
+ ("perplexity", "Perplexity"),
25
+ ]
26
+
27
+ api_keys = st.session_state.get("api_keys", {})
28
+ for provider_id, display_name in providers:
29
+ key = st.sidebar.text_input(
30
+ display_name,
31
+ value=api_keys.get(provider_id, ""),
32
+ type="password",
33
+ key=f"apikey_{provider_id}",
34
+ )
35
+ if key:
36
+ api_keys[provider_id] = key
37
+ elif provider_id in api_keys:
38
+ del api_keys[provider_id]
39
+ st.session_state.api_keys = api_keys
40
+
41
+
42
+ def _resolve_model_and_key(model_name, model_tier, api_key_input, api_keys):
43
+ """Resolve actual model name, source, and API key based on tier."""
44
+ if model_tier == "Free Models":
45
+ # Free models use HF_API_KEY from env
46
+ import os
47
+ hf_key = os.environ.get("HF_API_KEY", "")
48
+ if not hf_key:
49
+ # Fall back to sidebar-provided HF key
50
+ hf_key = api_keys.get("huggingface", "")
51
+ if not hf_key:
52
+ return model_name, "", "HuggingFace"
53
+ source = get_model_source(model_name)
54
+ return model_name, hf_key, source
55
+ else:
56
+ # Paid models use user-provided keys
57
+ key_val, provider = resolve_api_key(model_name, api_keys)
58
+ source = get_model_source(model_name)
59
+ return model_name, key_val, source
60
+
61
+
62
+ def render_model_selector(mode="single", key_prefix=""):
63
+ """Render model selection UI with free/paid tier.
64
+
65
+ Args:
66
+ mode: "single", "classify" (includes comparison/ensemble), or "extract"/"summarize" (single only).
67
+ key_prefix: Prefix for widget keys to avoid collisions.
68
+
69
+ Returns:
70
+ dict with keys:
71
+ models_tuples: list of (model, source, api_key) or 4-tuples with creativity
72
+ classify_mode: "Single Model", "Model Comparison", or "Ensemble"
73
+ models_list: list of model name strings
74
+ model_temperatures: dict of model -> temperature
75
+ ensemble_runs: list of (model, temperature) for ensemble
76
+ consensus_threshold: float (for ensemble)
77
+ error: str or None
78
+ """
79
+ result = {
80
+ "models_tuples": [],
81
+ "classify_mode": "Single Model",
82
+ "models_list": [],
83
+ "model_temperatures": {},
84
+ "ensemble_runs": [],
85
+ "consensus_threshold": 0.5,
86
+ "error": None,
87
+ }
88
+
89
+ api_keys = st.session_state.get("api_keys", {})
90
+
91
+ # Classification mode selector (only for classify function)
92
+ if mode == "classify":
93
+ classify_mode = st.radio(
94
+ "Classification Mode",
95
+ options=["Single Model", "Model Comparison", "Ensemble"],
96
+ horizontal=True,
97
+ key=f"{key_prefix}classify_mode",
98
+ help="Single: one model. Comparison: side-by-side. Ensemble: majority vote.",
99
+ )
100
+ result["classify_mode"] = classify_mode
101
+ else:
102
+ classify_mode = "Single Model"
103
+
104
+ # Model tier selector
105
+ model_tier = st.radio(
106
+ "Model Tier",
107
+ options=["Free Models", "Bring Your Own Key"],
108
+ key=f"{key_prefix}model_tier",
109
+ horizontal=True,
110
+ )
111
+
112
+ is_free = model_tier == "Free Models"
113
+
114
+ if is_free:
115
+ model_options = FREE_MODEL_DISPLAY_NAMES
116
+ model_values = list(FREE_MODELS_MAP.values())
117
+ else:
118
+ model_options = PAID_MODEL_CHOICES
119
+ model_values = PAID_MODEL_CHOICES
120
+
121
+ model_temperatures = {}
122
+ ensemble_runs = []
123
+
124
+ if classify_mode == "Ensemble":
125
+ # Dynamic run rows allowing same model multiple times
126
+ if "ensemble_num_runs" not in st.session_state:
127
+ st.session_state.ensemble_num_runs = 3
128
+
129
+ st.markdown("**Model Runs** (select 3+ runs)")
130
+ for i in range(st.session_state.ensemble_num_runs):
131
+ cols = st.columns([3, 1, 0.5])
132
+ with cols[0]:
133
+ default_idx = i % len(model_options)
134
+ selected = st.selectbox(
135
+ f"Run {i + 1}",
136
+ options=model_options,
137
+ index=default_idx,
138
+ key=f"{key_prefix}ensemble_model_{i}",
139
+ label_visibility="collapsed",
140
+ )
141
+ with cols[1]:
142
+ temp = st.number_input(
143
+ "Temp",
144
+ min_value=0.0,
145
+ max_value=2.0,
146
+ value=round(i * 0.25, 2),
147
+ step=0.25,
148
+ key=f"{key_prefix}ensemble_temp_{i}",
149
+ label_visibility="collapsed",
150
+ )
151
+ with cols[2]:
152
+ if st.session_state.ensemble_num_runs > 3:
153
+ if st.button("x", key=f"{key_prefix}ensemble_remove_{i}"):
154
+ st.session_state.ensemble_num_runs -= 1
155
+ st.rerun()
156
+
157
+ # Resolve display name to actual model name for free tier
158
+ model_name = FREE_MODELS_MAP[selected] if is_free else selected
159
+ ensemble_runs.append((model_name, temp))
160
+
161
+ if st.button("Add Run", key=f"{key_prefix}add_ensemble_run"):
162
+ st.session_state.ensemble_num_runs += 1
163
+ st.rerun()
164
+
165
+ result["ensemble_runs"] = ensemble_runs
166
+ result["models_list"] = [r[0] for r in ensemble_runs]
167
+
168
+ # Consensus threshold
169
+ consensus_options = {
170
+ "Majority (50%+)": 0.5,
171
+ "Two-Thirds (67%+)": 0.67,
172
+ "Unanimous (100%)": 1.0,
173
+ }
174
+ consensus_choice = st.radio(
175
+ "Consensus Rule",
176
+ options=list(consensus_options.keys()),
177
+ horizontal=True,
178
+ key=f"{key_prefix}consensus_choice",
179
+ help="How many models must agree for a category to be marked present",
180
+ )
181
+ result["consensus_threshold"] = consensus_options[consensus_choice]
182
+
183
+ # Build model tuples
184
+ for m, temp in ensemble_runs:
185
+ m_name, key_val, m_source = _resolve_model_and_key(m, model_tier, None, api_keys)
186
+ if not key_val:
187
+ result["error"] = f"No API key for {m_source} (needed for {m})"
188
+ return result
189
+ result["models_tuples"].append((m, m_source, key_val, {"creativity": temp}))
190
+
191
+ elif classify_mode == "Model Comparison":
192
+ default_models = model_options[:2] if len(model_options) >= 2 else model_options
193
+ selected_models = st.multiselect(
194
+ "Models (select 2+)",
195
+ options=model_options,
196
+ default=default_models,
197
+ key=f"{key_prefix}classify_models_multi",
198
+ )
199
+ # Resolve display names to actual model names
200
+ models_list = [FREE_MODELS_MAP[d] for d in selected_models] if is_free else selected_models
201
+ result["models_list"] = models_list
202
+
203
+ if models_list:
204
+ st.markdown("**Model Temperature**")
205
+ temp_cols = st.columns(len(models_list))
206
+ for idx, (col, m) in enumerate(zip(temp_cols, models_list)):
207
+ short_name = m.split("/")[-1].split(":")[0][:20]
208
+ model_temperatures[m] = col.number_input(
209
+ short_name,
210
+ min_value=0.0,
211
+ max_value=2.0,
212
+ value=0.0,
213
+ step=0.25,
214
+ key=f"{key_prefix}temp_{idx}",
215
+ help=f"Temperature for {m}",
216
+ )
217
+ result["model_temperatures"] = model_temperatures
218
+
219
+ # Build model tuples
220
+ for m in models_list:
221
+ m_name, key_val, m_source = _resolve_model_and_key(m, model_tier, None, api_keys)
222
+ if not key_val:
223
+ result["error"] = f"No API key for {m_source} (needed for {m})"
224
+ return result
225
+ temp = model_temperatures.get(m)
226
+ if temp is not None:
227
+ result["models_tuples"].append((m, m_source, key_val, {"creativity": temp}))
228
+ else:
229
+ result["models_tuples"].append((m, m_source, key_val))
230
+
231
+ else:
232
+ # Single model
233
+ model_display = st.selectbox("Model", options=model_options, key=f"{key_prefix}model")
234
+ model = FREE_MODELS_MAP[model_display] if is_free else model_display
235
+ result["models_list"] = [model]
236
+
237
+ m_name, key_val, m_source = _resolve_model_and_key(model, model_tier, None, api_keys)
238
+ if not key_val:
239
+ result["error"] = f"No API key for {m_source} (needed for {model}). Add it in the sidebar or set HF_API_KEY env var."
240
+ return result
241
+ result["models_tuples"].append((model, m_source, key_val))
242
+
243
+ return result
components/progress.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Progress tracking with ETA estimation.
3
+ """
4
+
5
+ import time
6
+ import streamlit as st
7
+
8
+
9
+ class ProgressTracker:
10
+ """Wraps st.progress + status text with ETA calculation."""
11
+
12
+ def __init__(self, label_prefix="Processing"):
13
+ self.progress_bar = st.progress(0)
14
+ self.status_text = st.empty()
15
+ self.start_time = time.time()
16
+ self.label_prefix = label_prefix
17
+
18
+ def get_callback(self):
19
+ """Return a callback function with (current_idx, total, label) signature."""
20
+ start_time = self.start_time
21
+ progress_bar = self.progress_bar
22
+ status_text = self.status_text
23
+ prefix = self.label_prefix
24
+
25
+ def callback(current_idx, total, label=None):
26
+ progress = current_idx / total if total > 0 else 0
27
+ progress_bar.progress(min(progress, 1.0))
28
+
29
+ elapsed = time.time() - start_time
30
+ if current_idx > 0:
31
+ avg_time = elapsed / current_idx
32
+ eta_seconds = avg_time * (total - current_idx)
33
+ eta_str = f" | ETA: {eta_seconds:.0f}s" if eta_seconds < 60 else f" | ETA: {eta_seconds/60:.1f}m"
34
+ else:
35
+ eta_str = ""
36
+
37
+ label_str = f" ({label})" if label else ""
38
+ status_text.text(
39
+ f"{prefix} {current_idx + 1} of {total}{label_str} ({progress * 100:.0f}%){eta_str}"
40
+ )
41
+
42
+ return callback
43
+
44
+ def complete(self, message):
45
+ """Mark progress as complete."""
46
+ self.progress_bar.progress(1.0)
47
+ self.status_text.text(message)
components/reports.py ADDED
@@ -0,0 +1,273 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Unified methodology PDF report generation (ReportLab).
3
+ """
4
+
5
+ import io
6
+ import tempfile
7
+ from datetime import datetime
8
+
9
+ from components.visualizations import (
10
+ _find_all_model_suffixes,
11
+ create_distribution_chart,
12
+ create_classification_heatmap,
13
+ )
14
+
15
+
16
+ def generate_methodology_report_pdf(
17
+ task_type="classify",
18
+ categories=None,
19
+ model="",
20
+ column_name="",
21
+ num_rows=0,
22
+ model_source="",
23
+ filename="",
24
+ success_rate=100.0,
25
+ result_df=None,
26
+ processing_time=None,
27
+ catllm_version=None,
28
+ python_version=None,
29
+ input_type="text",
30
+ description=None,
31
+ classify_mode="Single Model",
32
+ models_list=None,
33
+ code=None,
34
+ consensus_threshold=None,
35
+ domain="general",
36
+ # Summarize-specific
37
+ focus=None,
38
+ max_length=None,
39
+ ):
40
+ """Generate a PDF methodology report for any task type."""
41
+ from reportlab.lib.pagesizes import letter
42
+ from reportlab.lib import colors
43
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
44
+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
45
+
46
+ import matplotlib.pyplot as plt
47
+
48
+ pdf_file = tempfile.NamedTemporaryFile(mode="wb", suffix="_methodology_report.pdf", delete=False)
49
+ doc = SimpleDocTemplate(pdf_file.name, pagesize=letter)
50
+ styles = getSampleStyleSheet()
51
+
52
+ title_style = ParagraphStyle("Title", parent=styles["Heading1"], fontSize=18, spaceAfter=20)
53
+ heading_style = ParagraphStyle("Heading", parent=styles["Heading2"], fontSize=14, spaceAfter=10, spaceBefore=15)
54
+ normal_style = styles["Normal"]
55
+ code_style = ParagraphStyle("Code", parent=styles["Normal"], fontName="Courier", fontSize=9, leftIndent=20, spaceAfter=3)
56
+
57
+ story = []
58
+
59
+ # Title
60
+ titles = {
61
+ "classify": "CatLLM Classification Report",
62
+ "extract_and_classify": "CatLLM Extraction &amp; Classification Report",
63
+ "summarize": "CatLLM Summarization Report",
64
+ "extract": "CatLLM Category Extraction Report",
65
+ "explore": "CatLLM Category Exploration Report",
66
+ }
67
+ report_title = titles.get(task_type, "CatLLM Report")
68
+ story.append(Paragraph(report_title, title_style))
69
+ story.append(Paragraph(f"Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", normal_style))
70
+ if domain != "general":
71
+ story.append(Paragraph(f"Domain: {domain.replace('_', ' ').title()}", normal_style))
72
+ story.append(Spacer(1, 15))
73
+
74
+ # About
75
+ story.append(Paragraph("About This Report", heading_style))
76
+ about_texts = {
77
+ "classify": "This report documents the classification process for reproducibility and transparency.",
78
+ "extract_and_classify": "This report documents the automated category extraction and classification process.",
79
+ "summarize": "This report documents the automated summarization process.",
80
+ "extract": "This report documents the automated category extraction process.",
81
+ "explore": "This report documents the category exploration and saturation analysis.",
82
+ }
83
+ story.append(Paragraph(about_texts.get(task_type, ""), normal_style))
84
+ story.append(Spacer(1, 15))
85
+
86
+ # Category mapping (classify tasks)
87
+ if categories and task_type in ("classify", "extract_and_classify"):
88
+ story.append(Paragraph("Category Mapping", heading_style))
89
+ if classify_mode in ("Ensemble", "Model Comparison") and result_df is not None:
90
+ all_suffixes = _find_all_model_suffixes(result_df)
91
+ category_data = [["Column Name", "Category Description"]]
92
+ for i, cat in enumerate(categories, 1):
93
+ for suffix in all_suffixes:
94
+ category_data.append([f"category_{i}_{suffix}", f"{cat} ({suffix})"])
95
+ category_data.append([f"category_{i}_consensus", f"{cat} (consensus)"])
96
+ category_data.append([f"category_{i}_agreement", f"{cat} (agreement score)"])
97
+ cat_table = Table(category_data, colWidths=[200, 250])
98
+ else:
99
+ story.append(Paragraph("Each category column: 1 = present, 0 = not present", normal_style))
100
+ story.append(Spacer(1, 8))
101
+ category_data = [["Column Name", "Category Description"]]
102
+ for i, cat in enumerate(categories, 1):
103
+ category_data.append([f"category_{i}", cat])
104
+ cat_table = Table(category_data, colWidths=[120, 330])
105
+
106
+ cat_table.setStyle(TableStyle([
107
+ ("BACKGROUND", (0, 0), (-1, 0), colors.grey),
108
+ ("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke),
109
+ ("GRID", (0, 0), (-1, -1), 1, colors.black),
110
+ ("PADDING", (0, 0), (-1, -1), 6),
111
+ ("BACKGROUND", (0, 1), (0, -1), colors.lightgrey),
112
+ ("FONTSIZE", (0, 0), (-1, -1), 9),
113
+ ]))
114
+ story.append(cat_table)
115
+ story.append(Spacer(1, 15))
116
+
117
+ # Citation
118
+ story.append(Spacer(1, 30))
119
+ story.append(Paragraph("Citation", heading_style))
120
+ story.append(Paragraph("If you use CatLLM in your research, please cite:", normal_style))
121
+ story.append(Spacer(1, 5))
122
+ story.append(Paragraph(
123
+ "Soria, C. (2025). CatLLM: A Python package for LLM-based text classification. DOI: 10.5281/zenodo.15532316",
124
+ normal_style,
125
+ ))
126
+
127
+ # Summary page
128
+ story.append(PageBreak())
129
+ summary_title = {
130
+ "classify": "Classification Summary",
131
+ "extract_and_classify": "Classification Summary",
132
+ "summarize": "Summarization Summary",
133
+ "extract": "Extraction Summary",
134
+ "explore": "Exploration Summary",
135
+ }
136
+ story.append(Paragraph(summary_title.get(task_type, "Summary"), title_style))
137
+ story.append(Spacer(1, 15))
138
+
139
+ summary_data = [
140
+ ["Source File", filename],
141
+ ["Source Column", column_name],
142
+ ["Model(s) Used", model],
143
+ ["Model Source", model_source],
144
+ ["Items Processed", str(num_rows)],
145
+ ["Success Rate", f"{success_rate:.2f}%"],
146
+ ]
147
+ if classify_mode != "Single Model" and task_type in ("classify", "extract_and_classify"):
148
+ summary_data.insert(2, ["Classification Mode", classify_mode])
149
+ if consensus_threshold is not None and classify_mode == "Ensemble":
150
+ labels = {0.5: "Majority (50%+)", 0.67: "Two-Thirds (67%+)", 1.0: "Unanimous (100%)"}
151
+ summary_data.append(["Consensus Threshold", labels.get(consensus_threshold, f"{consensus_threshold:.0%}")])
152
+ if focus:
153
+ summary_data.append(["Focus", focus])
154
+ if max_length:
155
+ summary_data.append(["Max Length", f"{max_length} words"])
156
+ if categories:
157
+ summary_data.append(["Number of Categories", str(len(categories))])
158
+
159
+ summary_table = Table(summary_data, colWidths=[150, 300])
160
+ summary_table.setStyle(TableStyle([
161
+ ("BACKGROUND", (0, 0), (0, -1), colors.lightgrey),
162
+ ("GRID", (0, 0), (-1, -1), 1, colors.black),
163
+ ("PADDING", (0, 0), (-1, -1), 6),
164
+ ("FONTSIZE", (0, 0), (-1, -1), 9),
165
+ ]))
166
+ story.append(summary_table)
167
+ story.append(Spacer(1, 15))
168
+
169
+ # Ensemble agreement scores
170
+ if classify_mode == "Ensemble" and result_df is not None and categories:
171
+ agreement_cols = [f"category_{i}_agreement" for i in range(1, len(categories) + 1)]
172
+ if all(col in result_df.columns for col in agreement_cols):
173
+ story.append(Paragraph("Ensemble Agreement Scores", heading_style))
174
+ agree_data = [["Category", "Mean Agreement", "Min Agreement"]]
175
+ for i, cat in enumerate(categories, 1):
176
+ col = f"category_{i}_agreement"
177
+ agree_data.append([cat, f"{result_df[col].mean():.1%}", f"{result_df[col].min():.1%}"])
178
+ agree_table = Table(agree_data, colWidths=[200, 125, 125])
179
+ agree_table.setStyle(TableStyle([
180
+ ("BACKGROUND", (0, 0), (-1, 0), colors.grey),
181
+ ("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke),
182
+ ("GRID", (0, 0), (-1, -1), 1, colors.black),
183
+ ("PADDING", (0, 0), (-1, -1), 6),
184
+ ("FONTSIZE", (0, 0), (-1, -1), 9),
185
+ ]))
186
+ story.append(agree_table)
187
+ story.append(Spacer(1, 15))
188
+
189
+ # Processing time
190
+ if processing_time is not None:
191
+ story.append(Paragraph("Processing Time", heading_style))
192
+ rows_per_min = (num_rows / processing_time) * 60 if processing_time > 0 else 0
193
+ avg_time = processing_time / num_rows if num_rows > 0 else 0
194
+ time_data = [
195
+ ["Total Processing Time", f"{processing_time:.1f} seconds"],
196
+ ["Average Time per Item", f"{avg_time:.2f} seconds"],
197
+ ["Processing Rate", f"{rows_per_min:.1f} items/minute"],
198
+ ]
199
+ time_table = Table(time_data, colWidths=[180, 270])
200
+ time_table.setStyle(TableStyle([
201
+ ("BACKGROUND", (0, 0), (0, -1), colors.lightgrey),
202
+ ("GRID", (0, 0), (-1, -1), 1, colors.black),
203
+ ("PADDING", (0, 0), (-1, -1), 6),
204
+ ("FONTSIZE", (0, 0), (-1, -1), 9),
205
+ ]))
206
+ story.append(time_table)
207
+
208
+ # Version info
209
+ story.append(Spacer(1, 15))
210
+ story.append(Paragraph("Version Information", heading_style))
211
+ version_data = [
212
+ ["CatLLM Version", catllm_version or "unknown"],
213
+ ["Python Version", python_version or "unknown"],
214
+ ["Timestamp", datetime.now().strftime("%Y-%m-%d %H:%M:%S")],
215
+ ]
216
+ version_table = Table(version_data, colWidths=[180, 270])
217
+ version_table.setStyle(TableStyle([
218
+ ("BACKGROUND", (0, 0), (0, -1), colors.lightgrey),
219
+ ("GRID", (0, 0), (-1, -1), 1, colors.black),
220
+ ("PADDING", (0, 0), (-1, -1), 6),
221
+ ("FONTSIZE", (0, 0), (-1, -1), 9),
222
+ ]))
223
+ story.append(version_table)
224
+
225
+ # Reproducibility code
226
+ if code:
227
+ story.append(PageBreak())
228
+ story.append(Paragraph("Reproducibility Code", title_style))
229
+ story.append(Paragraph("Use this Python code to reproduce the results:", normal_style))
230
+ story.append(Spacer(1, 10))
231
+ for line in code.strip().split("\n"):
232
+ escaped_line = line.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
233
+ if escaped_line.strip():
234
+ story.append(Paragraph(escaped_line, code_style))
235
+ else:
236
+ story.append(Spacer(1, 6))
237
+
238
+ # Visualizations (classify tasks only)
239
+ if result_df is not None and categories and task_type in ("classify", "extract_and_classify"):
240
+ from reportlab.platypus import Image as RLImage
241
+
242
+ story.append(PageBreak())
243
+ story.append(Paragraph("Category Distribution", title_style))
244
+ try:
245
+ fig1 = create_distribution_chart(result_df, categories, classify_mode, models_list)
246
+ img_buffer1 = io.BytesIO()
247
+ fig1.savefig(img_buffer1, format="png", dpi=150, bbox_inches="tight")
248
+ img_buffer1.seek(0)
249
+ plt.close(fig1)
250
+ img_temp1 = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
251
+ img_temp1.write(img_buffer1.read())
252
+ img_temp1.close()
253
+ story.append(RLImage(img_temp1.name, width=450, height=250))
254
+ except Exception as e:
255
+ story.append(Paragraph(f"Could not generate chart: {e}", normal_style))
256
+
257
+ story.append(PageBreak())
258
+ story.append(Paragraph("Classification Matrix", title_style))
259
+ try:
260
+ fig2 = create_classification_heatmap(result_df, categories, classify_mode, models_list)
261
+ img_buffer2 = io.BytesIO()
262
+ fig2.savefig(img_buffer2, format="png", dpi=150, bbox_inches="tight")
263
+ img_buffer2.seek(0)
264
+ plt.close(fig2)
265
+ img_temp2 = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
266
+ img_temp2.write(img_buffer2.read())
267
+ img_temp2.close()
268
+ story.append(RLImage(img_temp2.name, width=450, height=300))
269
+ except Exception as e:
270
+ story.append(Paragraph(f"Could not generate matrix: {e}", normal_style))
271
+
272
+ doc.build(story)
273
+ return pdf_file.name
components/results_display.py ADDED
@@ -0,0 +1,127 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Results display: DataFrame, downloads, code expander.
3
+ """
4
+
5
+ import io
6
+ import streamlit as st
7
+ import matplotlib.pyplot as plt
8
+ from matplotlib.backends.backend_pdf import PdfPages
9
+ from components.visualizations import create_distribution_chart, create_classification_heatmap
10
+
11
+
12
+ COLS_TO_HIDE = ["model_response", "json", "raw_response", "raw_json"]
13
+
14
+
15
+ def render_classify_results(results):
16
+ """Render classification results: visualizations, table, downloads, code."""
17
+ # Visualization selector
18
+ viz_type = st.selectbox(
19
+ "Visualization",
20
+ options=["Category Distribution", "Classification Matrix"],
21
+ key="viz_type",
22
+ help="Distribution shows category percentages. Matrix shows each response's classifications.",
23
+ )
24
+
25
+ if viz_type == "Category Distribution":
26
+ fig = create_distribution_chart(
27
+ results["df"],
28
+ results["categories"],
29
+ classify_mode=results.get("classify_mode", "Single Model"),
30
+ models_list=results.get("models_list", []),
31
+ )
32
+ st.pyplot(fig)
33
+ st.caption("Note: Categories are not mutually exclusive -- each item can belong to multiple categories.")
34
+ else:
35
+ fig = create_classification_heatmap(
36
+ results["df"],
37
+ results["categories"],
38
+ classify_mode=results.get("classify_mode", "Single Model"),
39
+ models_list=results.get("models_list", []),
40
+ )
41
+ st.pyplot(fig)
42
+ st.caption("Orange = category present, Black = not present. Each row is one response.")
43
+
44
+ # Results dataframe
45
+ display_df = results["df"].copy()
46
+ display_df = display_df.drop(columns=[c for c in COLS_TO_HIDE if c in display_df.columns])
47
+ st.dataframe(display_df, use_container_width=True)
48
+
49
+ # Downloads
50
+ col_dl1, col_dl2, col_dl3 = st.columns(3)
51
+ with col_dl1:
52
+ with open(results["csv_path"], "rb") as f:
53
+ st.download_button("Download CSV", data=f, file_name="classified_results.csv", mime="text/csv")
54
+ with col_dl2:
55
+ with open(results["pdf_path"], "rb") as f:
56
+ st.download_button("Download Report", data=f, file_name="methodology_report.pdf", mime="application/pdf")
57
+ with col_dl3:
58
+ plot_buffer = io.BytesIO()
59
+ with PdfPages(plot_buffer) as pdf:
60
+ fig1 = create_distribution_chart(
61
+ results["df"], results["categories"],
62
+ classify_mode=results.get("classify_mode", "Single Model"),
63
+ models_list=results.get("models_list", []),
64
+ )
65
+ pdf.savefig(fig1, bbox_inches="tight")
66
+ plt.close(fig1)
67
+ fig2 = create_classification_heatmap(
68
+ results["df"], results["categories"],
69
+ classify_mode=results.get("classify_mode", "Single Model"),
70
+ models_list=results.get("models_list", []),
71
+ )
72
+ pdf.savefig(fig2, bbox_inches="tight")
73
+ plt.close(fig2)
74
+ plot_buffer.seek(0)
75
+ st.download_button("Download Plots", data=plot_buffer, file_name="classification_plots.pdf", mime="application/pdf")
76
+
77
+ # Code
78
+ with st.expander("See the Code"):
79
+ st.code(results["code"], language="python")
80
+
81
+
82
+ def render_summarize_results(results):
83
+ """Render summarization results: table, downloads, code."""
84
+ st.info("Summary visualization coming soon!")
85
+
86
+ display_df = results["df"].copy()
87
+ display_df = display_df.drop(columns=[c for c in COLS_TO_HIDE if c in display_df.columns])
88
+ st.dataframe(display_df, use_container_width=True)
89
+
90
+ col_dl1, col_dl2 = st.columns(2)
91
+ with col_dl1:
92
+ with open(results["csv_path"], "rb") as f:
93
+ st.download_button("Download Results (CSV)", data=f, file_name="summarized_results.csv", mime="text/csv")
94
+ with col_dl2:
95
+ if results.get("pdf_path"):
96
+ with open(results["pdf_path"], "rb") as f:
97
+ st.download_button("Download Report (PDF)", data=f, file_name="methodology_report.pdf", mime="application/pdf")
98
+
99
+ with st.expander("See the Code"):
100
+ st.code(results["code"], language="python")
101
+
102
+
103
+ def render_extract_results(results):
104
+ """Render extraction results: category list, counts, code."""
105
+ if results.get("categories"):
106
+ st.success(f"Extracted {len(results['categories'])} categories")
107
+ for i, cat in enumerate(results["categories"], 1):
108
+ st.markdown(f"**{i}.** {cat}")
109
+
110
+ if results.get("counts_df") is not None:
111
+ st.dataframe(results["counts_df"], use_container_width=True)
112
+
113
+ if results.get("code"):
114
+ with st.expander("See the Code"):
115
+ st.code(results["code"], language="python")
116
+
117
+
118
+ def render_explore_results(results):
119
+ """Render exploration results."""
120
+ if results.get("categories"):
121
+ st.success(f"Discovered {len(results['categories'])} categories")
122
+ for i, cat in enumerate(results["categories"], 1):
123
+ st.markdown(f"**{i}.** {cat}")
124
+
125
+ if results.get("code"):
126
+ with st.expander("See the Code"):
127
+ st.code(results["code"], language="python")
components/visualizations.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Visualization helpers: distribution chart, classification heatmap.
3
+ """
4
+
5
+ import re
6
+ import numpy as np
7
+ import matplotlib.pyplot as plt
8
+ from matplotlib.colors import ListedColormap
9
+ from matplotlib.patches import Patch
10
+
11
+
12
+ def sanitize_model_name(model: str) -> str:
13
+ """Convert model name to column-safe suffix (matches catllm logic)."""
14
+ sanitized = re.sub(r"[^a-zA-Z0-9]", "_", model)
15
+ sanitized = re.sub(r"_+", "_", sanitized)
16
+ sanitized = sanitized.strip("_").lower()
17
+ return sanitized[:40]
18
+
19
+
20
+ def _find_model_column_suffix(result_df, model_name):
21
+ """Find the actual column suffix used for a model in the DataFrame."""
22
+ sanitized = sanitize_model_name(model_name)
23
+ prefix = f"category_1_{sanitized}"
24
+ for col in result_df.columns:
25
+ if col.startswith(prefix):
26
+ return col[len("category_1_"):]
27
+ return sanitized
28
+
29
+
30
+ def _find_all_model_suffixes(result_df):
31
+ """Discover all distinct per-model column suffixes from the DataFrame."""
32
+ suffixes = []
33
+ for col in result_df.columns:
34
+ m = re.match(r"^category_1_(.+)$", col)
35
+ if m:
36
+ suffix = m.group(1)
37
+ if suffix not in ("consensus", "agreement"):
38
+ suffixes.append(suffix)
39
+ return suffixes
40
+
41
+
42
+ MODEL_COLORS = [
43
+ "#2563eb", "#dc2626", "#16a34a", "#ca8a04",
44
+ "#9333ea", "#0891b2", "#be185d", "#65a30d",
45
+ ]
46
+
47
+
48
+ def create_distribution_chart(result_df, categories, classify_mode="Single Model", models_list=None):
49
+ """Create a horizontal bar chart showing category distribution."""
50
+ total_rows = len(result_df)
51
+ if total_rows == 0:
52
+ fig, ax = plt.subplots(figsize=(10, 4))
53
+ ax.text(0.5, 0.5, "No data to display", ha="center", va="center", fontsize=14)
54
+ ax.axis("off")
55
+ return fig
56
+
57
+ if classify_mode == "Single Model":
58
+ fig, ax = plt.subplots(figsize=(10, max(4, len(categories) * 0.8)))
59
+ dist_data = []
60
+ for i, cat in enumerate(categories, 1):
61
+ col_name = f"category_{i}"
62
+ if col_name in result_df.columns:
63
+ count = int(result_df[col_name].sum())
64
+ pct = (count / total_rows) * 100
65
+ dist_data.append({"Category": cat, "Percentage": round(pct, 1)})
66
+
67
+ categories_list = [d["Category"] for d in dist_data][::-1]
68
+ percentages = [d["Percentage"] for d in dist_data][::-1]
69
+
70
+ bars = ax.barh(categories_list, percentages, color="#2563eb")
71
+ ax.set_xlim(0, 100)
72
+ ax.set_xlabel("Percentage (%)", fontsize=11)
73
+ ax.set_title("Category Distribution (%)", fontsize=14, fontweight="bold")
74
+ for bar, pct in zip(bars, percentages):
75
+ ax.text(bar.get_width() + 1, bar.get_y() + bar.get_height() / 2,
76
+ f"{pct:.1f}%", va="center", fontsize=10)
77
+
78
+ elif classify_mode == "Ensemble":
79
+ fig, ax = plt.subplots(figsize=(10, max(4, len(categories) * 0.8)))
80
+ dist_data = []
81
+ for i, cat in enumerate(categories, 1):
82
+ col_name = f"category_{i}_consensus"
83
+ if col_name in result_df.columns:
84
+ count = int(result_df[col_name].sum())
85
+ pct = (count / total_rows) * 100
86
+ dist_data.append({"Category": cat, "Percentage": round(pct, 1)})
87
+
88
+ categories_list = [d["Category"] for d in dist_data][::-1]
89
+ percentages = [d["Percentage"] for d in dist_data][::-1]
90
+
91
+ bars = ax.barh(categories_list, percentages, color="#16a34a")
92
+ ax.set_xlim(0, 100)
93
+ ax.set_xlabel("Percentage (%)", fontsize=11)
94
+ ax.set_title("Ensemble Consensus Distribution (%)", fontsize=14, fontweight="bold")
95
+ for bar, pct in zip(bars, percentages):
96
+ ax.text(bar.get_width() + 1, bar.get_y() + bar.get_height() / 2,
97
+ f"{pct:.1f}%", va="center", fontsize=10)
98
+
99
+ else: # Model Comparison
100
+ if not models_list:
101
+ models_list = []
102
+ model_suffixes = [_find_model_column_suffix(result_df, m) for m in models_list]
103
+ n_models = len(model_suffixes)
104
+ n_categories = len(categories)
105
+
106
+ fig, ax = plt.subplots(figsize=(12, max(5, n_categories * 1.2)))
107
+ bar_height = 0.8 / max(n_models, 1)
108
+ y_positions = np.arange(n_categories)
109
+
110
+ for model_idx, (model_name, suffix) in enumerate(zip(models_list, model_suffixes)):
111
+ model_pcts = []
112
+ for i in range(1, n_categories + 1):
113
+ col_name = f"category_{i}_{suffix}"
114
+ if col_name in result_df.columns:
115
+ pct = (int(result_df[col_name].sum()) / total_rows) * 100
116
+ else:
117
+ pct = 0
118
+ model_pcts.append(pct)
119
+
120
+ model_pcts = model_pcts[::-1]
121
+ offset = (model_idx - n_models / 2 + 0.5) * bar_height
122
+ color = MODEL_COLORS[model_idx % len(MODEL_COLORS)]
123
+ display_name = model_name.split("/")[-1].split(":")[0][:20]
124
+ ax.barh(y_positions + offset, model_pcts, bar_height * 0.9,
125
+ label=display_name, color=color, alpha=0.85)
126
+
127
+ ax.set_yticks(y_positions)
128
+ ax.set_yticklabels(categories[::-1])
129
+ ax.set_xlim(0, 100)
130
+ ax.set_xlabel("Percentage (%)", fontsize=11)
131
+ ax.set_title("Category Distribution by Model (%)", fontsize=14, fontweight="bold")
132
+ ax.legend(loc="lower right", fontsize=9)
133
+
134
+ plt.tight_layout()
135
+ return fig
136
+
137
+
138
+ def create_classification_heatmap(result_df, categories, classify_mode="Single Model", models_list=None):
139
+ """Create a binary heatmap showing classification for each row."""
140
+ total_rows = len(result_df)
141
+ if total_rows == 0:
142
+ fig, ax = plt.subplots(figsize=(10, 4))
143
+ ax.text(0.5, 0.5, "No data to display", ha="center", va="center", fontsize=14)
144
+ ax.axis("off")
145
+ return fig
146
+
147
+ if classify_mode == "Ensemble":
148
+ col_names = [f"category_{i}_consensus" for i in range(1, len(categories) + 1)]
149
+ elif classify_mode == "Model Comparison" and models_list:
150
+ suffix = _find_model_column_suffix(result_df, models_list[0])
151
+ col_names = [f"category_{i}_{suffix}" for i in range(1, len(categories) + 1)]
152
+ else:
153
+ col_names = [f"category_{i}" for i in range(1, len(categories) + 1)]
154
+
155
+ matrix_data = []
156
+ for col in col_names:
157
+ if col in result_df.columns:
158
+ matrix_data.append(result_df[col].astype(int).values)
159
+ else:
160
+ matrix_data.append(np.zeros(total_rows, dtype=int))
161
+
162
+ matrix = np.array(matrix_data).T
163
+
164
+ fig_height = max(4, min(20, total_rows * 0.15))
165
+ fig_width = max(8, len(categories) * 0.8)
166
+ fig, ax = plt.subplots(figsize=(fig_width, fig_height))
167
+
168
+ cmap = ListedColormap(["#1a1a1a", "#E8A33C"])
169
+ ax.imshow(matrix, aspect="auto", cmap=cmap, vmin=0, vmax=1)
170
+
171
+ ax.set_xticks(range(len(categories)))
172
+ ax.set_xticklabels(categories, rotation=45, ha="right", fontsize=9)
173
+ ax.set_xlabel("Categories", fontsize=11)
174
+ ax.set_ylabel(f"Responses (n={total_rows})", fontsize=11)
175
+ ax.set_yticks([])
176
+
177
+ title = "Classification Matrix"
178
+ if classify_mode == "Ensemble":
179
+ title += " (Ensemble Consensus)"
180
+ elif classify_mode == "Model Comparison" and models_list:
181
+ title += f' ({models_list[0].split("/")[-1].split(":")[0][:20]})'
182
+ ax.set_title(title, fontsize=14, fontweight="bold")
183
+
184
+ legend_elements = [
185
+ Patch(facecolor="#1a1a1a", edgecolor="white", label="Not Present"),
186
+ Patch(facecolor="#E8A33C", edgecolor="white", label="Present"),
187
+ ]
188
+ ax.legend(handles=legend_elements, loc="upper right", bbox_to_anchor=(1.15, 1))
189
+
190
+ plt.tight_layout()
191
+ return fig
config.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Configuration: model lists, API key helpers, constants.
3
+ """
4
+
5
+ import os
6
+
7
+ MAX_CATEGORIES = 10
8
+ INITIAL_CATEGORIES = 3
9
+ MAX_FILE_SIZE_MB = 100
10
+
11
+ # Free models — display name -> actual API model name
12
+ # These are routed through HuggingFace Inference API and use HF_API_KEY env var
13
+ FREE_MODELS_MAP = {
14
+ "Qwen 2.5 72B": "Qwen/Qwen2.5-72B-Instruct",
15
+ }
16
+ FREE_MODEL_DISPLAY_NAMES = list(FREE_MODELS_MAP.keys())
17
+
18
+ # Paid models (user provides their own API key)
19
+ PAID_MODEL_CHOICES = [
20
+ "gemini-2.5-flash",
21
+ "gemini-2.5-pro",
22
+ "gpt-4.1",
23
+ "gpt-4o",
24
+ "gpt-4o-mini",
25
+ "claude-sonnet-4-5-20250929",
26
+ "claude-opus-4-20250514",
27
+ "claude-3-5-haiku-20241022",
28
+ "mistral-large-latest",
29
+ "mistral-medium-2505",
30
+ "grok-4-fast-non-reasoning",
31
+ ]
32
+
33
+ # Combined list for components that need all models
34
+ MODEL_CHOICES = list(FREE_MODELS_MAP.values()) + PAID_MODEL_CHOICES
35
+
36
+ # HuggingFace-routed models (need HF_API_KEY)
37
+ HF_ROUTED_MODELS = list(FREE_MODELS_MAP.values())
38
+
39
+ # Provider -> env var name mapping (for users who set env vars)
40
+ PROVIDER_ENV_KEYS = {
41
+ "openai": "OPENAI_API_KEY",
42
+ "anthropic": "ANTHROPIC_API_KEY",
43
+ "google": "GOOGLE_API_KEY",
44
+ "mistral": "MISTRAL_API_KEY",
45
+ "huggingface": "HF_API_KEY",
46
+ "perplexity": "PERPLEXITY_API_KEY",
47
+ "xai": "XAI_API_KEY",
48
+ }
49
+
50
+
51
+ def get_model_source(model):
52
+ """Auto-detect model provider from model name."""
53
+ model_lower = model.lower()
54
+ if "gpt" in model_lower:
55
+ return "openai"
56
+ elif "claude" in model_lower:
57
+ return "anthropic"
58
+ elif "gemini" in model_lower:
59
+ return "google"
60
+ elif "mistral" in model_lower and ":novita" not in model_lower:
61
+ return "mistral"
62
+ elif any(x in model_lower for x in [":novita", ":groq", "qwen", "llama", "deepseek"]):
63
+ return "huggingface"
64
+ elif "sonar" in model_lower:
65
+ return "perplexity"
66
+ elif "grok" in model_lower:
67
+ return "xai"
68
+ return "huggingface"
69
+
70
+
71
+ def resolve_api_key(model, api_keys_dict):
72
+ """Resolve the API key for a model from the user-provided keys dict.
73
+
74
+ Args:
75
+ model: Model name string.
76
+ api_keys_dict: Dict mapping provider names to API key strings,
77
+ e.g. {"openai": "sk-...", "anthropic": "sk-ant-..."}.
78
+ Returns:
79
+ (api_key, provider_name) tuple.
80
+ """
81
+ provider = get_model_source(model)
82
+ # Check user-provided keys first
83
+ key = api_keys_dict.get(provider, "")
84
+ if key:
85
+ return key, provider
86
+ # Fall back to environment variables
87
+ env_var = PROVIDER_ENV_KEYS.get(provider, "")
88
+ if env_var:
89
+ key = os.environ.get(env_var, "")
90
+ if key:
91
+ return key, provider
92
+ return "", provider
93
+
94
+
95
+ def render_single_model_selector(key_prefix=""):
96
+ """Render a simple free/paid model selector (no ensemble/comparison).
97
+
98
+ Returns:
99
+ (model_name, api_key, model_source, error) tuple.
100
+ """
101
+ import streamlit as st
102
+
103
+ model_tier = st.radio(
104
+ "Model Tier",
105
+ options=["Free Models", "Bring Your Own Key"],
106
+ key=f"{key_prefix}model_tier",
107
+ horizontal=True,
108
+ )
109
+
110
+ api_keys = st.session_state.get("api_keys", {})
111
+
112
+ if model_tier == "Free Models":
113
+ model_display = st.selectbox("Model", options=FREE_MODEL_DISPLAY_NAMES, key=f"{key_prefix}model")
114
+ model = FREE_MODELS_MAP[model_display]
115
+ hf_key = os.environ.get("HF_API_KEY", "") or api_keys.get("huggingface", "")
116
+ if not hf_key:
117
+ return model, "", "huggingface", "No HuggingFace API key. Set HF_API_KEY env var or add it in the sidebar."
118
+ return model, hf_key, get_model_source(model), None
119
+ else:
120
+ model = st.selectbox("Model", options=PAID_MODEL_CHOICES, key=f"{key_prefix}model")
121
+ api_key, provider = resolve_api_key(model, api_keys)
122
+ if not api_key:
123
+ return model, "", provider, f"No API key for {provider}. Add it in the sidebar."
124
+ return model, api_key, get_model_source(model), None
domains/__init__.py ADDED
File without changes
domains/academic.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Academic domain (cat-ademic): OpenAlex paper fetching or upload.
3
+ """
4
+
5
+ import streamlit as st
6
+ from components.file_upload import render_csv_upload
7
+
8
+
9
+ def render_domain_panel(function_id):
10
+ """Render input panel for the Academic domain."""
11
+ result = {
12
+ "input_data": None,
13
+ "input_type": "text",
14
+ "description": "",
15
+ "original_filename": "data",
16
+ "mode": None,
17
+ "df": None,
18
+ "domain_kwargs": {},
19
+ }
20
+
21
+ data_source = st.radio(
22
+ "Data Source",
23
+ options=["Upload CSV/Excel", "Fetch from OpenAlex"],
24
+ horizontal=True,
25
+ key="acad_data_source",
26
+ )
27
+
28
+ if data_source == "Upload CSV/Excel":
29
+ input_data, description, filename, df = render_csv_upload(key_prefix="acad_")
30
+ result["input_data"] = input_data
31
+ result["description"] = description
32
+ result["original_filename"] = filename
33
+ result["df"] = df
34
+ else:
35
+ st.markdown("#### OpenAlex Search")
36
+ journal_name = st.text_input("Journal Name", placeholder="e.g., 'Nature'", key="acad_journal")
37
+ if journal_name:
38
+ result["domain_kwargs"]["journal_name"] = journal_name
39
+
40
+ journal_issn = st.text_input("Journal ISSN (optional)", placeholder="e.g., '0028-0836'", key="acad_issn")
41
+ if journal_issn:
42
+ result["domain_kwargs"]["journal_issn"] = journal_issn
43
+
44
+ journal_field = st.text_input("Field (optional)", placeholder="e.g., 'Computer Science'", key="acad_field")
45
+ if journal_field:
46
+ result["domain_kwargs"]["journal_field"] = journal_field
47
+
48
+ topic_name = st.text_input("Topic (optional)", placeholder="e.g., 'machine learning'", key="acad_topic")
49
+ if topic_name:
50
+ result["domain_kwargs"]["topic_name"] = topic_name
51
+
52
+ col1, col2 = st.columns(2)
53
+ with col1:
54
+ paper_limit = st.number_input("Max Papers", min_value=1, max_value=500, value=50, key="acad_limit")
55
+ result["domain_kwargs"]["paper_limit"] = paper_limit
56
+ with col2:
57
+ polite_email = st.text_input("Email (polite pool)", placeholder="your@email.com", key="acad_email")
58
+ if polite_email:
59
+ result["domain_kwargs"]["polite_email"] = polite_email
60
+
61
+ col1, col2 = st.columns(2)
62
+ with col1:
63
+ date_from = st.date_input("From Date", value=None, key="acad_date_from")
64
+ if date_from:
65
+ result["domain_kwargs"]["date_from"] = str(date_from)
66
+ with col2:
67
+ date_to = st.date_input("To Date", value=None, key="acad_date_to")
68
+ if date_to:
69
+ result["domain_kwargs"]["date_to"] = str(date_to)
70
+
71
+ result["description"] = journal_name or topic_name or "academic papers"
72
+ result["original_filename"] = "openalex_data"
73
+
74
+ # Context fields
75
+ st.markdown("#### Context (optional)")
76
+ col1, col2 = st.columns(2)
77
+ with col1:
78
+ journal_ctx = st.text_input("Journal", key="acad_journal_ctx", placeholder="e.g., 'Nature'")
79
+ if journal_ctx:
80
+ result["domain_kwargs"]["journal"] = journal_ctx
81
+ with col2:
82
+ field_ctx = st.text_input("Field", key="acad_field_ctx", placeholder="e.g., 'Neuroscience'")
83
+ if field_ctx:
84
+ result["domain_kwargs"]["field"] = field_ctx
85
+
86
+ research_focus = st.text_input("Research Focus", key="acad_focus",
87
+ placeholder="e.g., 'deep learning applications in healthcare'")
88
+ if research_focus:
89
+ result["domain_kwargs"]["research_focus"] = research_focus
90
+
91
+ return result
domains/cognitive.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Cognitive domain (cat-cog): CERAD drawing scoring.
3
+ Special case -- only supports cerad_score function.
4
+ """
5
+
6
+ import streamlit as st
7
+ from components.file_upload import render_image_upload
8
+
9
+
10
+ def render_domain_panel(function_id):
11
+ """Render input panel for the Cognitive domain.
12
+
13
+ Only supports image upload for CERAD scoring.
14
+ """
15
+ result = {
16
+ "input_data": None,
17
+ "input_type": "image",
18
+ "description": "CERAD drawing",
19
+ "original_filename": "cerad_images",
20
+ "mode": None,
21
+ "df": None,
22
+ "domain_kwargs": {},
23
+ }
24
+
25
+ # The CERAD page handles its own image upload and shape selection,
26
+ # so this panel is minimal. The function page (cerad_page.py) does the work.
27
+ st.info("Select a shape and upload drawing image(s) below.")
28
+
29
+ return result
domains/general.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ General domain (cat-stack): no extra parameters, standard file upload only.
3
+ """
4
+
5
+ import streamlit as st
6
+ from components.file_upload import render_csv_upload, render_pdf_upload, render_image_upload
7
+
8
+
9
+ def render_domain_panel(function_id):
10
+ """Render input panel for the General domain.
11
+
12
+ Args:
13
+ function_id: Current function ("classify", "extract", "explore", "summarize").
14
+
15
+ Returns:
16
+ dict with keys:
17
+ input_data: list or None
18
+ input_type: "text", "pdf", or "image"
19
+ description: str
20
+ original_filename: str
21
+ mode: str or None (PDF mode)
22
+ df: DataFrame or None
23
+ domain_kwargs: dict of domain-specific kwargs (empty for general)
24
+ """
25
+ input_type_choice = st.radio(
26
+ "Input Type",
27
+ options=["Text Data (CSV/Excel)", "PDF Documents", "Images"],
28
+ horizontal=True,
29
+ key="input_type_radio",
30
+ )
31
+
32
+ result = {
33
+ "input_data": None,
34
+ "input_type": "text",
35
+ "description": "",
36
+ "original_filename": "data",
37
+ "mode": None,
38
+ "df": None,
39
+ "domain_kwargs": {},
40
+ }
41
+
42
+ if input_type_choice == "Text Data (CSV/Excel)":
43
+ result["input_type"] = "text"
44
+ input_data, description, filename, df = render_csv_upload()
45
+ result["input_data"] = input_data
46
+ result["description"] = description
47
+ result["original_filename"] = filename
48
+ result["df"] = df
49
+
50
+ elif input_type_choice == "PDF Documents":
51
+ result["input_type"] = "pdf"
52
+ input_data, description, filename, mode = render_pdf_upload()
53
+ result["input_data"] = input_data
54
+ result["description"] = description
55
+ result["original_filename"] = filename
56
+ result["mode"] = mode
57
+
58
+ else: # Images
59
+ result["input_type"] = "image"
60
+ input_data, description, filename = render_image_upload()
61
+ result["input_data"] = input_data
62
+ result["description"] = description
63
+ result["original_filename"] = filename
64
+
65
+ return result
domains/policy.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Policy domain (cat-pol): registered data sources, doc_type, date filters.
3
+ """
4
+
5
+ import streamlit as st
6
+ from components.file_upload import render_csv_upload, render_pdf_upload
7
+
8
+
9
+ def render_domain_panel(function_id):
10
+ """Render input panel for the Policy domain."""
11
+ result = {
12
+ "input_data": None,
13
+ "input_type": "text",
14
+ "description": "",
15
+ "original_filename": "data",
16
+ "mode": None,
17
+ "df": None,
18
+ "domain_kwargs": {},
19
+ }
20
+
21
+ data_source = st.radio(
22
+ "Data Source",
23
+ options=["Upload CSV/Excel", "Upload PDF", "Fetch from Source"],
24
+ horizontal=True,
25
+ key="pol_data_source",
26
+ )
27
+
28
+ if data_source == "Upload CSV/Excel":
29
+ input_data, description, filename, df = render_csv_upload(key_prefix="pol_")
30
+ result["input_data"] = input_data
31
+ result["description"] = description
32
+ result["original_filename"] = filename
33
+ result["df"] = df
34
+
35
+ elif data_source == "Upload PDF":
36
+ result["input_type"] = "pdf"
37
+ input_data, description, filename, mode = render_pdf_upload(key_prefix="pol_")
38
+ result["input_data"] = input_data
39
+ result["description"] = description
40
+ result["original_filename"] = filename
41
+ result["mode"] = mode
42
+
43
+ else:
44
+ # Fetch from registered source
45
+ st.markdown("#### Policy Data Source")
46
+
47
+ # Try to get available sources
48
+ try:
49
+ import catllm
50
+ sources = catllm.list_policy_sources()
51
+ source_ids = list(sources.keys()) if isinstance(sources, dict) else []
52
+ except Exception:
53
+ source_ids = [
54
+ "city_san_diego", "city_la", "city_berkeley",
55
+ "federal_laws", "trump_truth_social",
56
+ ]
57
+
58
+ source = st.selectbox("Source", options=source_ids, key="pol_source")
59
+ result["domain_kwargs"]["source"] = source
60
+
61
+ doc_type = st.text_input("Document Type (optional)", placeholder="e.g., 'ordinance', 'resolution'",
62
+ key="pol_doc_type")
63
+ if doc_type:
64
+ result["domain_kwargs"]["doc_type"] = doc_type
65
+
66
+ col1, col2 = st.columns(2)
67
+ with col1:
68
+ since = st.date_input("Since", value=None, key="pol_since")
69
+ if since:
70
+ result["domain_kwargs"]["since"] = str(since)
71
+ with col2:
72
+ until = st.date_input("Until", value=None, key="pol_until")
73
+ if until:
74
+ result["domain_kwargs"]["until"] = str(until)
75
+
76
+ n = st.number_input("Max Documents", min_value=1, max_value=500, value=50, key="pol_n")
77
+ result["domain_kwargs"]["n"] = n
78
+
79
+ result["description"] = f"{source} documents"
80
+ result["original_filename"] = f"{source}_data"
81
+
82
+ # Context
83
+ doc_context = st.text_input("Document Context (optional)",
84
+ placeholder="e.g., 'City council proceedings from San Diego'",
85
+ key="pol_context")
86
+ if doc_context:
87
+ result["domain_kwargs"]["document_context"] = doc_context
88
+
89
+ return result
domains/registry.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Domain registry: maps domain IDs to labels, available functions, and catllm callables.
3
+ """
4
+
5
+ import catllm
6
+
7
+ # Each domain defines:
8
+ # label: Display name
9
+ # functions: dict of function_id -> {label, callable}
10
+ # available: whether the domain package is importable
11
+
12
+ DOMAINS = {}
13
+
14
+
15
+ def _register(domain_id, label, functions):
16
+ """Register a domain if its functions are importable."""
17
+ fn_map = {}
18
+ for fn_id, fn_info in functions.items():
19
+ fn_map[fn_id] = fn_info
20
+ DOMAINS[domain_id] = {"label": label, "fn_map": fn_map}
21
+
22
+
23
+ # General (cat-stack) -- always available
24
+ _register("general", "General", {
25
+ "classify": {"label": "Classify", "callable": catllm.classify},
26
+ "extract": {"label": "Extract Categories", "callable": catllm.extract},
27
+ "explore": {"label": "Explore Categories", "callable": catllm.explore},
28
+ "summarize": {"label": "Summarize", "callable": catllm.summarize},
29
+ })
30
+
31
+ # Survey (cat-survey)
32
+ try:
33
+ _register("survey", "Survey", {
34
+ "classify": {"label": "Classify", "callable": catllm.classify_survey},
35
+ "extract": {"label": "Extract Categories", "callable": catllm.extract_survey},
36
+ "explore": {"label": "Explore Categories", "callable": catllm.explore_survey},
37
+ "summarize": {"label": "Summarize", "callable": catllm.summarize_survey},
38
+ })
39
+ except AttributeError:
40
+ pass
41
+
42
+ # Social Media (cat-vader) -- no summarize
43
+ try:
44
+ _register("social_media", "Social Media", {
45
+ "classify": {"label": "Classify", "callable": catllm.classify_social},
46
+ "extract": {"label": "Extract Categories", "callable": catllm.extract_social},
47
+ "explore": {"label": "Explore Categories", "callable": catllm.explore_social},
48
+ })
49
+ except AttributeError:
50
+ pass
51
+
52
+ # Academic (cat-ademic)
53
+ try:
54
+ _register("academic", "Academic", {
55
+ "classify": {"label": "Classify", "callable": catllm.classify_academic},
56
+ "extract": {"label": "Extract Categories", "callable": catllm.extract_academic},
57
+ "explore": {"label": "Explore Categories", "callable": catllm.explore_academic},
58
+ "summarize": {"label": "Summarize", "callable": catllm.summarize_academic},
59
+ })
60
+ except AttributeError:
61
+ pass
62
+
63
+ # Policy (cat-pol)
64
+ try:
65
+ _register("policy", "Policy", {
66
+ "classify": {"label": "Classify", "callable": catllm.classify_policy},
67
+ "extract": {"label": "Extract Categories", "callable": catllm.extract_policy},
68
+ "explore": {"label": "Explore Categories", "callable": catllm.explore_policy},
69
+ "summarize": {"label": "Summarize", "callable": catllm.summarize_policy},
70
+ })
71
+ except AttributeError:
72
+ pass
73
+
74
+ # Web (cat-web)
75
+ try:
76
+ _register("web", "Web", {
77
+ "classify": {"label": "Classify", "callable": catllm.classify_web},
78
+ "extract": {"label": "Extract Categories", "callable": catllm.extract_web},
79
+ "explore": {"label": "Explore Categories", "callable": catllm.explore_web},
80
+ "summarize": {"label": "Summarize", "callable": catllm.summarize_web},
81
+ })
82
+ except AttributeError:
83
+ pass
84
+
85
+ # Cognitive (cat-cog)
86
+ try:
87
+ _register("cognitive", "Cognitive", {
88
+ "cerad_score": {"label": "CERAD Score", "callable": catllm.cerad_drawn_score},
89
+ })
90
+ except AttributeError:
91
+ pass
92
+
93
+
94
+ def get_domain_ids():
95
+ """Return ordered list of available domain IDs."""
96
+ order = ["general", "survey", "social_media", "academic", "policy", "web", "cognitive"]
97
+ return [d for d in order if d in DOMAINS]
98
+
99
+
100
+ def get_domain_label(domain_id):
101
+ """Get display label for a domain."""
102
+ return DOMAINS.get(domain_id, {}).get("label", domain_id)
103
+
104
+
105
+ def get_functions(domain_id):
106
+ """Return dict of function_id -> {label, callable} for a domain."""
107
+ return DOMAINS.get(domain_id, {}).get("fn_map", {})
108
+
109
+
110
+ def get_callable(domain_id, function_id):
111
+ """Get the catllm callable for a (domain, function) pair."""
112
+ fn_map = get_functions(domain_id)
113
+ fn_info = fn_map.get(function_id)
114
+ if fn_info:
115
+ return fn_info["callable"]
116
+ return None
domains/social_media.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Social Media domain (cat-vader): fetch from platforms or upload data.
3
+ """
4
+
5
+ import streamlit as st
6
+ from components.file_upload import render_csv_upload
7
+
8
+
9
+ def render_domain_panel(function_id):
10
+ """Render input panel for the Social Media domain."""
11
+ result = {
12
+ "input_data": None,
13
+ "input_type": "text",
14
+ "description": "",
15
+ "original_filename": "data",
16
+ "mode": None,
17
+ "df": None,
18
+ "domain_kwargs": {},
19
+ }
20
+
21
+ data_source = st.radio(
22
+ "Data Source",
23
+ options=["Upload CSV/Excel", "Fetch from Platform"],
24
+ horizontal=True,
25
+ key="sm_data_source",
26
+ )
27
+
28
+ if data_source == "Upload CSV/Excel":
29
+ input_data, description, filename, df = render_csv_upload(key_prefix="sm_")
30
+ result["input_data"] = input_data
31
+ result["description"] = description
32
+ result["original_filename"] = filename
33
+ result["df"] = df
34
+ else:
35
+ # Fetch from platform
36
+ platform = st.selectbox(
37
+ "Platform",
38
+ options=["threads", "bluesky", "reddit", "mastodon", "youtube"],
39
+ key="sm_platform",
40
+ )
41
+ result["domain_kwargs"]["sm_source"] = platform
42
+
43
+ handle = st.text_input("Handle / Username", placeholder="e.g., @username", key="sm_handle")
44
+ if handle:
45
+ result["domain_kwargs"]["sm_handle"] = handle
46
+
47
+ sm_limit = st.number_input("Max Posts to Fetch", min_value=1, max_value=500, value=50, key="sm_limit")
48
+ result["domain_kwargs"]["sm_limit"] = sm_limit
49
+
50
+ col1, col2 = st.columns(2)
51
+ with col1:
52
+ sm_months = st.number_input("Months Back", min_value=0, max_value=24, value=0, key="sm_months",
53
+ help="0 = no limit")
54
+ if sm_months > 0:
55
+ result["domain_kwargs"]["sm_months"] = sm_months
56
+ with col2:
57
+ sm_days = st.number_input("Days Back", min_value=0, max_value=365, value=0, key="sm_days",
58
+ help="0 = no limit")
59
+ if sm_days > 0:
60
+ result["domain_kwargs"]["sm_days"] = sm_days
61
+
62
+ # YouTube-specific options
63
+ if platform == "youtube":
64
+ yt_content = st.selectbox("Content Type", options=["video", "comments"], key="sm_yt_content")
65
+ result["domain_kwargs"]["sm_youtube_content"] = yt_content
66
+ if yt_content == "video":
67
+ yt_transcript = st.checkbox("Include Transcripts", key="sm_yt_transcript")
68
+ result["domain_kwargs"]["sm_youtube_transcript"] = yt_transcript
69
+
70
+ # Credentials
71
+ with st.expander("Platform Credentials"):
72
+ st.caption("Required for some platforms (e.g., Reddit client_id/secret, Threads token).")
73
+ cred_key = st.text_input("Credential / Token", type="password", key="sm_credential")
74
+ if cred_key:
75
+ if platform == "reddit":
76
+ client_id = st.text_input("Reddit Client ID", key="sm_reddit_id")
77
+ client_secret = st.text_input("Reddit Client Secret", type="password", key="sm_reddit_secret")
78
+ if client_id and client_secret:
79
+ result["domain_kwargs"]["sm_credentials"] = {
80
+ "client_id": client_id,
81
+ "client_secret": client_secret,
82
+ }
83
+ else:
84
+ result["domain_kwargs"]["sm_credentials"] = {"token": cred_key}
85
+
86
+ result["description"] = f"{platform} posts"
87
+ result["original_filename"] = f"{platform}_data"
88
+
89
+ # Context fields
90
+ st.markdown("#### Context (optional)")
91
+ col1, col2 = st.columns(2)
92
+ with col1:
93
+ platform_ctx = st.text_input("Platform", key="sm_platform_ctx",
94
+ placeholder="e.g., 'Twitter'")
95
+ if platform_ctx:
96
+ result["domain_kwargs"]["platform"] = platform_ctx
97
+ with col2:
98
+ handle_ctx = st.text_input("Handle", key="sm_handle_ctx",
99
+ placeholder="e.g., '@elonmusk'")
100
+ if handle_ctx:
101
+ result["domain_kwargs"]["handle"] = handle_ctx
102
+
103
+ hashtags = st.text_input("Hashtags (comma-separated)", key="sm_hashtags",
104
+ placeholder="e.g., '#AI, #tech'")
105
+ if hashtags:
106
+ result["domain_kwargs"]["hashtags"] = [h.strip() for h in hashtags.split(",") if h.strip()]
107
+
108
+ return result
domains/survey.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Survey domain (cat-survey): adds survey_question input.
3
+ """
4
+
5
+ import streamlit as st
6
+ from domains.general import render_domain_panel as render_general_panel
7
+
8
+
9
+ def render_domain_panel(function_id):
10
+ """Render input panel for the Survey domain.
11
+
12
+ Same as General but adds a 'Survey Question' text input.
13
+ """
14
+ result = render_general_panel(function_id)
15
+
16
+ survey_question = st.text_input(
17
+ "Survey Question",
18
+ placeholder="e.g., 'What is the primary reason you moved to your current neighborhood?'",
19
+ help="The question respondents were asked. Helps the LLM understand context.",
20
+ key="survey_question",
21
+ )
22
+
23
+ result["domain_kwargs"]["survey_question"] = survey_question
24
+ return result
domains/web.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Web domain (cat-web): URL list or CSV upload, source_domain, content_type.
3
+ """
4
+
5
+ import streamlit as st
6
+ from components.file_upload import render_csv_upload
7
+
8
+
9
+ def render_domain_panel(function_id):
10
+ """Render input panel for the Web domain."""
11
+ result = {
12
+ "input_data": None,
13
+ "input_type": "text",
14
+ "description": "",
15
+ "original_filename": "data",
16
+ "mode": None,
17
+ "df": None,
18
+ "domain_kwargs": {},
19
+ }
20
+
21
+ data_source = st.radio(
22
+ "Data Source",
23
+ options=["Upload CSV/Excel", "Enter URLs"],
24
+ horizontal=True,
25
+ key="web_data_source",
26
+ )
27
+
28
+ if data_source == "Upload CSV/Excel":
29
+ input_data, description, filename, df = render_csv_upload(key_prefix="web_")
30
+ result["input_data"] = input_data
31
+ result["description"] = description
32
+ result["original_filename"] = filename
33
+ result["df"] = df
34
+ else:
35
+ urls_text = st.text_area(
36
+ "URLs (one per line)",
37
+ placeholder="https://example.com/article1\nhttps://example.com/article2",
38
+ height=150,
39
+ key="web_urls",
40
+ )
41
+ if urls_text:
42
+ urls = [u.strip() for u in urls_text.strip().split("\n") if u.strip()]
43
+ if urls:
44
+ result["input_data"] = urls
45
+ result["description"] = "web content"
46
+ result["original_filename"] = "urls"
47
+ st.success(f"{len(urls)} URL(s) entered")
48
+
49
+ # Web-specific fields
50
+ st.markdown("#### Web Context (optional)")
51
+ col1, col2 = st.columns(2)
52
+ with col1:
53
+ source_domain = st.text_input("Source Domain", placeholder="e.g., 'nytimes.com'", key="web_domain")
54
+ if source_domain:
55
+ result["domain_kwargs"]["source_domain"] = source_domain
56
+ with col2:
57
+ content_type = st.text_input("Content Type", placeholder="e.g., 'news article'", key="web_content_type")
58
+ if content_type:
59
+ result["domain_kwargs"]["content_type"] = content_type
60
+
61
+ timeout = st.number_input("Fetch Timeout (seconds)", min_value=5, max_value=120, value=30, key="web_timeout")
62
+ result["domain_kwargs"]["timeout"] = timeout
63
+
64
+ # Web metadata key-value pairs
65
+ with st.expander("Additional Metadata"):
66
+ st.caption("Add key-value pairs to inject into prompts.")
67
+ meta_key = st.text_input("Key", key="web_meta_key", placeholder="e.g., 'section'")
68
+ meta_val = st.text_input("Value", key="web_meta_val", placeholder="e.g., 'technology'")
69
+ if meta_key and meta_val:
70
+ result["domain_kwargs"]["web_metadata"] = {meta_key: meta_val}
71
+
72
+ return result
functions/__init__.py ADDED
File without changes
functions/cerad_page.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CERAD scoring page (cat-cog only): shape selector, image upload, score display.
3
+ """
4
+
5
+ import sys
6
+ import time
7
+ import tempfile
8
+ import streamlit as st
9
+
10
+ import catllm
11
+ from config import render_single_model_selector, get_model_source
12
+ from components.file_upload import render_image_upload
13
+
14
+
15
+ def render(domain_id, domain_panel):
16
+ """Render the CERAD scoring page."""
17
+ st.markdown("---")
18
+ st.markdown("### CERAD Drawing Score")
19
+ st.markdown("Score hand-drawn images for the CERAD cognitive assessment.")
20
+
21
+ shape = st.selectbox("Shape", options=["circle", "diamond", "rectangles", "cube"], key="cerad_shape")
22
+
23
+ # Image upload
24
+ input_data, description, filename = render_image_upload(key_prefix="cerad_")
25
+
26
+ st.markdown("### Model Selection")
27
+ model, api_key, model_source, key_error = render_single_model_selector(key_prefix="cerad_")
28
+
29
+ if st.button("Score Drawing", type="primary", use_container_width=True):
30
+ if input_data is None:
31
+ st.error("Please upload image(s) first")
32
+ return
33
+
34
+ if key_error:
35
+ st.error(key_error)
36
+ return
37
+
38
+ try:
39
+ with st.spinner("Scoring..."):
40
+ result_df = catllm.cerad_drawn_score(
41
+ shape=shape,
42
+ image_input=input_data,
43
+ api_key=api_key,
44
+ user_model=model,
45
+ model_source=model_source,
46
+ )
47
+
48
+ st.success("Scoring complete!")
49
+ st.dataframe(result_df, use_container_width=True)
50
+
51
+ # Download
52
+ with tempfile.NamedTemporaryFile(mode="w", suffix="_cerad_scores.csv", delete=False) as f:
53
+ result_df.to_csv(f.name, index=False)
54
+ with open(f.name, "rb") as fread:
55
+ st.download_button("Download Scores (CSV)", data=fread, file_name="cerad_scores.csv", mime="text/csv")
56
+
57
+ # Code
58
+ with st.expander("See the Code"):
59
+ st.code(f"""import catllm
60
+
61
+ result = catllm.cerad_drawn_score(
62
+ shape="{shape}",
63
+ image_input="path/to/images/",
64
+ api_key="YOUR_API_KEY",
65
+ user_model="{model}"
66
+ )
67
+ print(result)
68
+ """, language="python")
69
+
70
+ except Exception as e:
71
+ st.error(f"Error: {str(e)}")
functions/classify_page.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Classify function page: categories (manual/auto-extract), classify modes, run + results.
3
+ """
4
+
5
+ import os
6
+ import sys
7
+ import time
8
+ import tempfile
9
+ import pandas as pd
10
+ import streamlit as st
11
+
12
+ import catllm
13
+ from config import MAX_CATEGORIES, INITIAL_CATEGORIES, get_model_source, resolve_api_key, render_single_model_selector
14
+ from components.model_selection import render_model_selector
15
+ from components.progress import ProgressTracker
16
+ from components.reports import generate_methodology_report_pdf
17
+ from components.code_generation import generate_classify_code, generate_extract_code
18
+ from components.results_display import render_classify_results
19
+ from domains.registry import get_callable
20
+
21
+
22
+ def render(domain_id, domain_panel):
23
+ """Render the classify function page.
24
+
25
+ Args:
26
+ domain_id: Current domain ID string.
27
+ domain_panel: Dict returned by the domain's render_domain_panel().
28
+ """
29
+ input_data = domain_panel["input_data"]
30
+ input_type = domain_panel["input_type"]
31
+ description = domain_panel["description"]
32
+ original_filename = domain_panel["original_filename"]
33
+ mode = domain_panel.get("mode")
34
+ domain_kwargs = domain_panel.get("domain_kwargs", {})
35
+
36
+ st.markdown("---")
37
+
38
+ # Task selection
39
+ st.markdown("### What would you like to do?")
40
+ col_btn1, col_btn2 = st.columns(2)
41
+ with col_btn1:
42
+ if st.button("Enter Categories Manually", use_container_width=True):
43
+ st.session_state.task_mode = "manual"
44
+ with col_btn2:
45
+ if st.button("Auto-extract Categories", use_container_width=True):
46
+ st.session_state.task_mode = "auto_extract"
47
+
48
+ # Auto-extract flow
49
+ if st.session_state.task_mode == "auto_extract":
50
+ _render_auto_extract(domain_id, input_data, input_type, description, mode, domain_kwargs)
51
+
52
+ # Manual category entry + classify
53
+ if st.session_state.task_mode == "manual":
54
+ _render_manual_classify(domain_id, input_data, input_type, description, original_filename, mode, domain_kwargs)
55
+
56
+
57
+ def _render_auto_extract(domain_id, input_data, input_type, description, mode, domain_kwargs):
58
+ """Render auto-extract UI and run extraction."""
59
+ st.markdown("### Auto-extract Categories")
60
+ st.markdown("We'll analyze your data to discover the main categories.")
61
+
62
+ max_categories = st.slider("Number of Categories to Extract", min_value=3, max_value=25, value=12)
63
+ specificity = st.selectbox("How specific?", options=["Broad", "Moderate", "Narrow"], index=0)
64
+ focus = st.text_input("Focus (optional)", placeholder="e.g., 'emotional responses', 'financial factors'")
65
+
66
+ # Model selection (single model for extraction)
67
+ st.markdown("### Model Selection")
68
+ model, api_key, model_source_val, key_error = render_single_model_selector(key_prefix="extract_")
69
+
70
+ if st.button("Extract Categories", type="primary"):
71
+ if input_data is None:
72
+ st.error("Please upload data first")
73
+ elif key_error:
74
+ st.error(key_error)
75
+ else:
76
+ model_source = get_model_source(model)
77
+ tracker = ProgressTracker("Extracting categories")
78
+
79
+ extract_fn = get_callable(domain_id, "extract")
80
+ if extract_fn is None:
81
+ st.error(f"Extract not available for domain '{domain_id}'")
82
+ return
83
+
84
+ extract_kwargs = {
85
+ "input_data": input_data,
86
+ "api_key": api_key,
87
+ "input_type": input_type,
88
+ "description": description,
89
+ "user_model": model,
90
+ "model_source": model_source,
91
+ "max_categories": int(max_categories),
92
+ "specificity": specificity.lower(),
93
+ "progress_callback": tracker.get_callback(),
94
+ }
95
+ if mode:
96
+ extract_kwargs["mode"] = mode
97
+ if focus and focus.strip():
98
+ extract_kwargs["focus"] = focus.strip()
99
+ # Add domain-specific kwargs
100
+ extract_kwargs.update(domain_kwargs)
101
+
102
+ try:
103
+ extract_result = extract_fn(**extract_kwargs)
104
+ categories = extract_result.get("top_categories", [])
105
+ processing_time = time.time() - tracker.start_time
106
+ tracker.complete(f"Completed in {processing_time:.1f}s")
107
+
108
+ if categories:
109
+ st.success(f"Extracted {len(categories)} categories in {processing_time:.1f}s")
110
+ st.session_state.extracted_categories = categories
111
+ st.session_state.extraction_params = {
112
+ "model": model,
113
+ "model_source": model_source,
114
+ "max_categories": int(max_categories),
115
+ "input_type": input_type,
116
+ "description": description,
117
+ "mode": mode,
118
+ }
119
+ st.session_state.task_mode = "manual"
120
+ st.rerun()
121
+ else:
122
+ st.error("No categories were extracted from the data")
123
+ except Exception as e:
124
+ st.error(f"Error: {str(e)}")
125
+
126
+
127
+ def _render_manual_classify(domain_id, input_data, input_type, description, original_filename, mode, domain_kwargs):
128
+ """Render manual category entry and classification."""
129
+ st.markdown("### Categories")
130
+
131
+ # Pre-fill with extracted categories
132
+ if st.session_state.extracted_categories:
133
+ for i, cat in enumerate(st.session_state.extracted_categories[:MAX_CATEGORIES]):
134
+ st.session_state.categories[i] = cat
135
+ st.session_state.category_count = min(len(st.session_state.extracted_categories), MAX_CATEGORIES)
136
+ st.session_state.extracted_categories = None
137
+
138
+ placeholders = [
139
+ "e.g., Positive sentiment", "e.g., Negative sentiment", "e.g., Product feedback",
140
+ "e.g., Service complaint", "e.g., Feature request", "e.g., Custom category",
141
+ ]
142
+ categories_entered = []
143
+ for i in range(st.session_state.category_count):
144
+ placeholder = placeholders[i] if i < len(placeholders) else "e.g., Custom category"
145
+ cat_value = st.text_input(
146
+ f"Category {i + 1}",
147
+ value=st.session_state.categories[i],
148
+ placeholder=placeholder,
149
+ key=f"cat_{i}",
150
+ )
151
+ st.session_state.categories[i] = cat_value
152
+ if cat_value.strip():
153
+ categories_entered.append(cat_value.strip())
154
+
155
+ if st.session_state.category_count < MAX_CATEGORIES:
156
+ if st.button("+ Add More"):
157
+ st.session_state.category_count += 1
158
+ st.rerun()
159
+
160
+ # Model selection with classify modes
161
+ st.markdown("### Model Selection")
162
+ model_sel = render_model_selector(mode="classify", key_prefix="cls_")
163
+
164
+ classify_mode = model_sel["classify_mode"]
165
+ models_list = model_sel["models_list"]
166
+ models_tuples = model_sel["models_tuples"]
167
+ ensemble_runs = model_sel["ensemble_runs"]
168
+ model_temperatures = model_sel["model_temperatures"]
169
+ consensus_threshold = model_sel["consensus_threshold"]
170
+
171
+ if st.button("Categorize Data", type="primary", use_container_width=True):
172
+ if input_data is None:
173
+ st.error("Please upload data first")
174
+ elif not categories_entered:
175
+ st.error("Please enter at least one category")
176
+ elif model_sel["error"]:
177
+ st.error(model_sel["error"])
178
+ elif classify_mode == "Model Comparison" and len(models_list) < 2:
179
+ st.error("Please select at least 2 models for comparison mode")
180
+ elif classify_mode == "Ensemble" and len(models_list) < 3:
181
+ st.error("Please select at least 3 models for ensemble mode")
182
+ else:
183
+ _run_classify(
184
+ domain_id, input_data, input_type, description, original_filename,
185
+ mode, categories_entered, models_tuples, models_list, classify_mode,
186
+ consensus_threshold, model_temperatures, ensemble_runs, domain_kwargs,
187
+ )
188
+
189
+
190
+ def _run_classify(
191
+ domain_id, input_data, input_type, description, original_filename,
192
+ mode, categories, models_tuples, models_list, classify_mode,
193
+ consensus_threshold, model_temperatures, ensemble_runs, domain_kwargs,
194
+ ):
195
+ """Execute the classification and store results."""
196
+ items_list = input_data if isinstance(input_data, list) else [input_data]
197
+ tracker = ProgressTracker("Processing item" if input_type != "pdf" else "Processing page")
198
+
199
+ classify_fn = get_callable(domain_id, "classify")
200
+ if classify_fn is None:
201
+ st.error(f"Classify not available for domain '{domain_id}'")
202
+ return
203
+
204
+ classify_kwargs = {
205
+ "input_data": items_list,
206
+ "categories": categories,
207
+ "models": models_tuples,
208
+ "description": description,
209
+ "progress_callback": tracker.get_callback(),
210
+ }
211
+ if mode:
212
+ classify_kwargs["mode"] = mode
213
+ if classify_mode == "Ensemble":
214
+ classify_kwargs["consensus_threshold"] = consensus_threshold
215
+ # Add domain-specific kwargs
216
+ classify_kwargs.update(domain_kwargs)
217
+
218
+ try:
219
+ start_time = time.time()
220
+ result_df = classify_fn(**classify_kwargs)
221
+ processing_time = time.time() - start_time
222
+ tracker.complete(f"Completed {len(result_df)} items in {processing_time:.1f}s")
223
+
224
+ # Replace temp PDF paths
225
+ if input_type == "pdf" and "pdf_input" in result_df.columns:
226
+ pdf_name_map = st.session_state.get("pdf_name_map", {})
227
+ def replace_temp_path(val):
228
+ if pd.isna(val):
229
+ return val
230
+ val_str = str(val)
231
+ for temp_path, orig_name in pdf_name_map.items():
232
+ temp_name = os.path.basename(temp_path).replace(".pdf", "")
233
+ if temp_name in val_str:
234
+ return val_str.replace(temp_name, orig_name)
235
+ return val_str
236
+ result_df["pdf_input"] = result_df["pdf_input"].apply(replace_temp_path)
237
+
238
+ # Save CSV
239
+ with tempfile.NamedTemporaryFile(mode="w", suffix="_classified.csv", delete=False) as f:
240
+ result_df.to_csv(f.name, index=False)
241
+ csv_path = f.name
242
+
243
+ # Success rate
244
+ if "processing_status" in result_df.columns:
245
+ success_rate = (result_df["processing_status"] == "success").sum() / len(result_df) * 100
246
+ else:
247
+ success_rate = 100.0
248
+
249
+ # Version info
250
+ catllm_version = getattr(catllm, "__version__", "unknown")
251
+ python_version = sys.version.split()[0]
252
+
253
+ # Report model string
254
+ report_model = models_list[0] if len(models_list) == 1 else ", ".join(models_list)
255
+ report_source = models_tuples[0][1] if len(models_list) == 1 else f"{classify_mode} ({len(models_list)} models)"
256
+
257
+ # Generate code
258
+ code = generate_classify_code(
259
+ domain_id, input_type, description, categories, report_model, report_source,
260
+ mode=mode, classify_mode=classify_mode, models_list=models_list,
261
+ consensus_threshold=consensus_threshold, model_temperatures=model_temperatures,
262
+ ensemble_runs=ensemble_runs if ensemble_runs else None,
263
+ domain_kwargs=domain_kwargs,
264
+ )
265
+
266
+ # Generate report
267
+ pdf_path = generate_methodology_report_pdf(
268
+ task_type="classify", categories=categories, model=report_model,
269
+ column_name=description, num_rows=len(result_df), model_source=report_source,
270
+ filename=original_filename, success_rate=success_rate, result_df=result_df,
271
+ processing_time=processing_time, catllm_version=catllm_version,
272
+ python_version=python_version, input_type=input_type, description=description,
273
+ classify_mode=classify_mode, models_list=models_list, code=code,
274
+ consensus_threshold=consensus_threshold if classify_mode == "Ensemble" else None,
275
+ domain=domain_id,
276
+ )
277
+
278
+ st.session_state.results = {
279
+ "df": result_df,
280
+ "csv_path": csv_path,
281
+ "pdf_path": pdf_path,
282
+ "code": code,
283
+ "status": f"Classified {len(result_df)} items in {processing_time:.1f}s",
284
+ "categories": categories,
285
+ "classify_mode": classify_mode,
286
+ "models_list": models_list,
287
+ "model_temperatures": model_temperatures,
288
+ "ensemble_runs": ensemble_runs if ensemble_runs else None,
289
+ "task_type": "classify",
290
+ }
291
+ st.success(f"Classified {len(result_df)} items in {processing_time:.1f}s")
292
+ st.rerun()
293
+
294
+ except Exception as e:
295
+ st.error(f"Error: {str(e)}")
functions/explore_page.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Explore function page: saturation analysis for category discovery.
3
+ """
4
+
5
+ import time
6
+ import streamlit as st
7
+
8
+ from config import render_single_model_selector, get_model_source
9
+ from components.progress import ProgressTracker
10
+ from components.results_display import render_explore_results
11
+ from domains.registry import get_callable
12
+
13
+
14
+ def render(domain_id, domain_panel):
15
+ """Render the explore function page."""
16
+ input_data = domain_panel["input_data"]
17
+ input_type = domain_panel["input_type"]
18
+ description = domain_panel["description"]
19
+ mode = domain_panel.get("mode")
20
+ domain_kwargs = domain_panel.get("domain_kwargs", {})
21
+
22
+ st.markdown("---")
23
+ st.markdown("### Exploration Options")
24
+ st.markdown("Explore discovers categories and checks for saturation (whether new categories keep appearing).")
25
+
26
+ st.markdown("### Model Selection")
27
+ model, api_key, model_source, key_error = render_single_model_selector(key_prefix="explore_")
28
+
29
+ if st.button("Explore Categories", type="primary", use_container_width=True):
30
+ if input_data is None:
31
+ st.error("Please upload data first")
32
+ return
33
+
34
+ if key_error:
35
+ st.error(key_error)
36
+ return
37
+ tracker = ProgressTracker("Exploring categories")
38
+
39
+ explore_fn = get_callable(domain_id, "explore")
40
+ if explore_fn is None:
41
+ st.error(f"Explore not available for domain '{domain_id}'")
42
+ return
43
+
44
+ items_list = input_data if isinstance(input_data, list) else [input_data]
45
+
46
+ explore_kwargs = {
47
+ "input_data": items_list,
48
+ "api_key": api_key,
49
+ "description": description,
50
+ "user_model": model,
51
+ "model_source": model_source,
52
+ }
53
+ if mode:
54
+ explore_kwargs["mode"] = mode
55
+ explore_kwargs.update(domain_kwargs)
56
+
57
+ try:
58
+ categories = explore_fn(**explore_kwargs)
59
+ processing_time = time.time() - tracker.start_time
60
+ tracker.complete(f"Completed in {processing_time:.1f}s")
61
+
62
+ st.session_state.results = {
63
+ "categories": categories if isinstance(categories, list) else [],
64
+ "code": f"""import catllm
65
+
66
+ result = catllm.explore(
67
+ input_data=your_data,
68
+ api_key="YOUR_API_KEY",
69
+ description="{description}",
70
+ user_model="{model}"
71
+ )
72
+ print(result)
73
+ """,
74
+ "task_type": "explore",
75
+ }
76
+ st.success(f"Discovered {len(categories) if isinstance(categories, list) else 0} categories")
77
+ st.rerun()
78
+
79
+ except Exception as e:
80
+ st.error(f"Error: {str(e)}")
functions/extract_page.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Extract function page: standalone category extraction.
3
+ """
4
+
5
+ import time
6
+ import streamlit as st
7
+
8
+ from config import render_single_model_selector, get_model_source
9
+ from components.progress import ProgressTracker
10
+ from components.code_generation import generate_extract_code
11
+ from components.results_display import render_extract_results
12
+ from domains.registry import get_callable
13
+
14
+
15
+ def render(domain_id, domain_panel):
16
+ """Render the extract function page."""
17
+ input_data = domain_panel["input_data"]
18
+ input_type = domain_panel["input_type"]
19
+ description = domain_panel["description"]
20
+ mode = domain_panel.get("mode")
21
+ domain_kwargs = domain_panel.get("domain_kwargs", {})
22
+
23
+ st.markdown("---")
24
+ st.markdown("### Category Extraction Options")
25
+
26
+ max_categories = st.slider("Number of Categories to Extract", min_value=3, max_value=25, value=12)
27
+ specificity = st.selectbox("Specificity", options=["Broad", "Moderate", "Narrow"], index=0)
28
+ focus = st.text_input("Focus (optional)", placeholder="e.g., 'emotional responses'", key="extract_focus")
29
+
30
+ st.markdown("### Model Selection")
31
+ model, api_key, model_source, key_error = render_single_model_selector(key_prefix="extract_standalone_")
32
+
33
+ if st.button("Extract Categories", type="primary", use_container_width=True):
34
+ if input_data is None:
35
+ st.error("Please upload data first")
36
+ return
37
+
38
+ if key_error:
39
+ st.error(key_error)
40
+ return
41
+ tracker = ProgressTracker("Extracting categories")
42
+
43
+ extract_fn = get_callable(domain_id, "extract")
44
+ if extract_fn is None:
45
+ st.error(f"Extract not available for domain '{domain_id}'")
46
+ return
47
+
48
+ items_list = input_data if isinstance(input_data, list) else [input_data]
49
+ num_items = len(items_list)
50
+ divisions = max(1, min(5, num_items // 15))
51
+
52
+ extract_kwargs = {
53
+ "input_data": items_list,
54
+ "api_key": api_key,
55
+ "input_type": input_type,
56
+ "description": description,
57
+ "user_model": model,
58
+ "model_source": model_source,
59
+ "max_categories": int(max_categories),
60
+ "specificity": specificity.lower(),
61
+ "progress_callback": tracker.get_callback(),
62
+ }
63
+ if mode:
64
+ extract_kwargs["mode"] = mode
65
+ if focus and focus.strip():
66
+ extract_kwargs["focus"] = focus.strip()
67
+ extract_kwargs.update(domain_kwargs)
68
+
69
+ try:
70
+ extract_result = extract_fn(**extract_kwargs)
71
+ categories = extract_result.get("top_categories", [])
72
+ processing_time = time.time() - tracker.start_time
73
+ tracker.complete(f"Completed in {processing_time:.1f}s")
74
+
75
+ code = generate_extract_code(
76
+ domain_id, input_type, description, model, model_source,
77
+ int(max_categories), mode=mode, domain_kwargs=domain_kwargs,
78
+ )
79
+
80
+ st.session_state.results = {
81
+ "categories": categories,
82
+ "counts_df": extract_result.get("counts_df"),
83
+ "code": code,
84
+ "task_type": "extract",
85
+ }
86
+ st.success(f"Extracted {len(categories)} categories in {processing_time:.1f}s")
87
+ st.rerun()
88
+
89
+ except Exception as e:
90
+ st.error(f"Error: {str(e)}")
functions/summarize_page.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Summarize function page: focus, max_length, instructions, run + results.
3
+ """
4
+
5
+ import os
6
+ import sys
7
+ import time
8
+ import tempfile
9
+ import pandas as pd
10
+ import streamlit as st
11
+
12
+ import catllm
13
+ from config import render_single_model_selector, get_model_source
14
+ from components.progress import ProgressTracker
15
+ from components.reports import generate_methodology_report_pdf
16
+ from components.code_generation import generate_summarize_code
17
+ from components.results_display import render_summarize_results
18
+ from components.file_upload import count_pdf_pages
19
+ from domains.registry import get_callable
20
+
21
+
22
+ def render(domain_id, domain_panel):
23
+ """Render the summarize function page."""
24
+ input_data = domain_panel["input_data"]
25
+ input_type = domain_panel["input_type"]
26
+ description = domain_panel["description"]
27
+ original_filename = domain_panel["original_filename"]
28
+ mode = domain_panel.get("mode")
29
+ domain_kwargs = domain_panel.get("domain_kwargs", {})
30
+
31
+ st.markdown("---")
32
+ st.markdown("### Summarization Options")
33
+
34
+ focus = st.text_input("Focus (optional)", placeholder="e.g., 'main arguments', 'key findings'")
35
+ max_length = st.number_input("Max Summary Length (words, 0=no limit)", min_value=0, max_value=1000, value=0)
36
+ max_length = max_length if max_length > 0 else None
37
+ instructions = st.text_input("Additional Instructions (optional)", placeholder="e.g., 'use bullet points'")
38
+
39
+ # Policy-specific: format and tone
40
+ format_val = None
41
+ tone_val = None
42
+ if domain_id == "policy":
43
+ format_val = st.selectbox("Format", options=["paragraph", "bullets", "one-liner", "structured", "report"], key="policy_format")
44
+ tone_val = st.selectbox("Tone", options=["eli5", "legal"], key="policy_tone")
45
+ domain_kwargs["format"] = format_val
46
+ domain_kwargs["tone"] = tone_val
47
+
48
+ st.markdown("### Model Selection")
49
+ model, api_key, model_source, key_error = render_single_model_selector(key_prefix="summarize_")
50
+
51
+ if st.button("Summarize Data", type="primary", use_container_width=True):
52
+ if input_data is None:
53
+ st.error("Please upload data first")
54
+ return
55
+
56
+ if key_error:
57
+ st.error(key_error)
58
+ return
59
+ items_list = input_data if isinstance(input_data, list) else [input_data]
60
+ tracker = ProgressTracker("Processing item")
61
+
62
+ summarize_fn = get_callable(domain_id, "summarize")
63
+ if summarize_fn is None:
64
+ st.error(f"Summarize not available for domain '{domain_id}'")
65
+ return
66
+
67
+ summarize_kwargs = {
68
+ "input_data": items_list,
69
+ "api_key": api_key,
70
+ "description": description,
71
+ "user_model": model,
72
+ "model_source": model_source,
73
+ "progress_callback": tracker.get_callback(),
74
+ }
75
+ if mode:
76
+ summarize_kwargs["mode"] = mode
77
+ if focus and focus.strip():
78
+ summarize_kwargs["focus"] = focus.strip()
79
+ if max_length:
80
+ summarize_kwargs["max_length"] = max_length
81
+ if instructions and instructions.strip():
82
+ summarize_kwargs["instructions"] = instructions.strip()
83
+ summarize_kwargs.update(domain_kwargs)
84
+
85
+ try:
86
+ start_time = time.time()
87
+ result_df = summarize_fn(**summarize_kwargs)
88
+ processing_time = time.time() - start_time
89
+ tracker.complete(f"Completed {len(result_df)} items in {processing_time:.1f}s")
90
+
91
+ # Replace temp PDF paths
92
+ if input_type == "pdf" and "pdf_path" in result_df.columns:
93
+ pdf_name_map = st.session_state.get("pdf_name_map", {})
94
+ def replace_temp_path(val):
95
+ if pd.isna(val):
96
+ return val
97
+ val_str = str(val)
98
+ for temp_path, orig_name in pdf_name_map.items():
99
+ if temp_path in val_str:
100
+ return val_str.replace(temp_path, orig_name + ".pdf")
101
+ return val_str
102
+ result_df["pdf_path"] = result_df["pdf_path"].apply(replace_temp_path)
103
+
104
+ # Save CSV
105
+ with tempfile.NamedTemporaryFile(mode="w", suffix="_summarized.csv", delete=False) as f:
106
+ result_df.to_csv(f.name, index=False)
107
+ csv_path = f.name
108
+
109
+ # Success rate
110
+ if "processing_status" in result_df.columns:
111
+ success_rate = (result_df["processing_status"] == "success").sum() / len(result_df) * 100
112
+ else:
113
+ success_rate = 100.0
114
+
115
+ catllm_version = getattr(catllm, "__version__", "unknown")
116
+ python_version = sys.version.split()[0]
117
+
118
+ # Report
119
+ pdf_path = generate_methodology_report_pdf(
120
+ task_type="summarize", model=model, column_name=description,
121
+ num_rows=len(result_df), model_source=model_source,
122
+ filename=original_filename, success_rate=success_rate,
123
+ result_df=result_df, processing_time=processing_time,
124
+ catllm_version=catllm_version, python_version=python_version,
125
+ input_type=input_type, description=description, domain=domain_id,
126
+ focus=focus if focus else None, max_length=max_length,
127
+ )
128
+
129
+ # Code
130
+ code = generate_summarize_code(
131
+ domain_id, input_type, description, model, model_source,
132
+ focus=focus if focus else None, max_length=max_length,
133
+ instructions=instructions if instructions else None, mode=mode,
134
+ domain_kwargs=domain_kwargs,
135
+ )
136
+
137
+ st.session_state.results = {
138
+ "df": result_df,
139
+ "csv_path": csv_path,
140
+ "pdf_path": pdf_path,
141
+ "code": code,
142
+ "status": f"Summarized {len(result_df)} items in {processing_time:.1f}s",
143
+ "task_type": "summarize",
144
+ }
145
+ st.success(f"Summarized {len(result_df)} items in {processing_time:.1f}s")
146
+ st.rerun()
147
+
148
+ except Exception as e:
149
+ st.error(f"Error: {str(e)}")
requirements.txt CHANGED
@@ -1,12 +1,8 @@
1
  streamlit>=1.32.0
2
- cat-llm[pdf]>=2.3.4
3
- mistralai
4
- pydantic==2.10.6
5
- huggingface_hub<0.27.0
6
  pandas
7
  openpyxl
8
  requests
9
- regex
10
  reportlab
11
  matplotlib
12
  Pillow
 
1
  streamlit>=1.32.0
2
+ cat-llm[pdf]>=3.0.0
 
 
 
3
  pandas
4
  openpyxl
5
  requests
 
6
  reportlab
7
  matplotlib
8
  Pillow
session.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Session state initialization and reset helpers.
3
+ """
4
+
5
+ import streamlit as st
6
+ from config import MAX_CATEGORIES, INITIAL_CATEGORIES
7
+
8
+
9
+ def init_session_state():
10
+ """Initialize all session state keys with defaults."""
11
+ defaults = {
12
+ # Navigation
13
+ "domain": "general",
14
+ "function": "classify",
15
+ # API keys (persisted across domain/function switches)
16
+ "api_keys": {},
17
+ # Classify state
18
+ "categories": [""] * MAX_CATEGORIES,
19
+ "category_count": INITIAL_CATEGORIES,
20
+ "task_mode": None,
21
+ "extracted_categories": None,
22
+ "extraction_params": None,
23
+ "ensemble_num_runs": 3,
24
+ # Data
25
+ "survey_data": None,
26
+ "pdf_data": None,
27
+ "image_data": None,
28
+ "example_loaded": False,
29
+ "pdf_name_map": {},
30
+ # Results
31
+ "results": None,
32
+ # UI
33
+ "show_code_modal": False,
34
+ }
35
+ for key, value in defaults.items():
36
+ if key not in st.session_state:
37
+ st.session_state[key] = value
38
+
39
+
40
+ def reset_results():
41
+ """Clear results and related state."""
42
+ st.session_state.results = None
43
+ st.session_state.show_code_modal = False
44
+
45
+
46
+ def reset_all():
47
+ """Full reset of all working state."""
48
+ st.session_state.categories = [""] * MAX_CATEGORIES
49
+ st.session_state.category_count = INITIAL_CATEGORIES
50
+ st.session_state.task_mode = None
51
+ st.session_state.extracted_categories = None
52
+ st.session_state.extraction_params = None
53
+ st.session_state.results = None
54
+ st.session_state.show_code_modal = False
55
+ st.session_state.example_loaded = False
56
+ st.session_state.pdf_name_map = {}