File size: 4,591 Bytes
419149e
 
 
bf6c190
 
419149e
bf6c190
 
 
419149e
11e1379
 
bf6c190
 
 
 
 
 
 
 
11e1379
853e66f
 
97c15d2
 
 
11e1379
bf6c190
11e1379
97c15d2
419149e
11e1379
 
bf6c190
 
 
 
 
 
 
 
11e1379
bf6c190
 
 
 
 
 
 
 
11e1379
bf6c190
 
 
11e1379
bf6c190
11e1379
 
97c15d2
 
11e1379
 
853e66f
419149e
 
97c15d2
419149e
11e1379
419149e
11e1379
 
853e66f
419149e
 
11e1379
 
 
853e66f
 
 
 
 
 
 
11e1379
419149e
 
97c15d2
 
11e1379
 
97c15d2
 
 
 
 
 
 
11e1379
 
 
419149e
 
11e1379
 
853e66f
11e1379
853e66f
97c15d2
11e1379
 
 
853e66f
11e1379
 
 
853e66f
11e1379
97c15d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
853e66f
 
11e1379
853e66f
 
 
 
 
 
97c15d2
853e66f
 
97c15d2
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
import json
import os
from datetime import datetime
from huggingface_hub import HfApi, hf_hub_download
import tempfile

HF_TOKEN = os.environ.get("HF_TOKEN")
DATASET_ID = "aysan98/empathy-interview-data"
FILENAME = "sessions.json"

def load_data():
    """Load complete data structure from HuggingFace Dataset"""
    try:
        filepath = hf_hub_download(
            repo_id=DATASET_ID,
            filename=FILENAME,
            repo_type="dataset",
            token=HF_TOKEN
        )
        with open(filepath, 'r', encoding='utf-8') as f:
            data = json.load(f)
            # Ensure structure
            if 'sessions' not in data:
                data = {'sessions': {}, 'analyses': {}}
            if 'analyses' not in data:
                data['analyses'] = {}
            return data
    except Exception as e:
        print(f"Error loading data: {e}")
        return {'sessions': {}, 'analyses': {}}

def save_data(data):
    """Save complete data structure to HuggingFace Dataset"""
    if not HF_TOKEN:
        print("Warning: No HF_TOKEN found")
        return
    
    try:
        api = HfApi()
        
        with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
            temp_path = f.name
        
        api.upload_file(
            path_or_fileobj=temp_path,
            path_in_repo=FILENAME,
            repo_id=DATASET_ID,
            repo_type="dataset",
            token=HF_TOKEN,
            commit_message=f"Update data - {datetime.now().isoformat()}"
        )
        
        os.remove(temp_path)
        print("Data saved successfully!")
    except Exception as e:
        print(f"Error saving data: {e}")

def add_session(session_id, questions, api_key, study_name):
    """Add a new session with study identifier"""
    data = load_data()
    
    data['sessions'][session_id] = {
        'questions': questions,
        'api_key': api_key,
        'study_name': study_name,
        'created_at': datetime.now().isoformat(),
        'responses': []
    }
    
    save_data(data)
    return data['sessions'][session_id]

def add_response(session_id, response_data):
    """Add a response to a session"""
    data = load_data()
    
    if session_id in data['sessions']:
        data['sessions'][session_id]['responses'].append({
            'timestamp': datetime.now().isoformat(),
            'data': response_data
        })
        save_data(data)
        return True
    
    return False

def update_global_analysis(analysis, study_name):
    """Update analysis for a specific study"""
    data = load_data()
    
    if 'analyses' not in data:
        data['analyses'] = {}
    
    data['analyses'][study_name] = {
        **analysis,
        'updated_at': datetime.now().isoformat()
    }
    
    save_data(data)
    return True

def get_session(session_id):
    """Get a specific session"""
    data = load_data()
    return data['sessions'].get(session_id, None)

def get_all_responses():
    """Get all responses from all sessions (deprecated - use get_responses_by_study)"""
    data = load_data()
    
    all_responses = []
    for session_id, session in data['sessions'].items():
        for response in session['responses']:
            all_responses.append(response['data'])
    
    return all_responses, len(data['sessions'])

def get_responses_by_study(study_name):
    """Get all responses for a specific study"""
    data = load_data()
    
    all_responses = []
    session_count = 0
    
    for session_id, session in data['sessions'].items():
        if session.get('study_name') == study_name:
            session_count += 1
            for response in session['responses']:
                all_responses.append(response['data'])
    
    return all_responses, session_count

def get_unique_studies():
    """Get list of all unique study names"""
    data = load_data()
    
    studies = set()
    for session_id, session in data['sessions'].items():
        study_name = session.get('study_name', 'Unnamed Study')
        studies.add(study_name)
    
    return sorted(list(studies))

def get_global_data():
    """Get complete global data for analysis"""
    data = load_data()
    
    total_sessions = len(data['sessions'])
    total_responses = sum(len(s['responses']) for s in data['sessions'].values())
    
    return {
        'sessions': data['sessions'],
        'analyses': data.get('analyses', {}),
        'total_sessions': total_sessions,
        'total_responses': total_responses
    }