File size: 2,460 Bytes
1636366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# utils/helper_functions.py

import time
import json
import csv
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import LabelEncoder

# Labeling logic
keywords_to_labels = {
    'advice': ['try', 'should', 'suggest', 'recommend'],
    'validation': ['understand', 'feel', 'valid', 'normal'],
    'information': ['cause', 'often', 'disorder', 'symptom'],
    'question': ['how', 'what', 'why', 'have you']
}

def auto_label_response(response):
    response = response.lower()
    for label, keywords in keywords_to_labels.items():
        if any(word in response for word in keywords):
            return label
    return 'information'

def build_prompt(user_input, response_type):
    prompts = {
        "advice": f"A patient said: \"{user_input}\". What advice should a mental health counselor give to support them?",
        "validation": f"A patient said: \"{user_input}\". How can a counselor validate and empathize with their emotions?",
        "information": f"A patient said: \"{user_input}\". Explain what might be happening from a mental health perspective.",
        "question": f"A patient said: \"{user_input}\". What thoughtful follow-up questions should a counselor ask?"
    }
    return prompts.get(response_type, prompts["information"])

def predict_response_type(user_input, model, vectorizer, label_encoder):
    vec = vectorizer.transform([user_input])
    pred = model.predict(vec)
    proba = model.predict_proba(vec).max()
    label = label_encoder.inverse_transform(pred)[0]
    return label, proba

def generate_llm_response(prompt, llm):
    start = time.time()
    result = llm(prompt, max_tokens=300, temperature=0.7)
    end = time.time()
    elapsed = round(end - start, 1)
    return result['choices'][0]['text'].strip(), elapsed

def trim_memory(history, max_turns=6):
    return history[-max_turns * 2:]

def save_conversation(history):
    timestamp = time.strftime("%Y%m%d-%H%M%S")
    file_name = f"chat_log_{timestamp}.csv"
    with open(file_name, "w", newline='') as f:
        writer = csv.writer(f)
        writer.writerow(["Role", "Content", "Intent", "Confidence"])
        for turn in history:
            writer.writerow([
                turn.get("role", ""),
                turn.get("content", ""),
                turn.get("label", ""),
                round(float(turn.get("confidence", 0)) * 100)
            ])
    print(f"Saved to {file_name}")
    return file_name