bichnhan2701 commited on
Commit
e762958
·
1 Parent(s): d2bb844

Update redis

Browse files
app/config/settings.py CHANGED
@@ -27,3 +27,6 @@ HTTPX_TIMEOUT = float(os.getenv("HTTPX_TIMEOUT", "10.0"))
27
 
28
  # Redis URL
29
  REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
 
 
 
 
27
 
28
  # Redis URL
29
  REDIS_URL = os.getenv("REDIS_URL", "redis://localhost:6379/0")
30
+ REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
31
+ REDIS_PORT = int(os.getenv("REDIS_PORT", "6379"))
32
+ REDIS_DB = int(os.getenv("REDIS_DB", "0"))
app/infra/redis_client.py CHANGED
@@ -1,8 +1,22 @@
 
 
 
 
 
 
 
 
 
1
  import os
2
  import redis
3
- from app.config.settings import REDIS_URL
 
4
 
5
- redis_client = redis.Redis.from_url(
6
- REDIS_URL,
7
- decode_responses=True
8
- )
 
 
 
 
 
1
+ # import os
2
+ # import redis
3
+ # from app.config.settings import REDIS_URL
4
+
5
+ # redis_client = redis.Redis.from_url(
6
+ # REDIS_URL,
7
+ # decode_responses=True
8
+ # )
9
+
10
  import os
11
  import redis
12
+ from app.config.settings import REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_URL
13
+
14
 
15
+ if REDIS_URL:
16
+ redis_client = redis.from_url(REDIS_URL)
17
+ else:
18
+ redis_client = redis.Redis(
19
+ host=REDIS_HOST,
20
+ port=REDIS_PORT,
21
+ db=REDIS_DB,
22
+ )
app/services/nlp_postprocess.py CHANGED
@@ -5,6 +5,74 @@ import google.generativeai as genai
5
  import asyncio
6
  import json
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  CACHE_TTL = 60 * 60 * 24 * 3 # 3 days
9
 
10
  if GEMINI_API_KEY:
@@ -13,7 +81,6 @@ if GEMINI_API_KEY:
13
  else:
14
  _model = None
15
 
16
-
17
  async def normalize_and_extract(raw_text: str) -> dict:
18
  """
19
  return {
@@ -22,9 +89,15 @@ async def normalize_and_extract(raw_text: str) -> dict:
22
  }
23
  """
24
  cache_key = f"nlp:{sha256(raw_text)}"
25
- cached = redis_client.get(cache_key)
26
- if cached:
27
- return json.loads(cached)
 
 
 
 
 
 
28
 
29
  prompt = f"""
30
  Bạn là một hệ thống Xử lý Hậu kỳ NLP (NLP Post-Processing) Tiếng Việt.
@@ -43,11 +116,13 @@ Cấu trúc JSON bắt buộc:
43
  }}
44
  """
45
 
 
46
  result = {
47
  "normalized_text": raw_text,
48
  "keywords": []
49
  }
50
 
 
51
  if _model:
52
  loop = asyncio.get_event_loop()
53
 
@@ -61,11 +136,19 @@ Cấu trúc JSON bắt buộc:
61
  start = text.find("{")
62
  end = text.rfind("}")
63
  if start != -1 and end != -1:
64
- data = json.loads(text[start:end+1])
65
- result = {
66
- "normalized_text": data.get("normalizedText", raw_text),
67
- "keywords": data.get("keywords", [])
68
- }
 
 
 
 
 
 
 
 
 
69
 
70
- redis_client.setex(cache_key, CACHE_TTL, json.dumps(result))
71
  return result
 
5
  import asyncio
6
  import json
7
 
8
+ # CACHE_TTL = 60 * 60 * 24 * 3 # 3 days
9
+
10
+ # if GEMINI_API_KEY:
11
+ # genai.configure(api_key=GEMINI_API_KEY)
12
+ # _model = genai.GenerativeModel("gemini-pro")
13
+ # else:
14
+ # _model = None
15
+
16
+
17
+ # async def normalize_and_extract(raw_text: str) -> dict:
18
+ # """
19
+ # return {
20
+ # "normalized_text": "...",
21
+ # "keywords": [...]
22
+ # }
23
+ # """
24
+ # cache_key = f"nlp:{sha256(raw_text)}"
25
+ # cached = redis_client.get(cache_key)
26
+ # if cached:
27
+ # return json.loads(cached)
28
+
29
+ # prompt = f"""
30
+ # Bạn là một hệ thống Xử lý Hậu kỳ NLP (NLP Post-Processing) Tiếng Việt.
31
+
32
+ # Đầu vào là văn bản thô (raw transcript), có thể thiếu dấu câu và sai chính tả do nhận dạng giọng nói (ví dụ: 'ăn chứa' -> 'ăn chưa').
33
+
34
+ # Nhiệm vụ (Trả về JSON duy nhất):
35
+ # 1. [ASR Correction & Punctuation]: Sửa lỗi chính tả ASR, thêm dấu câu, viết hoa chuẩn xác.
36
+
37
+ # Văn bản đầu vào: \"\"\"{raw_text}\"\"\"
38
+
39
+ # Cấu trúc JSON bắt buộc:
40
+ # {{
41
+ # "normalizedText": "Văn bản đã sửa hoàn chỉnh...",
42
+ # "keywords": ["Từ khóa 1", "Từ khóa 2", "..."]
43
+ # }}
44
+ # """
45
+
46
+ # result = {
47
+ # "normalized_text": raw_text,
48
+ # "keywords": []
49
+ # }
50
+
51
+ # if _model:
52
+ # loop = asyncio.get_event_loop()
53
+
54
+ # def call():
55
+ # r = _model.generate_content(prompt)
56
+ # return r.text
57
+
58
+ # text = await loop.run_in_executor(None, call)
59
+
60
+ # # clean JSON
61
+ # start = text.find("{")
62
+ # end = text.rfind("}")
63
+ # if start != -1 and end != -1:
64
+ # data = json.loads(text[start:end+1])
65
+ # result = {
66
+ # "normalized_text": data.get("normalizedText", raw_text),
67
+ # "keywords": data.get("keywords", [])
68
+ # }
69
+
70
+ # redis_client.setex(cache_key, CACHE_TTL, json.dumps(result))
71
+ # return result
72
+
73
+ import logging
74
+ import redis # để bắt lỗi ConnectionError nếu cần
75
+
76
  CACHE_TTL = 60 * 60 * 24 * 3 # 3 days
77
 
78
  if GEMINI_API_KEY:
 
81
  else:
82
  _model = None
83
 
 
84
  async def normalize_and_extract(raw_text: str) -> dict:
85
  """
86
  return {
 
89
  }
90
  """
91
  cache_key = f"nlp:{sha256(raw_text)}"
92
+
93
+ # 1) Thử đọc cache từ Redis, nhưng không để lỗi Redis làm vỡ pipeline
94
+ try:
95
+ cached = redis_client.get(cache_key)
96
+ if cached:
97
+ return json.loads(cached)
98
+ except Exception as e:
99
+ logging.warning(f"Redis GET failed in normalize_and_extract, skip cache: {e}")
100
+
101
 
102
  prompt = f"""
103
  Bạn là một hệ thống Xử lý Hậu kỳ NLP (NLP Post-Processing) Tiếng Việt.
 
116
  }}
117
  """
118
 
119
+ # 2) Giá trị mặc định nếu không có model
120
  result = {
121
  "normalized_text": raw_text,
122
  "keywords": []
123
  }
124
 
125
+ # 3) Gọi Gemini nếu có cấu hình
126
  if _model:
127
  loop = asyncio.get_event_loop()
128
 
 
136
  start = text.find("{")
137
  end = text.rfind("}")
138
  if start != -1 and end != -1:
139
+ try:
140
+ data = json.loads(text[start:end + 1])
141
+ result = {
142
+ "normalized_text": data.get("normalizedText", raw_text),
143
+ "keywords": data.get("keywords", []),
144
+ }
145
+ except Exception as e:
146
+ logging.warning(f"Failed to parse Gemini JSON, fallback to raw_text: {e}")
147
+
148
+ # 4) Thử ghi cache lại, cũng không để lỗi Redis làm vỡ pipeline
149
+ try:
150
+ redis_client.setex(cache_key, CACHE_TTL, json.dumps(result))
151
+ except Exception as e:
152
+ logging.warning(f"Redis SETEX failed in normalize_and_extract, skip cache: {e}")
153
 
 
154
  return result