File size: 19,664 Bytes
87c7efb
6cf7b79
87c7efb
04b94fe
f0673f4
f29818e
800ed29
f0673f4
27e2bbc
e301855
ed22a9d
f0673f4
e2c66cd
f29818e
 
e2c66cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f29818e
536e6ec
f29818e
 
18aed9b
c45741c
 
18aed9b
 
c9bef70
 
 
c45741c
 
6cf7b79
18aed9b
b025fa7
 
 
 
 
 
 
 
 
 
e2c66cd
 
 
f29818e
 
 
af94b83
 
 
 
 
a9f7557
18aed9b
 
3b0e1c2
 
 
18aed9b
3b0e1c2
 
 
 
 
 
c45741c
 
c9bef70
c45741c
 
 
 
18aed9b
5372ec3
 
 
 
18aed9b
5372ec3
 
 
 
 
 
 
90bf65f
 
 
 
 
 
 
 
 
 
 
 
 
a9f7557
61608e4
 
a9f7557
 
 
 
87c7efb
61608e4
 
 
 
 
 
 
 
 
 
 
 
3a3a88f
 
 
 
 
 
 
 
87c7efb
3a3a88f
87c7efb
3a3a88f
 
 
 
 
 
 
 
 
 
 
 
 
27e2bbc
3a3a88f
27e2bbc
 
3a3a88f
 
ed22a9d
3a3a88f
 
 
 
 
 
27e2bbc
 
3a3a88f
 
6cf7b79
3a3a88f
 
87c7efb
3a3a88f
 
ed22a9d
87c7efb
6cf7b79
3a3a88f
87c7efb
 
3a3a88f
afdd8f3
87c7efb
afdd8f3
3a3a88f
 
87c7efb
3a3a88f
 
 
afdd8f3
 
 
 
 
87c7efb
 
 
 
3a3a88f
 
 
 
 
f0673f4
3a3a88f
 
87c7efb
 
3a3a88f
 
 
 
 
 
 
 
 
 
 
87c7efb
 
6cf7b79
3a3a88f
 
87c7efb
6cf7b79
 
13a429a
f29818e
3a3a88f
13a429a
87c7efb
 
 
3a3a88f
87c7efb
3a3a88f
 
6cf7b79
87c7efb
 
3a3a88f
 
87c7efb
 
27e2bbc
 
 
6cf7b79
27e2bbc
 
 
 
 
 
 
3a3a88f
 
 
 
 
27e2bbc
 
 
 
 
 
87c7efb
3a3a88f
 
87c7efb
3a3a88f
 
87c7efb
27e2bbc
3a3a88f
27e2bbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87c7efb
 
3a3a88f
87c7efb
3a3a88f
f0673f4
61608e4
8b54216
f0673f4
 
 
61608e4
3a3a88f
61608e4
 
 
 
 
8b54216
 
 
 
3a3a88f
f0673f4
6cf7b79
 
61608e4
 
 
 
8b54216
61608e4
6cf7b79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80b72e4
 
 
 
 
 
 
 
 
 
 
 
6cf7b79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2c66cd
 
 
 
8b54216
e2c66cd
6cf7b79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e301855
 
 
 
 
 
 
 
 
 
 
80b72e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0673f4
a9f7557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6cf7b79
 
a9f7557
6cf7b79
 
a9f7557
237655f
 
6cf7b79
237655f
 
 
 
 
 
 
 
 
 
 
 
 
6cf7b79
 
 
 
 
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
"""
Flare – ConfigProvider (TTS/STT support)
"""

from __future__ import annotations
import json, os
import threading
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from datetime import datetime
import commentjson
from utils import log
from pydantic import BaseModel, Field, HttpUrl, ValidationError, field_validator, validator
from encryption_utils import decrypt

# ---------------- Parameter Collection Config ---------
class ParameterCollectionConfig(BaseModel):
    """Configuration for smart parameter collection"""
    max_params_per_question: int = Field(default=2, ge=1, le=5)
    smart_grouping: bool = Field(default=True)
    retry_unanswered: bool = Field(default=True)
    collection_prompt: str = Field(default="""
You are a helpful assistant collecting information from the user.

Conversation context:
{{conversation_history}}

Intent: {{intent_name}} - {{intent_caption}}

Already collected:
{{collected_params}}

Still needed:
{{missing_params}}

Previously asked but not answered:
{{unanswered_params}}

Rules:
1. Ask for maximum {{max_params}} parameters in one question
2. Group parameters that naturally go together (like from/to cities, dates)
3. If some parameters were asked before but not answered, include them again
4. Be natural and conversational in {{project_language}}
5. Use context from the conversation to make the question flow naturally

Generate ONLY the question, nothing else.""")

    class Config:
        extra = "allow"

class GlobalConfig(BaseModel):
    work_mode: str = Field("hfcloud", pattern=r"^(hfcloud|cloud|on-premise|gpt4o|gpt4o-mini)$")
    cloud_token: Optional[str] = None
    spark_endpoint: HttpUrl
    internal_prompt: Optional[str] = None
    
    # TTS configurations
    tts_engine: str = Field("no_tts", pattern=r"^(no_tts|elevenlabs|blaze)$")
    tts_engine_api_key: Optional[str] = None
    tts_settings: Optional[Dict[str, Any]] = Field(default_factory=lambda: {
        "use_ssml": False
    })

    # STT configurations
    stt_engine: str = Field("no_stt", pattern=r"^(no_stt|google|azure|amazon|gpt4o_realtime|flicker)$")
    stt_engine_api_key: Optional[str] = None
    stt_settings: Optional[Dict[str, Any]] = Field(default_factory=lambda: {
        "speech_timeout_ms": 2000,
        "noise_reduction_level": 2,
        "vad_sensitivity": 0.5,
        "language": "tr-TR",
        "model": "latest_long",
        "use_enhanced": True,
        "enable_punctuation": True,
        "interim_results": True
    })

    parameter_collection_config: ParameterCollectionConfig = Field(default_factory=ParameterCollectionConfig)

    users: List["UserConfig"] = []

    def get_plain_token(self) -> Optional[str]:
        if self.cloud_token:
            # Lazy import to avoid circular dependency
            from encryption_utils import decrypt
            return decrypt(self.cloud_token)
        return None
    
    def get_tts_api_key(self) -> Optional[str]:
        """Get decrypted TTS API key"""
        raw_key = self.tts_engine_api_key
        
        if raw_key and raw_key.startswith("enc:"):
            from encryption_utils import decrypt
            decrypted = decrypt(raw_key)
            log(f"🔓 TTS key decrypted: {'***' + decrypted[-4:] if decrypted else 'None'}")
            return decrypted
        
        log(f"🔑 TTS key not encrypted: {'***' + raw_key[-4:] if raw_key else 'None'}")
        return raw_key

    def get_tts_settings(self) -> Dict[str, Any]:
        """Get TTS settings with defaults"""
        return self.tts_settings or {
            "use_ssml": False
        }

    def get_stt_api_key(self) -> Optional[str]:
        """Get decrypted STT API key or credentials path"""
        raw_key = self.stt_engine_api_key
        
        if raw_key and raw_key.startswith("enc:"):
            from encryption_utils import decrypt
            decrypted = decrypt(raw_key)
            log(f"🔓 STT key decrypted: {'***' + decrypted[-4:] if decrypted else 'None'}")
            return decrypted
        
        log(f"🔑 STT key/path: {'***' + raw_key[-4:] if raw_key else 'None'}")
        return raw_key
    
    def get_stt_settings(self) -> Dict[str, Any]:
        """Get STT settings with defaults"""
        return self.stt_settings or {
            "speech_timeout_ms": 2000,
            "noise_reduction_level": 2,
            "vad_sensitivity": 0.5,
            "language": "tr-TR",
            "model": "latest_long",
            "use_enhanced": True,
            "enable_punctuation": True,
            "interim_results": True
        }
        
    def is_cloud_mode(self) -> bool:
        """Check if running in cloud mode (anything except on-premise)"""
        return self.work_mode != "on-premise"
    
    def is_on_premise(self) -> bool:
        """Check if running in on-premise mode"""
        return self.work_mode == "on-premise"

    def is_gpt_mode(self) -> bool:
        """Check if running in GPT mode (any variant)"""
        return self.work_mode in ("gpt4o", "gpt4o-mini")
    
    def get_gpt_model(self) -> str:
        """Get the GPT model name for OpenAI API"""
        if self.work_mode == "gpt4o":
            return "gpt-4o"
        elif self.work_mode == "gpt4o-mini":
            return "gpt-4o-mini"
        return None

# ---------------- Global -----------------
class UserConfig(BaseModel):
    username: str
    password_hash: str
    salt: str


# ---------------- Retry / Proxy ----------
class RetryConfig(BaseModel):
    retry_count: int = Field(3, alias="max_attempts")
    backoff_seconds: int = 2
    strategy: str = Field("static", pattern=r"^(static|exponential)$")


class ProxyConfig(BaseModel):
    enabled: bool = True
    url: HttpUrl


# ---------------- API & Auth -------------
class APIAuthConfig(BaseModel):
    enabled: bool = False
    token_endpoint: Optional[HttpUrl] = None
    response_token_path: str = "access_token"
    token_request_body: Dict[str, Any] = Field({}, alias="body_template")
    token_refresh_endpoint: Optional[HttpUrl] = None
    token_refresh_body: Dict[str, Any] = {}

    class Config:
        extra = "allow"
        populate_by_name = True


class APIConfig(BaseModel):
    name: str
    url: HttpUrl
    method: str = Field("GET", pattern=r"^(GET|POST|PUT|PATCH|DELETE)$")
    headers: Dict[str, Any] = {}
    body_template: Dict[str, Any] = {}
    timeout_seconds: int = 10
    retry: RetryConfig = RetryConfig()
    proxy: Optional[str | ProxyConfig] = None
    auth: Optional[APIAuthConfig] = None
    response_prompt: Optional[str] = None

    class Config:
        extra = "allow"
        populate_by_name = True


# ---------------- Intent / Param ---------
class ParameterConfig(BaseModel):
    name: str
    caption: Optional[str] = ""
    type: str = Field(..., pattern=r"^(int|float|bool|str|string|date)$")  # Added 'date'
    required: bool = True
    variable_name: str
    extraction_prompt: Optional[str] = None
    validation_regex: Optional[str] = None
    invalid_prompt: Optional[str] = None
    type_error_prompt: Optional[str] = None

    def canonical_type(self) -> str:
        if self.type == "string":
            return "str"
        elif self.type == "date":
            return "str"  # Store dates as strings in ISO format
        return self.type


class IntentConfig(BaseModel):
    name: str
    caption: Optional[str] = ""
    locale: str = "tr-TR"
    dependencies: List[str] = []
    examples: List[str] = []
    detection_prompt: Optional[str] = None
    parameters: List[ParameterConfig] = []
    action: str
    fallback_timeout_prompt: Optional[str] = None
    fallback_error_prompt: Optional[str] = None

    class Config:
        extra = "allow"


# ---------------- Version / Project ------
class LLMConfig(BaseModel):
    repo_id: str
    generation_config: Dict[str, Any] = {}
    use_fine_tune: bool = False
    fine_tune_zip: str = ""


class VersionConfig(BaseModel):
    id: int = Field(..., alias="version_number")
    caption: Optional[str] = ""
    published: bool = False
    general_prompt: str
    llm: "LLMConfig"
    intents: List["IntentConfig"]

    class Config:
        extra = "allow"
        populate_by_name = True


class ProjectConfig(BaseModel):
    id: Optional[int] = None
    name: str
    caption: Optional[str] = ""
    enabled: bool = True
    last_version_number: Optional[int] = None
    versions: List[VersionConfig]

    class Config:
        extra = "allow"


# ---------------- Activity Log -----------
class ActivityLogEntry(BaseModel):
    timestamp: str
    username: str
    action: str
    entity_type: str
    entity_id: Optional[int] = None
    entity_name: Optional[str] = None
    details: Optional[str] = None


# ---------------- Service Config ---------
class ServiceConfig(BaseModel):
    global_config: GlobalConfig = Field(..., alias="config")
    projects: List[ProjectConfig]
    apis: List[APIConfig]
    activity_log: List[ActivityLogEntry] = []
    
    # Config level fields
    project_id_counter: int = 1
    last_update_date: Optional[str] = None
    last_update_user: Optional[str] = None

    # runtime helpers (skip validation)
    _api_by_name: Dict[str, APIConfig] = {}

    def build_index(self):
        self._api_by_name = {a.name: a for a in self.apis}

    def get_api(self, name: str) -> Optional[APIConfig]:
        return self._api_by_name.get(name)
    
    def to_jsonc_dict(self) -> dict:
        """Convert to dict for saving to JSONC file"""
        data = self.model_dump(by_alias=True, exclude={'_api_by_name'})
        
        # Convert API configs
        for api in data.get('apis', []):
            # Convert headers and body_template to JSON strings
            if 'headers' in api and isinstance(api['headers'], dict):
                api['headers'] = json.dumps(api['headers'], ensure_ascii=False)
            if 'body_template' in api and isinstance(api['body_template'], dict):
                api['body_template'] = json.dumps(api['body_template'], ensure_ascii=False)
            
            # Convert auth configs
            if 'auth' in api and api['auth']:
                if 'token_request_body' in api['auth'] and isinstance(api['auth']['token_request_body'], dict):
                    api['auth']['token_request_body'] = json.dumps(api['auth']['token_request_body'], ensure_ascii=False)
                if 'token_refresh_body' in api['auth'] and isinstance(api['auth']['token_refresh_body'], dict):
                    api['auth']['token_refresh_body'] = json.dumps(api['auth']['token_refresh_body'], ensure_ascii=False)
        
        return data
    
    def save(self):
        """Save configuration to file"""
        config_path = Path(__file__).parent / "service_config.jsonc"
        data = self.to_jsonc_dict()
        
        with open(config_path, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
        
        log("✅ Configuration saved to service_config.jsonc")


# ---------------- Provider Singleton -----
class ConfigProvider:
    _instance: Optional[ServiceConfig] = None
    _CONFIG_PATH = Path(__file__).parent / "service_config.jsonc"
    _lock = threading.Lock()  # Thread-safe access için lock
    _environment_checked = False  # Environment kontrolü için flag

    @classmethod
    def get(cls) -> ServiceConfig:
        """Get cached config - thread-safe"""
        if cls._instance is None:
            with cls._lock:
                # Double-checked locking pattern
                if cls._instance is None:
                    cls._instance = cls._load()
                    cls._instance.build_index()
                    # Environment kontrolünü sadece ilk yüklemede yap
                    if not cls._environment_checked:
                        cls._check_environment_setup()
                        cls._environment_checked = True
        return cls._instance

    @classmethod
    def reload(cls) -> ServiceConfig:
        """Force reload configuration from file - used after UI saves"""
        with cls._lock:
            log("🔄 Reloading configuration...")
            cls._instance = None
            # reload'da environment kontrolünü tekrar yapmıyoruz, flag'i reset etmiyoruz
            return cls.get()
    
    @classmethod
    def update_config(cls, config_dict: dict):
        """Update the current configuration with new values"""
        if cls._instance is None:
            cls.get()
        
        # Update global config
        if 'config' in config_dict:
            for key, value in config_dict['config'].items():
                if hasattr(cls._instance.global_config, key):
                    setattr(cls._instance.global_config, key, value)
        
        # Save to file
        cls._instance.save()

    @classmethod
    def _load(cls) -> ServiceConfig:
        """Load configuration from service_config.jsonc"""
        try:
            log(f"📂 Loading config from: {cls._CONFIG_PATH}")
            
            if not cls._CONFIG_PATH.exists():
                raise FileNotFoundError(f"Config file not found: {cls._CONFIG_PATH}")
            
            with open(cls._CONFIG_PATH, 'r', encoding='utf-8') as f:
                config_data = commentjson.load(f)
            
            # Ensure required fields exist in config data
            if 'config' not in config_data:
                config_data['config'] = {}
            
            config_section = config_data['config']
            
            # Set defaults for missing fields
            config_section.setdefault('work_mode', 'hfcloud')
            config_section.setdefault('spark_endpoint', 'http://localhost:7861')
            config_section.setdefault('cloud_token', None)
            config_section.setdefault('internal_prompt', None)
            config_section.setdefault('tts_engine', 'no_tts')
            config_section.setdefault('tts_engine_api_key', None)
            config_section.setdefault('tts_settings', {'use_ssml': False})
            config_section.setdefault('stt_engine', 'no_stt')
            config_section.setdefault('stt_engine_api_key', None)
            config_section.setdefault('stt_settings', {
                'speech_timeout_ms': 2000,
                'noise_reduction_level': 2,
                'vad_sensitivity': 0.5,
                'language': 'tr-TR',
                'model': 'latest_long',
                'use_enhanced': True,
                'enable_punctuation': True,
                'interim_results': True
            })

            pcc = config_data['config'].get('parameter_collection_config')
            if pcc is None:
                # Yoksa default değerlerle ekle
                config_data['config']['parameter_collection_config'] = ParameterCollectionConfig().model_dump()
            
            config_section.setdefault('users', [])
            
            # Convert string body/headers to dict if needed
            for api in config_data.get('apis', []):
                if isinstance(api.get('headers'), str):
                    try:
                        api['headers'] = json.loads(api['headers'])
                    except:
                        api['headers'] = {}
                
                if isinstance(api.get('body_template'), str):
                    try:
                        api['body_template'] = json.loads(api['body_template'])
                    except:
                        api['body_template'] = {}
                
                # Handle auth section
                if api.get('auth'):
                    auth = api['auth']
                    if isinstance(auth.get('token_request_body'), str):
                        try:
                            auth['token_request_body'] = json.loads(auth['token_request_body'])
                        except:
                            auth['token_request_body'] = {}
                    if isinstance(auth.get('token_refresh_body'), str):
                        try:
                            auth['token_refresh_body'] = json.loads(auth['token_refresh_body'])
                        except:
                            auth['token_refresh_body'] = {}
            
            # Fix activity_log entries if needed
            if 'activity_log' in config_data:
                for entry in config_data['activity_log']:
                    # Add missing username field
                    if 'username' not in entry:
                        entry['username'] = entry.get('user', 'system')
                    # Ensure all required fields exist
                    entry.setdefault('action', 'UNKNOWN')
                    entry.setdefault('entity_type', 'unknown')
                    entry.setdefault('timestamp', datetime.now().isoformat())
            
            # Create ServiceConfig instance
            service_config = ServiceConfig(**config_data)
            
            log("✅ Configuration loaded successfully")
            return service_config
            
        except FileNotFoundError as e:
            log(f"❌ Config file not found: {e}")
            raise
        except json.JSONDecodeError as e:
            log(f"❌ Invalid JSON in config file: {e}")
            raise
        except ValidationError as e:
            log(f"❌ Config validation error: {e}")
            raise
        except Exception as e:
            log(f"❌ Unexpected error loading config: {e}")
            raise
            
    @classmethod
    def _check_environment_setup(cls):
        """Check if environment is properly configured based on work_mode"""
        config = cls._instance.global_config
        
        if config.is_cloud_mode():
            # Cloud mode - check for HuggingFace Secrets
            missing_secrets = []
            
            if not os.getenv("JWT_SECRET"):
                missing_secrets.append("JWT_SECRET")
            if not os.getenv("FLARE_TOKEN_KEY"):
                missing_secrets.append("FLARE_TOKEN_KEY")
            if not os.getenv("SPARK_TOKEN"):
                missing_secrets.append("SPARK_TOKEN")
            
            if missing_secrets:
                log(f"⚠️ Running in {config.work_mode} mode. Missing secrets: {', '.join(missing_secrets)}")
                log("Please set these as HuggingFace Space Secrets for cloud deployment.")
        else:
            # On-premise mode - check for .env file
            env_path = Path(__file__).parent / ".env"
            if not env_path.exists():
                log("⚠️ Running in on-premise mode but .env file not found")
                # Docker ortamında yazma izni olmayabilir, sadece uyarı ver
                log("⚠️ Cannot create .env file in Docker environment. Using default values.")
                
                # Set default environment variables if not already set
                if not os.getenv("JWT_SECRET"):
                    os.environ["JWT_SECRET"] = "flare-admin-secret-key-change-in-production"
                if not os.getenv("JWT_ALGORITHM"):
                    os.environ["JWT_ALGORITHM"] = "HS256"
                if not os.getenv("JWT_EXPIRATION_HOURS"):
                    os.environ["JWT_EXPIRATION_HOURS"] = "24"
                if not os.getenv("FLARE_TOKEN_KEY"):
                    os.environ["FLARE_TOKEN_KEY"] = "flare-token-encryption-key"
                if not os.getenv("SPARK_TOKEN"):
                    os.environ["SPARK_TOKEN"] = "your-spark-token-here"
                
                log("✅ Default environment variables set.")

# Forward references
GlobalConfig.model_rebuild()
VersionConfig.model_rebuild()
ServiceConfig.model_rebuild()