-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathanalyze_kolb_cyclus.py
More file actions
executable file
·276 lines (228 loc) · 9.22 KB
/
analyze_kolb_cyclus.py
File metadata and controls
executable file
·276 lines (228 loc) · 9.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
#!/usr/bin/env python3
#
# Dec 2025/Jan 2026 (w.m.otte@umcutrecht.nl)
#
# Analyse van preken aan de hand van Kolbs Leercyclus
# Gebaseerd op de homiletische toepassing door Kenton Anderson en Richard Osmer
#
#####################################################
import os
import json
import datetime
import re
import argparse
import google.generativeai as genai
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
def count_words(text):
"""
Count the actual number of words in the sermon text.
Returns the word count.
"""
words = text.split()
return len(words)
# Configuration
API_KEY = os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY")
DEFAULT_INPUT_FILE = "input/preek_01.txt"
PROMPT_FILE = "prompts/analyze_kolb_cyclus.md"
OUTPUT_DIR = "outputs"
def validate_input(text):
"""
Validates if the sermon text is substantial enough for Kolb analysis.
Checks for minimum length and basic structure.
"""
lines = text.split('\n')
non_empty_lines = [line for line in lines if line.strip()]
# Check minimum length (at least 50 non-empty lines for meaningful analysis)
if len(non_empty_lines) < 50:
raise ValueError(
f"Preektekst te kort voor Kolb-analyse. "
f"Gevonden: {len(non_empty_lines)} regels. Minimaal vereist: 50 regels."
)
# Count actual words
word_count = count_words(text)
if word_count < 500:
raise ValueError(
f"Preektekst te kort voor Kolb-analyse. "
f"Aantal woorden: {word_count}. Minimaal vereist: 500 woorden."
)
print(f"✓ Preektekst validatie geslaagd: {len(non_empty_lines)} regels, {word_count} woorden")
return word_count
def analyze_sermon_kolb(text, prompt_template, word_count):
"""
Calls Gemini API to analyze the sermon using Kolb's Learning Cycle framework.
"""
if not API_KEY:
raise ValueError("GOOGLE_API_KEY not found in environment variables.")
genai.configure(api_key=API_KEY)
# Use gemini-3.1-pro-preview for high quality analysis with strong reasoning
# This model is needed for the comprehensive analytical task
model = genai.GenerativeModel('gemini-3.1-pro-preview')
# Calculate estimated duration (100 words per minute)
estimated_duration = round(word_count / 100)
full_prompt = f"""{prompt_template}
--- BELANGRIJKE METADATA ---
Het exacte aantal woorden in deze preek is: {word_count}
Geschatte duur bij 100 woorden/minuut: {estimated_duration} minuten
Gebruik deze exacte waarden in je metadata sectie:
- "geschatte_woordlengte": {word_count}
- "geschatte_tijdsduur_minuten": {estimated_duration}
--- BEGIN PREEK ---
{text}
--- EINDE PREEK ---"""
print("📡 Versturen naar Gemini API voor analyse...")
print("⚙️ Dit kan 30-60 seconden duren vanwege de complexiteit van de analyse...")
response = model.generate_content(
full_prompt,
generation_config={
"response_mime_type": "application/json",
"temperature": 0.4, # Slightly lower for more consistent analytical output
}
)
return response.text
def save_output(input_filename, json_content, output_dir=OUTPUT_DIR):
"""
Saves the JSON content to the specified output directory.
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
base_name = os.path.splitext(os.path.basename(input_filename))[0]
output_filename = f"{output_dir}/{base_name}_kolb.json"
try:
# Ensure json_content is valid JSON string
parsed_json = json.loads(json_content)
# Calculate some statistics for confirmation
total_scores = []
if "kolb_fasen_analyse" in parsed_json:
for fase in parsed_json["kolb_fasen_analyse"].values():
if "score" in fase:
total_scores.append(fase["score"])
avg_score = sum(total_scores) / len(total_scores) if total_scores else 0
with open(output_filename, 'w', encoding='utf-8') as f:
json.dump(parsed_json, f, indent=2, ensure_ascii=False)
print(f"\n✅ Analyse succesvol opgeslagen: {output_filename}")
if avg_score > 0:
print(f"📊 Gemiddelde score Kolb-fasen: {avg_score:.1f}/10")
return output_filename
except json.JSONDecodeError as e:
print(f"❌ Error: content returned was not valid JSON: {e}")
# Save raw content for debugging
raw_filename = f"{output_filename}.raw"
with open(raw_filename, 'w', encoding='utf-8') as f:
f.write(json_content)
print(f"💾 Raw content saved for debugging: {raw_filename}")
return None
def print_summary(output_file):
"""
Prints a brief summary of the analysis results.
"""
try:
with open(output_file, 'r', encoding='utf-8') as f:
data = json.load(f)
print("\n" + "="*70)
print("📋 SAMENVATTING KOLB-ANALYSE")
print("="*70)
if "metadata" in data:
meta = data["metadata"]
if "titel_preek" in meta:
print(f"Preek: {meta['titel_preek']}")
if "bijbeltekst" in meta:
print(f"Tekst: {meta['bijbeltekst']}")
if "totaalbeeld" in data:
totaal = data["totaalbeeld"]
if "overall_kolb_score" in totaal:
score = totaal["overall_kolb_score"]
print(f"\n⭐ Overall Kolb Score: {score}/10")
if "primaire_homiletische_stijl" in totaal:
print(f"🎯 Primaire stijl: {totaal['primaire_homiletische_stijl']}")
if "primaire_leerstijl_aangesproken" in totaal:
print(f"🎓 Primaire leerstijl: {totaal['primaire_leerstijl_aangesproken']}")
# Print Kolb fase scores
if "kolb_fasen_analyse" in data:
print(f"\n📊 Scores per Kolb-fase:")
fase_namen = {
"fase_1_concrete_ervaring": "Concrete Ervaring (CE)",
"fase_2_reflectieve_observatie": "Reflectieve Observatie (RO)",
"fase_3_abstracte_conceptualisering": "Abstracte Conceptualisering (AC)",
"fase_4_actief_experimenteren": "Actief Experimenteren (AE)"
}
for key, naam in fase_namen.items():
if key in data["kolb_fasen_analyse"]:
score = data["kolb_fasen_analyse"][key].get("score", 0)
bar = "█" * score + "░" * (10 - score)
print(f" {naam:35s} {bar} {score}/10")
print("="*70 + "\n")
except Exception as e:
print(f"⚠️ Kon geen samenvatting genereren: {e}")
def main():
parser = argparse.ArgumentParser(
description="Analyseer een preek aan de hand van Kolbs Leercyclus en de homiletische toepassing door Anderson en Osmer.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Voorbeelden:
python analyze_kolb_cyclus.py
python analyze_kolb_cyclus.py --input input/mijn_preek.txt
python analyze_kolb_cyclus.py -i input/preek_02.txt
Deze tool analyseert de preek op:
• De 4 fasen van Kolb (CE, RO, AC, AE)
• De 4 structuren van Anderson (Declaratief, Pragmatisch, Narratief, Visionair)
• De 4 taken van Osmer (Descriptief, Interpretatief, Normatief, Pragmatisch)
• Welke leerstijlen worden aangesproken
• De integraliteit van de cyclus (Homiletic Window)
"""
)
parser.add_argument(
"-i", "--input",
type=str,
default=DEFAULT_INPUT_FILE,
help="Pad naar het inputbestand (.txt)"
)
parser.add_argument(
"--output-dir",
type=str,
default=OUTPUT_DIR,
help=f"Output directory voor JSON bestanden (default: {OUTPUT_DIR})"
)
parser.add_argument(
"--no-summary",
action="store_true",
help="Onderdruk de samenvatting in de console"
)
args = parser.parse_args()
input_file = args.input
output_dir = args.output_dir
print("="*70)
print("🔍 KOLB LEERCYCLUS ANALYSE VOOR HOMILETIEK")
print("="*70)
print(f"📖 Input bestand: {input_file}\n")
try:
# Read input file
with open(input_file, 'r', encoding='utf-8') as f:
sermon_text = f.read()
# Validate input
print("✓ Validatie wordt uitgevoerd...")
word_count = validate_input(sermon_text)
# Read prompt template
print("✓ Prompt template wordt geladen...")
with open(PROMPT_FILE, 'r', encoding='utf-8') as f:
prompt_template = f.read()
# Analyze with Gemini
print("✓ Analyse wordt gestart met Gemini AI...")
json_response = analyze_sermon_kolb(sermon_text, prompt_template, word_count)
# Save output
output_file = save_output(input_file, json_response, output_dir)
# Print summary
if output_file and not args.no_summary:
print_summary(output_file)
except FileNotFoundError as e:
print(f"❌ Bestand niet gevonden: {e}")
print(f" Zorg dat het bestand '{input_file}' bestaat.")
except ValueError as e:
print(f"❌ Validatie fout: {e}")
except Exception as e:
print(f"❌ Er is een onverwachte fout opgetreden: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()