dpaul93 commited on
Commit
9bca876
·
verified ·
1 Parent(s): 713c265

Update journal_utils.py

Browse files
Files changed (1) hide show
  1. journal_utils.py +63 -55
journal_utils.py CHANGED
@@ -1,73 +1,81 @@
1
- import json, os
2
- import markdown2
3
- import matplotlib.pyplot as plt
4
- from fpdf import FPDF
5
  from datetime import datetime
6
  from collections import Counter
 
 
7
 
8
- LOG_FILE = "journal_log.json"
9
-
10
- def log_entry(data):
11
- if os.path.exists(LOG_FILE):
12
- with open(LOG_FILE, "r") as f:
13
- logs = json.load(f)
14
- else:
15
- logs = []
16
-
17
  logs.append({
18
  "timestamp": datetime.utcnow().isoformat(),
19
- "mood": data["mood"],
20
- "mode": data["mode"],
21
- "entry": data["entry"],
22
- "response": data["response"]
23
  })
 
24
 
25
- with open(LOG_FILE, "w") as f:
26
- json.dump(logs, f, indent=2)
 
 
 
 
 
 
 
 
27
 
28
- def export_to_pdf(data, filename="journal_export.pdf"):
 
29
  pdf = FPDF()
30
  pdf.add_page()
31
  pdf.set_font("Arial", size=12)
32
- for k, v in data.items():
33
- pdf.multi_cell(0, 10, f"{k.upper()}:\n{v}\n", align="L")
34
- pdf.output(filename)
35
- return filename
36
 
37
- def export_to_md(data, filename="journal_export.md"):
38
- md_content = ""
39
- for k, v in data.items():
40
- md_content += f"### {k}\n{v}\n\n"
41
- with open(filename, "w") as f:
42
- f.write(md_content)
43
- return filename
 
 
 
 
 
 
 
 
 
 
44
 
45
  def generate_emotion_map():
46
- if not os.path.exists(LOG_FILE): return None
47
- with open(LOG_FILE, "r") as f:
48
  logs = json.load(f)
 
 
 
 
 
 
49
 
50
- mood_counts = Counter([log["mood"] for log in logs])
51
- moods = list(mood_counts.keys())
52
- counts = list(mood_counts.values())
53
-
54
- plt.figure(figsize=(6,4))
55
- plt.bar(moods, counts)
56
- plt.title("Weekly Mood Map")
57
- plt.xlabel("Mood")
58
- plt.ylabel("Frequency")
59
- plt.savefig("emotion_map.png")
60
- return "emotion_map.png"
61
-
62
- def get_weekly_summary():
63
- if not os.path.exists(LOG_FILE): return "No data available."
64
- with open(LOG_FILE, "r") as f:
65
- logs = json.load(f)[-7:] # Last 7 entries
66
-
67
  insights = {
68
- "Total Entries": len(logs),
69
- "Mood Distribution": Counter([log["mood"] for log in logs]),
70
- "Frequent Words": Counter(" ".join([log["entry"] for log in logs]).split()).most_common(5)
 
71
  }
72
-
73
- return insights
 
1
+ import os, json
 
 
 
2
  from datetime import datetime
3
  from collections import Counter
4
+ from fpdf import FPDF
5
+ import matplotlib.pyplot as plt
6
 
7
+ # --- Logging ---
8
+ def log_chat_interaction(user_msg, ai_reply, mood):
9
+ file = "chat_log.json"
10
+ logs = []
11
+ if os.path.exists(file):
12
+ with open(file) as f: logs = json.load(f)
 
 
 
13
  logs.append({
14
  "timestamp": datetime.utcnow().isoformat(),
15
+ "mood": mood,
16
+ "user": user_msg,
17
+ "ai": ai_reply
 
18
  })
19
+ with open(file, "w") as f: json.dump(logs, f, indent=2)
20
 
21
+ def log_entry(entry_obj):
22
+ file = "journal_log.json"
23
+ logs = []
24
+ if os.path.exists(file):
25
+ with open(file) as f: logs = json.load(f)
26
+ logs.append({
27
+ **entry_obj,
28
+ "timestamp": datetime.utcnow().isoformat()
29
+ })
30
+ with open(file, "w") as f: json.dump(logs, f, indent=2)
31
 
32
+ # --- Export ---
33
+ def export_to_pdf(entry, mood, mode):
34
  pdf = FPDF()
35
  pdf.add_page()
36
  pdf.set_font("Arial", size=12)
37
+ pdf.multi_cell(0, 10, f"Journaling Mode: {mode}\nMood: {mood}\nEntry:\n{entry}")
38
+ path = "journal_export.pdf"
39
+ pdf.output(path)
40
+ return path
41
 
42
+ def export_to_md(entry, mood, mode):
43
+ text = f"### Journal Entry\n**Mode**: {mode}\n**Mood**: {mood}\n\n{entry}"
44
+ path = "journal_export.md"
45
+ with open(path, "w") as f: f.write(text)
46
+ return path
47
+
48
+ # --- Counselor Analytics ---
49
+ def get_weekly_summary():
50
+ if not os.path.exists("journal_log.json"):
51
+ return {"error": "No logs yet."}
52
+ with open("journal_log.json") as f:
53
+ logs = json.load(f)[-7:]
54
+ return {
55
+ "total_entries": len(logs),
56
+ "mood_trend": Counter(x["mood"] for x in logs),
57
+ "frequent_words": Counter(" ".join(x["entry"] for x in logs).split()).most_common(7)
58
+ }
59
 
60
  def generate_emotion_map():
61
+ if not os.path.exists("journal_log.json"): return None
62
+ with open("journal_log.json") as f:
63
  logs = json.load(f)
64
+ moods = [x["mood"] for x in logs]
65
+ mood_count = Counter(moods)
66
+ plt.bar(mood_count.keys(), mood_count.values())
67
+ plt.title("Mood Trend")
68
+ plt.savefig("assets/emotion_map.png")
69
+ return "assets/emotion_map.png"
70
 
71
+ def get_counselor_view():
72
+ if not os.path.exists("journal_log.json"): return "No logs yet."
73
+ with open("journal_log.json") as f:
74
+ logs = json.load(f)
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  insights = {
76
+ "Total Journals": len(logs),
77
+ "Mood Counts": Counter(x["mood"] for x in logs),
78
+ "Flags (e.g., 'hopeless')": sum("hopeless" in x["entry"].lower() for x in logs),
79
+ "Flags (e.g., 'tired')": sum("tired" in x["entry"].lower() for x in logs)
80
  }
81
+ return "\n".join([f"{k}: {v}" for k, v in insights.items()])