File size: 11,940 Bytes
4b1a31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c1442ee
4b1a31e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323

import os
import pandas as pd
from datasets import load_dataset, Dataset, DatasetDict
from huggingface_hub import login
import logging
from typing import List, Optional, Dict, Any

from dotenv import load_dotenv

logger = logging.getLogger(__name__)

# Load envs
load_dotenv()
load_dotenv("../.env.local")

class DataService:
    def __init__(self):
        self.hf_token = os.getenv("HF_TOKEN")
        self.dataset_name = os.getenv("HF_DATASET_NAME")
        
        if not self.hf_token or not self.dataset_name:
            logger.error("HF_TOKEN or HF_DATASET_NAME not set via environment variables.")
            # We might want to raise an error here or handle it gracefully if running locally without HF
            # For now, we'll log error.
            
        if self.hf_token:
            login(token=self.hf_token)

        self.configs = ["files", "refined", "patterns", "results"]
        self.data: Dict[str, pd.DataFrame] = {}
        
        self._load_data()

    def _load_data(self):
        """Loads data from HF Hub for each config. Initializes empty if not found."""
        for config in self.configs:
            try:
                # trust_remote_code=True is sometimes needed, but for simple datasets usually not.
                # using split="train" by default as load_dataset returns a DatasetDict if split not specified
                ds = load_dataset(self.dataset_name, config, split="train")
                self.data[config] = ds.to_pandas()
                logger.info(f"Loaded config '{config}' with {len(self.data[config])} rows.")
            except Exception as e:
                logger.warning(f"Could not load config '{config}' from HF: {e}. Initializing empty.")
                self.data[config] = pd.DataFrame()

    def _save(self, config_name: str):
        """Pushes the specific config DataFrame to HF Hub."""
        if not self.hf_token or not self.dataset_name:
            logger.warning("Skipping save to HF: Credentials missing.")
            return

        try:
            df = self.data[config_name]
            # Convert DataFrame to Dataset
            ds = Dataset.from_pandas(df)
            # Push to hub
            # We need to preserve the columns.
            ds.push_to_hub(self.dataset_name, config_name=config_name, token=self.hf_token)
            logger.info(f"Saved config '{config_name}' to HF Hub.")
        except Exception as e:
            logger.error(f"Failed to save config '{config_name}': {e}")

    # --- Schema Helpers ---
    # These ensure we have the right columns even if empty

    def _ensure_columns(self, config, columns):
        if self.data[config].empty:
            self.data[config] = pd.DataFrame(columns=columns)
        else:
            # Add missing columns if any
            for col in columns:
                if col not in self.data[config].columns:
                    self.data[config][col] = None

    # --- File Operations ---

    def get_all_files(self) -> List[Dict[str, Any]]:
        if self.data["files"].empty:
            return []
        return self.data["files"].to_dict(orient="records")

    def get_file_content(self, file_id: str) -> Optional[str]:
        df = self.data["files"]
        if df.empty: return None
        row = df[df["file_id"] == file_id]
        if not row.empty:
            return row.iloc[0]["content"]
        return None

    def add_file(self, file_data: Dict[str, Any]):
        self._ensure_columns("files", ["file_id", "working_group", "meeting", "type", "status", "agenda_item", "content", "filename", "timestamp"])
        df = self.data["files"]
        
        # Check if exists
        if not df.empty:
             file_id = file_data["file_id"]
             df = df[df["file_id"] != file_id]
        
        # Add new row
        new_row = pd.DataFrame([file_data])
        self.data["files"] = pd.concat([df, new_row], ignore_index=True)
        self._save("files")

    # --- Refined Operations ---

    def get_refined_output(self, file_id: str) -> Optional[str]:
        df = self.data["refined"]
        if df.empty: return None
        row = df[df["file_id"] == file_id]
        if not row.empty:
            return row.iloc[0]["refined_output"]
        return None

    def add_refined(self, file_id: str, refined_output: str) -> int:
        self._ensure_columns("refined", ["refined_id", "refined_output", "file_id"])
        df = self.data["refined"]
        
        # Generate ID
        next_id = 1
        if not df.empty:
            # check max. If refined_id is not numeric (e.g. None), handle it.
            # Assuming it is numeric as per SQLite schema
            max_id = pd.to_numeric(df["refined_id"]).max()
            if not pd.isna(max_id):
                next_id = int(max_id) + 1
        
        new_row = pd.DataFrame([{
            "refined_id": next_id,
            "refined_output": refined_output,
            "file_id": file_id
        }])
        
        self.data["refined"] = pd.concat([df, new_row], ignore_index=True)
        self._save("refined")
        return next_id
    
    def get_refined_by_file_id(self, file_id: str):
        df = self.data["refined"]
        if df.empty: return None
        row = df[df["file_id"] == file_id]
        if not row.empty:
            return row.iloc[0].to_dict()
        return None

    # --- Pattern Operations ---

    def get_patterns(self) -> List[Dict[str, Any]]:
        if self.data["patterns"].empty:
            return []
        return self.data["patterns"].to_dict(orient="records")
    
    def get_pattern(self, pattern_id: int):
        df = self.data["patterns"]
        if df.empty: return None
        row = df[df["pattern_id"] == pattern_id]
        if not row.empty:
            return row.iloc[0].to_dict()
        return None

    def add_pattern(self, pattern_name: str, prompt: str) -> int:
        self._ensure_columns("patterns", ["pattern_id", "pattern_name", "prompt"])
        df = self.data["patterns"]
        
        next_id = 1
        if not df.empty:
            max_id = pd.to_numeric(df["pattern_id"]).max()
            if not pd.isna(max_id):
                next_id = int(max_id) + 1
        
        new_row = pd.DataFrame([{
            "pattern_id": next_id,
            "pattern_name": pattern_name,
            "prompt": prompt
        }])
        self.data["patterns"] = pd.concat([df, new_row], ignore_index=True)
        self._save("patterns")
        return next_id

    def update_pattern(self, pattern_id: int, pattern_name: str, prompt: str):
        df = self.data["patterns"]
        if df.empty: return False
        
        # Check if exists
        if pattern_id not in df["pattern_id"].values:
            return False
            
        # Update
        self.data["patterns"].loc[df["pattern_id"] == pattern_id, ["pattern_name", "prompt"]] = [pattern_name, prompt]
        self._save("patterns")
        return True

    # --- Result Operations ---

    def get_existing_result(self, file_id: str):
        """
        Equivalent to:
        SELECT ... FROM result r JOIN refined ref ... WHERE refined.file_id = ?
        """
        # First get refined_id for file_id
        ref_row = self.get_refined_by_file_id(file_id)
        file_df = self.data["files"]
        file_name = "Unknown File"
        if not file_df.empty:
            f_row = file_df[file_df["file_id"] == file_id]
            if not f_row.empty:
                file_name = f_row.iloc[0]["filename"]

        if not ref_row:
            return None, None, file_name
        
        refined_id = ref_row["refined_id"]
        
        # Search in results
        res_df = self.data["results"]
        if res_df.empty:
             return None, refined_id, file_name
        
        # Filter where refined_id matches
        # Note: result has refined_id
        match = res_df[res_df["refined_id"] == refined_id]
        
        if match.empty:
             return None, refined_id, file_name
             
        # Use the LAST result if multiple? Original SQL used simple join, usually implies 1-to-1 or fetchone
        # We'll take the first one or last one.
        result_row = match.iloc[-1].to_dict() # latest
        
        # Need pattern name
        pat_df = self.data["patterns"]
        pattern_name = "Unknown"
        if not pat_df.empty and "pattern_id" in result_row:
             pat_match = pat_df[pat_df["pattern_id"] == result_row["pattern_id"]]
             if not pat_match.empty:
                 pattern_name = pat_match.iloc[0]["pattern_name"]
        
        result_row["pattern_name"] = pattern_name
        # normalize keys to match what main.py expects (content vs result_content)
        # Main.py expects 'content' key for result_content
        result_row["content"] = result_row.get("result_content")
        
        return result_row, refined_id, file_name

    def add_result(self, pattern_id: int, refined_id: int, result_content: str, methodology: str, context: str, problem: str, classification: str = "UNCLASSIFIED") -> int:
        self._ensure_columns("results", ["result_id", "pattern_id", "refined_id", "result_content", "methodology", "context", "problem", "classification"])
        df = self.data["results"]
        
        next_id = 1
        if not df.empty:
             max_id = pd.to_numeric(df["result_id"]).max()
             if not pd.isna(max_id):
                 next_id = int(max_id) + 1
        
        new_row = pd.DataFrame([{
            "result_id": next_id,
            "pattern_id": pattern_id,
            "refined_id": refined_id,
            "result_content": result_content,
            "methodology": methodology,
            "context": context,
            "problem": problem,
            "classification": classification
        }])
        
        self.data["results"] = pd.concat([df, new_row], ignore_index=True)
        self._save("results")
        return next_id

    def update_classification(self, result_id: int, classification: str):
        df = self.data["results"]
        if df.empty: raise Exception("No results found")
        
        if result_id not in df["result_id"].values:
             return False
        
        self.data["results"].loc[df["result_id"] == result_id, "classification"] = classification
        self._save("results")
        return True

    def get_all_results_joined(self):
        """
        Joins results, refined, file, pattern
        """
        if self.data["results"].empty:
            return []
            
        res_df = self.data["results"].copy()
        
        # Join Patterns
        pat_df = self.data["patterns"]
        if not pat_df.empty:
            res_df = res_df.merge(pat_df[["pattern_id", "pattern_name"]], on="pattern_id", how="left")
            
        # Join Refined
        ref_df = self.data["refined"]
        if not ref_df.empty:
            res_df = res_df.merge(ref_df[["refined_id", "file_id"]], on="refined_id", how="left")
            
        # Join File
        def_file = self.data["files"]
        if not def_file.empty:
            res_df = res_df.merge(def_file[["file_id", "filename"]], on="file_id", how="left")
            
        # Select/Rename for output
        # Mappings based on API: id, file_name, content, classification, pattern_name, etc.
        out = []
        for _, row in res_df.iterrows():
            out.append({
                "id": row.get("result_id"),
                "file_name": row.get("filename"),
                "content": row.get("result_content"),
                "classification": row.get("classification"),
                "pattern_name": row.get("pattern_name"),
                "methodology": row.get("methodology"),
                "context": row.get("context"),
                "problem": row.get("problem")
            })
        # sort desc by id
        out.sort(key=lambda x: x["id"] or 0, reverse=True)
        return out