moodjournaltracker / journal_utils.py
dpaul93's picture
Update journal_utils.py
6e6cce7 verified
import os, json
from datetime import datetime
from collections import Counter
from fpdf import FPDF
import matplotlib.pyplot as plt
import os
import matplotlib.pyplot as plt
from collections import Counter
# --- Logging ---
def log_chat_interaction(user_msg, ai_reply, mood):
file = "chat_log.json"
logs = []
if os.path.exists(file):
with open(file) as f: logs = json.load(f)
logs.append({
"timestamp": datetime.utcnow().isoformat(),
"mood": mood,
"user": user_msg,
"ai": ai_reply
})
with open(file, "w") as f: json.dump(logs, f, indent=2)
def log_entry(entry_obj):
file = "journal_log.json"
logs = []
if os.path.exists(file):
with open(file) as f: logs = json.load(f)
logs.append({
**entry_obj,
"timestamp": datetime.utcnow().isoformat()
})
with open(file, "w") as f: json.dump(logs, f, indent=2)
# --- Export ---
def export_to_pdf(entry, mood, mode):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.multi_cell(0, 10, f"Journaling Mode: {mode}\nMood: {mood}\nEntry:\n{entry}")
path = "journal_export.pdf"
pdf.output(path)
return path
def export_to_md(entry, mood, mode):
text = f"### Journal Entry\n**Mode**: {mode}\n**Mood**: {mood}\n\n{entry}"
path = "journal_export.md"
with open(path, "w") as f: f.write(text)
return path
# --- Counselor Analytics ---
def get_weekly_summary():
if not os.path.exists("journal_log.json"):
return {"error": "No logs yet."}
with open("journal_log.json") as f:
logs = json.load(f)[-7:]
return {
"total_entries": len(logs),
"mood_trend": Counter(x["mood"] for x in logs),
"frequent_words": Counter(" ".join(x["entry"] for x in logs).split()).most_common(7)
}
from collections import Counter
import json
import os
def get_counselor_view():
journal_entries = []
chat_entries = []
if os.path.exists("journal_log.json"):
with open("journal_log.json") as f:
journal_entries = json.load(f)
if os.path.exists("chat_log.json"):
with open("chat_log.json") as f:
chat_entries = json.load(f)
combined_texts = []
for j in journal_entries:
combined_texts.append(j["entry"])
combined_texts.append(j["response"])
for c in chat_entries:
combined_texts.append(c["user"])
combined_texts.append(c["ai"])
all_text = " ".join(combined_texts).lower()
keywords_of_concern = ["tired", "hopeless", "alone", "worthless", "angry", "burnout", "anxious"]
flags = {kw: all_text.count(kw) for kw in keywords_of_concern}
moods = [j["mood"] for j in journal_entries] + [c["mood"] for c in chat_entries]
mood_counts = Counter(moods)
return f"""
🧠 Counselor Dashboard Summary
πŸ“ Total Journal Entries: {len(journal_entries)}
πŸ’¬ Total Conversations: {len(chat_entries)}
πŸ“Š Mood Distribution:
{dict(mood_counts)}
⚠️ Flagged Terms Detected:
{flags}
🧩 Top Observations:
- Watch for spikes in fatigue, hopelessness, or anger.
- Consistent use of certain terms may suggest emotional load.
- Consider encouraging journaling, breathing, or referring to a professional if >3 flags occur.
"""
import os
import matplotlib.pyplot as plt
from collections import Counter
def generate_emotion_map():
if not os.path.exists("journal_log.json"):
return None
# βœ… Ensure the folder exists
os.makedirs("assets", exist_ok=True)
with open("journal_log.json") as f:
logs = json.load(f)
moods = [x["mood"] for x in logs]
mood_count = Counter(moods)
plt.figure(figsize=(6, 4))
plt.bar(mood_count.keys(), mood_count.values())
plt.title("Mood Trend")
plt.xlabel("Mood")
plt.ylabel("Frequency")
plt.tight_layout()
save_path = "assets/emotion_map.png"
plt.savefig(save_path)
plt.close()
return save_path