app.py 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  1. import os
  2. import pymysql
  3. import requests
  4. import json
  5. import re
  6. import threading
  7. import urllib3
  8. import fitz # PyMuPDF
  9. from flask import Flask, render_template, request, redirect, url_for, session, flash, jsonify, Response, stream_with_context
  10. from werkzeug.utils import secure_filename
  11. from oss_utils import upload_to_oss
  12. from ocr_utils import extract_page_number
  13. import time
  14. from datetime import datetime
  15. # Suppress InsecureRequestWarning
  16. urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  17. app = Flask(__name__, static_folder='static', static_url_path='/manager/static')
  18. app.secret_key = 'genealogy_secret_key'
  19. app.config['UPLOAD_FOLDER'] = 'uploads'
  20. os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
  21. # 数据库配置
  22. DB_CONFIG = {
  23. "host": "rm-f8ze60yirdj8786u2wo.mysql.rds.aliyuncs.com",
  24. "port": 3306,
  25. "user": "csqz",
  26. "password": "csqz@2026",
  27. "db": "csqz-client",
  28. "charset": "utf8mb4",
  29. "cursorclass": pymysql.cursors.DictCursor
  30. }
  31. from PIL import Image
  32. def compress_image_if_needed(file_path, max_dim=2000):
  33. """Compress, resize and normalize image to JPEG for AI processing."""
  34. try:
  35. # We always want to normalize to JPEG so AI doesn't complain about format
  36. with Image.open(file_path) as img:
  37. # Convert RGBA/P or any other mode to RGB for JPEG saving
  38. if img.mode != 'RGB':
  39. img = img.convert('RGB')
  40. width, height = img.size
  41. if max(width, height) > max_dim:
  42. ratio = max_dim / max(width, height)
  43. new_size = (int(width * ratio), int(height * ratio))
  44. img = img.resize(new_size, Image.Resampling.LANCZOS)
  45. # Always save as JPEG to normalize the format
  46. new_path = os.path.splitext(file_path)[0] + '_normalized.jpg'
  47. img.save(new_path, 'JPEG', quality=85)
  48. return new_path
  49. except Exception as e:
  50. print(f"Warning: Image compression/normalization failed for {file_path}: {e}")
  51. return file_path
  52. def get_db_connection():
  53. return pymysql.connect(**DB_CONFIG)
  54. def format_timestamp(ts):
  55. if not ts: return '未知'
  56. try:
  57. # 兼容秒和毫秒
  58. if ts > 10000000000: # 超过2286年的秒数,通常认为是毫秒
  59. ts = ts / 1000
  60. return time.strftime('%Y-%m-%d', time.localtime(ts))
  61. except:
  62. return '未知'
  63. def manual_simplify(text):
  64. """
  65. Simple fallback for common Traditional to Simplified conversion
  66. if AI fails to convert specific characters.
  67. """
  68. if not text: return text
  69. mapping = {
  70. '學': '学', '國': '国', '萬': '万', '寶': '宝', '興': '兴',
  71. '華': '华', '會': '会', '葉': '叶', '藝': '艺', '號': '号',
  72. '處': '处', '見': '见', '視': '视', '言': '言', '語': '语',
  73. '貝': '贝', '車': '车', '長': '长', '門': '门', '韋': '韦',
  74. '頁': '页', '風': '风', '飛': '飞', '食': '食', '馬': '马',
  75. '魚': '鱼', '鳥': '鸟', '麥': '麦', '黃': '黄', '齊': '齐',
  76. '齒': '齿', '龍': '龙', '龜': '龟', '壽': '寿', '榮': '荣',
  77. '愛': '爱', '慶': '庆', '衛': '卫', '賢': '贤', '義': '义',
  78. '禮': '礼', '樂': '乐', '靈': '灵', '滅': '灭', '氣': '气',
  79. '智': '智', '信': '信', '仁': '仁', '勇': '勇', '嚴': '严',
  80. '銳': '锐', '優': '优', '楊': '杨', '吳': '吴', '銀': '银'
  81. }
  82. result = ""
  83. for char in text:
  84. result += mapping.get(char, char)
  85. return result
  86. def clean_name(name):
  87. """
  88. Clean name according to Liu family genealogy rules:
  89. 1. If name is '学公' or '留学公', keep 'Gong' (exception).
  90. 2. Otherwise, if name ends with '公', remove '公'.
  91. 3. If name does not start with '留', prepend '留'.
  92. """
  93. if not name: return name
  94. name = name.strip()
  95. # Pre-process: Ensure Simplified Chinese for specific chars
  96. name = manual_simplify(name)
  97. # 1. Check exceptions (names that SHOULD keep 'Gong')
  98. exceptions = ['学公', '留学公']
  99. if name in exceptions:
  100. if not name.startswith('留'):
  101. name = '留' + name
  102. return name
  103. # 2. General Rule: Remove 'Gong' suffix
  104. if name.endswith('公'):
  105. name = name[:-1]
  106. # 3. Ensure 'Liu' surname
  107. if not name.startswith('留'):
  108. name = '留' + name
  109. return name
  110. def is_female_value(sex_value):
  111. """Return True when sex value represents female."""
  112. if sex_value is None:
  113. return False
  114. s = str(sex_value).strip().lower()
  115. return s in ('女', '2', 'female', 'f')
  116. def normalize_lookup_name(name):
  117. """Normalize names for loose matching in AI parsed content."""
  118. if not name:
  119. return ''
  120. return manual_simplify(str(name)).strip()
  121. def should_skip_liu_prefix_for_person(person, spouse_name_set):
  122. """
  123. Female spouse records should not auto-prepend '留' in simplified_name.
  124. We treat a person as female spouse if:
  125. 1) sex is female, and
  126. 2) has spouse_name field OR appears in another person's spouse_name list.
  127. """
  128. if not isinstance(person, dict):
  129. return False
  130. if not is_female_value(person.get('sex')):
  131. return False
  132. own_names = set()
  133. own_names.add(normalize_lookup_name(person.get('name')))
  134. own_names.add(normalize_lookup_name(person.get('original_name')))
  135. own_names.discard('')
  136. has_spouse_name = bool(normalize_lookup_name(person.get('spouse_name')))
  137. referenced_by_other = any(n in spouse_name_set for n in own_names)
  138. return has_spouse_name or referenced_by_other
  139. def get_normalized_base64_image(image_url):
  140. """Download image, normalize to JPEG, and return base64 data URI for AI payload."""
  141. import io
  142. import base64
  143. import requests
  144. from PIL import Image
  145. try:
  146. response = requests.get(image_url, timeout=30)
  147. response.raise_for_status()
  148. with Image.open(io.BytesIO(response.content)) as img:
  149. # Convert to RGB to ensure JPEG compatibility
  150. if img.mode != 'RGB':
  151. img = img.convert('RGB')
  152. # Resize if too large
  153. max_dim = 2000
  154. if max(img.width, img.height) > max_dim:
  155. ratio = max_dim / max(img.width, img.height)
  156. new_size = (int(img.width * ratio), int(img.height * ratio))
  157. img = img.resize(new_size, Image.Resampling.LANCZOS)
  158. # Save as JPEG in memory
  159. buffer = io.BytesIO()
  160. img.save(buffer, format='JPEG', quality=85)
  161. b64_str = base64.b64encode(buffer.getvalue()).decode('utf-8')
  162. return f"data:image/jpeg;base64,{b64_str}"
  163. except Exception as e:
  164. print(f"Error normalizing image from {image_url}: {e}")
  165. return image_url # Fallback to original URL if processing fails
  166. def process_ai_task(record_id, image_url):
  167. """Background task to process image with AI and store result."""
  168. print(f"[AI Task] Starting task for record {record_id}...")
  169. conn = get_db_connection()
  170. try:
  171. with conn.cursor() as cursor:
  172. cursor.execute("UPDATE genealogy_records SET ai_status = 1 WHERE id = %s", (record_id,))
  173. conn.commit()
  174. print(f"[AI Task] Status updated to 'Processing' for record {record_id}")
  175. api_key = "a1800657-9212-4afe-9b7c-b49f015c54d3"
  176. api_url = "https://ark.cn-beijing.volces.com/api/v3/responses"
  177. prompt = """
  178. 请分析这张家谱图片,提取其中关于人物的信息。
  179. 请务必将繁体字转换为简体字(original_name 字段除外)。
  180. 特别注意:'name' 字段必须是纯简体中文,不能包含繁体字(例如:'學'应转换为'学','劉'应转换为'刘','萬'应转换为'万')。
  181. 请提取以下字段(如果存在):
  182. - original_name: 原始姓名(严格保持图片上的繁体字,不做任何修改或转换)
  183. - name: 简体姓名(必须转换为简体中文,去除不需要的敬称)
  184. - sex: 性别(男/女)
  185. - birthday: 出生日期(尝试转换为YYYY-MM-DD格式,如果无法确定年份可只填月日)
  186. - death_date: 逝世日期(如文本中出现“殁”、“葬”、“卒”等字眼及其对应的时间,请提取)
  187. - father_name: 父亲姓名
  188. - spouse_name: 配偶姓名
  189. - generation: 第几世/代数
  190. - name_word: 字辈(例如名字为“学勤公”,“学”为字辈;提取名字中的字辈信息)
  191. - education: 学历/功名
  192. - title: 官职/称号
  193. 请严格以JSON列表格式返回,不要包含Markdown代码块标记(如 ```json ... ```),直接返回JSON数组。
  194. 如果包含多个人物,请都提取出来。
  195. Do not output any reasoning or explanation, just the JSON.
  196. """
  197. ai_payload_url = get_normalized_base64_image(image_url)
  198. payload = {
  199. "model": "doubao-seed-1-8-251228",
  200. "stream": True, # Streaming for robust handling
  201. "input": [
  202. {
  203. "role": "user",
  204. "content": [
  205. {"type": "input_image", "image_url": ai_payload_url},
  206. {"type": "input_text", "text": prompt}
  207. ]
  208. }
  209. ]
  210. }
  211. headers = {
  212. "Authorization": f"Bearer {api_key}",
  213. "Content-Type": "application/json"
  214. }
  215. max_retries = 3
  216. last_exception = None
  217. for attempt in range(max_retries):
  218. try:
  219. print(f"[AI Task] Attempt {attempt+1}/{max_retries} connecting to API for record {record_id}...")
  220. response = requests.post(
  221. api_url,
  222. json=payload,
  223. headers=headers,
  224. timeout=1200,
  225. stream=True,
  226. verify=False,
  227. proxies={"http": None, "https": None}
  228. )
  229. if response.status_code == 200:
  230. print(f"[AI Task] Connection established for record {record_id}, receiving stream...")
  231. full_content = ""
  232. for line in response.iter_lines():
  233. if not line: continue
  234. line_str = line.decode('utf-8')
  235. # Debug: Print full line to understand event flow
  236. print(f"[AI Task Debug] Raw Line: {line_str[:500]}") # Truncate very long lines
  237. if line_str.startswith('data: '):
  238. json_str = line_str[6:]
  239. if json_str.strip() == '[DONE]':
  240. print("[AI Task Debug] Received [DONE]")
  241. break
  242. try:
  243. chunk = json.loads(json_str)
  244. chunk_type = chunk.get('type')
  245. # Standard OpenAI format (choices)
  246. if 'choices' in chunk and len(chunk['choices']) > 0:
  247. delta = chunk['choices'][0].get('delta', {})
  248. if 'content' in delta:
  249. full_content += delta['content']
  250. # Doubao/Volcengine specific formats (delta)
  251. elif chunk_type == 'response.text.delta':
  252. full_content += chunk.get('delta', '')
  253. # Check response.completed if empty
  254. elif chunk_type == 'response.completed' and not full_content:
  255. output = chunk.get('response', {}).get('output', [])
  256. for item in output:
  257. # Also extract from reasoning if it contains JSON-like text
  258. if item.get('type') == 'reasoning':
  259. summary = item.get('summary', [])
  260. for sum_item in summary:
  261. if sum_item.get('type') == 'summary_text':
  262. full_content += sum_item.get('text', '')
  263. elif item.get('type') == 'message':
  264. content = item.get('content')
  265. if isinstance(content, str):
  266. full_content += content
  267. elif isinstance(content, list):
  268. for part in content:
  269. if isinstance(part, dict) and part.get('type') == 'text':
  270. full_content += part.get('text', '')
  271. # Fallback: output_item.added
  272. elif chunk_type == 'response.output_item.added':
  273. item = chunk.get('item', {})
  274. if item.get('role') == 'assistant':
  275. content_field = item.get('content', [])
  276. if isinstance(content_field, str):
  277. full_content += content_field
  278. elif isinstance(content_field, list):
  279. for part in content_field:
  280. if isinstance(part, dict) and part.get('type') == 'text':
  281. full_content += part.get('text', '')
  282. except Exception as e:
  283. print(f"[AI Task] Chunk parse error: {e}")
  284. else:
  285. # Fallback for non-SSE
  286. try:
  287. chunk = json.loads(line_str)
  288. if 'choices' in chunk and len(chunk['choices']) > 0:
  289. content = chunk['choices'][0]['message']['content']
  290. full_content += content
  291. except:
  292. pass
  293. print(f"[AI Task] Stream finished. Content length: {len(full_content)}")
  294. if len(full_content) == 0:
  295. print(f"[AI Task] WARNING: No content received from AI stream.")
  296. # Continue to JSON parse to fail gracefully
  297. # Clean JSON
  298. try:
  299. # 1. Try finding [...] array
  300. start = full_content.find('[')
  301. end = full_content.rfind(']')
  302. # 2. If not found, try finding {...} object and wrap it
  303. is_single_object = False
  304. if start == -1 or end == -1 or end <= start:
  305. start = full_content.find('{')
  306. end = full_content.rfind('}')
  307. is_single_object = True
  308. if start != -1 and end != -1 and end > start:
  309. content_clean = full_content[start:end+1]
  310. else:
  311. # Fallback to regex or raw
  312. content_clean = re.sub(r'^```json\s*', '', full_content)
  313. content_clean = re.sub(r'```$', '', content_clean)
  314. parsed = json.loads(content_clean)
  315. # Normalize single object to list
  316. if is_single_object and isinstance(parsed, dict):
  317. parsed = [parsed]
  318. content_clean = json.dumps(parsed, ensure_ascii=False)
  319. elif isinstance(parsed, dict) and not isinstance(parsed, list):
  320. # Just in case json.loads parsed a dict even if we looked for []
  321. parsed = [parsed]
  322. content_clean = json.dumps(parsed, ensure_ascii=False)
  323. # Build spouse name lookup for "female spouse" detection
  324. spouse_name_set = set()
  325. if isinstance(parsed, list):
  326. for person in parsed:
  327. n = normalize_lookup_name(person.get('spouse_name'))
  328. if n:
  329. spouse_name_set.add(n)
  330. # Clean names in parsed content
  331. if isinstance(parsed, list):
  332. for person in parsed:
  333. # Process Name: 'name' is Simplified from AI, 'original_name' is Traditional/Raw from AI
  334. simplified_name = person.get('name', '') or person.get('original_name', '')
  335. original_name = person.get('original_name', '')
  336. # Female spouse: only simplify Chinese, do NOT prepend '留'
  337. if should_skip_liu_prefix_for_person(person, spouse_name_set):
  338. cleaned_simplified = manual_simplify(simplified_name)
  339. else:
  340. # Same-clan default: prepend '留' and handle trailing '公'
  341. cleaned_simplified = clean_name(simplified_name)
  342. person['simplified_name'] = cleaned_simplified
  343. # Store raw name in 'name' field (as requested)
  344. if original_name:
  345. person['name'] = original_name
  346. else:
  347. # Fallback: if no original_name returned, use the uncleaned name as 'name'
  348. # or keep existing logic. But user wants raw in 'name'.
  349. # If AI didn't return original_name, 'name' is likely simplified.
  350. pass # Keep 'name' as is (which is Simplified) if original_name missing
  351. # Father name:同族,需要按“留”姓规则清洗
  352. if 'father_name' in person and person['father_name']:
  353. person['father_name'] = clean_name(person['father_name'])
  354. # Spouse name:只做繁转简,不拼接“留”姓,也不去“公”
  355. if 'spouse_name' in person and person['spouse_name']:
  356. person['spouse_name'] = manual_simplify(person['spouse_name'])
  357. # Re-serialize
  358. content_clean = json.dumps(parsed, ensure_ascii=False)
  359. with conn.cursor() as cursor:
  360. cursor.execute("UPDATE genealogy_records SET ai_status = 2, ai_content = %s WHERE id = %s", (content_clean, record_id))
  361. conn.commit()
  362. print(f"[AI Task] SUCCESS: Record {record_id} processed and saved.")
  363. return # Success
  364. except json.JSONDecodeError as err:
  365. raise Exception(f"JSON Parse Error: {str(err)}. Raw: {full_content}")
  366. else:
  367. raise Exception(f"API Error {response.status_code}: {response.text}")
  368. except Exception as e:
  369. print(f"[AI Task] Attempt {attempt+1} failed for record {record_id}: {e}")
  370. last_exception = e
  371. if attempt < max_retries - 1:
  372. wait_time = 2 * (attempt + 1)
  373. print(f"[AI Task] Waiting {wait_time}s before retry...")
  374. time.sleep(wait_time)
  375. raise last_exception or Exception("Unknown error")
  376. except Exception as e:
  377. print(f"[AI Task] FINAL FAILURE for record {record_id}: {e}")
  378. try:
  379. with conn.cursor() as cursor:
  380. cursor.execute("UPDATE genealogy_records SET ai_status = 3, ai_content = %s WHERE id = %s", (f"Max Retries Exceeded. Error: {str(e)}", record_id))
  381. conn.commit()
  382. except:
  383. pass
  384. finally:
  385. conn.close()
  386. print(f"[AI Task] Task finished for record {record_id}")
  387. @app.route('/manager/')
  388. def index():
  389. if 'user_id' not in session:
  390. return redirect(url_for('login'))
  391. page = request.args.get('page', 1, type=int)
  392. version = request.args.get('version', '').strip()
  393. source = request.args.get('source', '').strip()
  394. person = request.args.get('person', '').strip()
  395. file_type = request.args.get('file_type', '').strip()
  396. per_page = 10
  397. offset = (page - 1) * per_page
  398. conn = get_db_connection()
  399. try:
  400. with conn.cursor() as cursor:
  401. query_conditions = []
  402. params = []
  403. if version:
  404. query_conditions.append("genealogy_version LIKE %s")
  405. params.append(f"%{version}%")
  406. if source:
  407. query_conditions.append("genealogy_source LIKE %s")
  408. params.append(f"%{source}%")
  409. if person:
  410. query_conditions.append("upload_person LIKE %s")
  411. params.append(f"%{person}%")
  412. if file_type:
  413. query_conditions.append("file_type = %s")
  414. params.append(file_type)
  415. where_clause = ""
  416. if query_conditions:
  417. where_clause = "WHERE " + " AND ".join(query_conditions)
  418. count_sql = f"SELECT COUNT(*) as count FROM genealogy_records {where_clause}"
  419. cursor.execute(count_sql, params)
  420. total = cursor.fetchone()['count']
  421. sql = f"SELECT * FROM genealogy_records {where_clause} ORDER BY page_number ASC LIMIT %s OFFSET %s"
  422. cursor.execute(sql, params + [per_page, offset])
  423. records = cursor.fetchall()
  424. total_pages = (total + per_page - 1) // per_page
  425. finally:
  426. conn.close()
  427. return render_template('index.html', records=records, page=page, total_pages=total_pages, version=version, source=source, person=person, file_type=file_type, total=total)
  428. @app.route('/manager/members')
  429. def members():
  430. if 'user_id' not in session:
  431. return redirect(url_for('login'))
  432. search_name = request.args.get('name', '').strip()
  433. page = request.args.get('page', 1, type=int)
  434. per_page = 10
  435. offset = (page - 1) * per_page
  436. conn = get_db_connection()
  437. try:
  438. with conn.cursor() as cursor:
  439. # 1. Get total count
  440. if search_name:
  441. cursor.execute("SELECT COUNT(*) as count FROM family_member_info WHERE name LIKE %s", (f"%{search_name}%",))
  442. else:
  443. cursor.execute("SELECT COUNT(*) as count FROM family_member_info")
  444. result = cursor.fetchone()
  445. total = result['count'] if result else 0
  446. total_pages = (total + per_page - 1) // per_page
  447. # 2. Get paginated results, ordered by modified_time DESC (or create_time if modified is null/same)
  448. # Using COALESCE to ensure sort works even if modified_time is NULL
  449. order_clause = "ORDER BY COALESCE(modified_time, create_time) DESC"
  450. if search_name:
  451. sql = f"SELECT * FROM family_member_info WHERE name LIKE %s {order_clause} LIMIT %s OFFSET %s"
  452. cursor.execute(sql, (f"%{search_name}%", per_page, offset))
  453. else:
  454. sql = f"SELECT * FROM family_member_info {order_clause} LIMIT %s OFFSET %s"
  455. cursor.execute(sql, (per_page, offset))
  456. members = cursor.fetchall()
  457. # 格式化日期
  458. for m in members:
  459. m['birthday_str'] = format_timestamp(m.get('birthday'))
  460. # 格式化创建时间 (针对 TIMESTAMP 字段)
  461. if m.get('create_time'):
  462. m['create_time_str'] = m['create_time'].strftime('%Y-%m-%d')
  463. if m.get('modified_time'):
  464. m['modified_time_str'] = m['modified_time'].strftime('%Y-%m-%d %H:%M')
  465. finally:
  466. conn.close()
  467. return render_template('members.html', members=members, search_name=search_name, page=page, total_pages=total_pages, total=total)
  468. @app.route('/manager/tree')
  469. def tree():
  470. if 'user_id' not in session:
  471. return redirect(url_for('login'))
  472. return render_template('tree.html')
  473. @app.route('/manager/tree_classic')
  474. def tree_classic():
  475. if 'user_id' not in session:
  476. return redirect(url_for('login'))
  477. return render_template('tree_classic.html')
  478. @app.route('/manager/api/tree_data')
  479. def tree_data():
  480. if 'user_id' not in session:
  481. return jsonify({"error": "Unauthorized"}), 401
  482. conn = get_db_connection()
  483. try:
  484. with conn.cursor() as cursor:
  485. # 获取所有成员
  486. cursor.execute("SELECT id, name, simplified_name, sex, family_rank, name_word_generation FROM family_member_info")
  487. members = cursor.fetchall()
  488. # 获取所有关系 (1:父子 2:母子 10:夫妻 11:兄弟 12:姐妹)
  489. cursor.execute("SELECT parent_mid, child_mid, relation_type FROM family_relation_info")
  490. relations = cursor.fetchall()
  491. return jsonify({"members": members, "relations": relations})
  492. finally:
  493. conn.close()
  494. @app.route('/manager/api/save_relation', methods=['POST'])
  495. def save_relation():
  496. if 'user_id' not in session:
  497. return jsonify({"success": False, "message": "Unauthorized"}), 401
  498. data = request.json
  499. source_mid = data.get('source_mid') # The member being dragged
  500. target_mid = data.get('target_mid') # The member being dropped onto
  501. rel_type = int(data.get('relation_type'))
  502. sub_rel_type = int(data.get('sub_relation_type', 0))
  503. if not source_mid or not target_mid or not rel_type:
  504. return jsonify({"success": False, "message": "参数不完整"}), 400
  505. conn = get_db_connection()
  506. try:
  507. with conn.cursor() as cursor:
  508. # 简单处理:如果是父子/母子关系
  509. # target_mid 是父辈,source_mid 是子辈
  510. parent_mid = target_mid
  511. child_mid = source_mid
  512. gen_diff = 1
  513. if rel_type == 10: # 夫妻
  514. # 夫妻关系中,我们通常把关联人设为 parent_mid
  515. parent_mid = target_mid
  516. child_mid = source_mid
  517. gen_diff = 0
  518. elif rel_type in [11, 12]: # 兄弟姐妹
  519. # 这里逻辑上比较复杂,通常兄弟姐妹有共同父母。
  520. # 简化处理:暂时存为同级关系 (gen_diff=0)
  521. parent_mid = target_mid
  522. child_mid = source_mid
  523. gen_diff = 0
  524. # 删除旧关系
  525. cursor.execute("DELETE FROM family_relation_info WHERE source_mid = %s", (source_mid,))
  526. # 插入新关系
  527. sql = """
  528. INSERT INTO family_relation_info
  529. (parent_mid, child_mid, relation_type, sub_relation_type, source_mid, generation_diff)
  530. VALUES (%s, %s, %s, %s, %s, %s)
  531. """
  532. cursor.execute(sql, (parent_mid, child_mid, rel_type, sub_rel_type, source_mid, gen_diff))
  533. conn.commit()
  534. return jsonify({"success": True, "message": "关系已保存"})
  535. except Exception as e:
  536. return jsonify({"success": False, "message": str(e)}), 500
  537. finally:
  538. conn.close()
  539. @app.route('/manager/api/check_relations', methods=['POST'])
  540. def check_relations():
  541. if 'user_id' not in session:
  542. return jsonify({"success": False, "message": "Unauthorized"}), 401
  543. data = request.json
  544. people = data.get('people', [])
  545. if not people:
  546. return jsonify({"success": False, "matches": {}})
  547. conn = get_db_connection()
  548. matches = {}
  549. try:
  550. with conn.cursor() as cursor:
  551. # Collect all father names and spouse names to query
  552. names_to_check = set()
  553. for p in people:
  554. if p.get('father_name'): names_to_check.add(p['father_name'])
  555. if p.get('spouse_name'): names_to_check.add(p['spouse_name'])
  556. if not names_to_check:
  557. return jsonify({"success": True, "matches": {}})
  558. # Query DB
  559. format_strings = ','.join(['%s'] * len(names_to_check))
  560. if names_to_check:
  561. sql = "SELECT id, name, simplified_name, sex, birthday FROM family_member_info WHERE name IN (%s) OR simplified_name IN (%s)" % (format_strings, format_strings)
  562. cursor.execute(sql, tuple(names_to_check) * 2)
  563. results = cursor.fetchall()
  564. else:
  565. results = []
  566. # Organize by name
  567. db_map = {} # name -> [list of members]
  568. for r in results:
  569. # Add under 'name' (Traditional/Old Simplified)
  570. if r['name'] not in db_map: db_map[r['name']] = []
  571. db_map[r['name']].append(r)
  572. # Add under 'simplified_name' if exists
  573. if r.get('simplified_name'):
  574. sname = r['simplified_name']
  575. if sname not in db_map: db_map[sname] = []
  576. # Avoid duplicates if simplified_name is same as name?
  577. # The list might contain same object reference, which is fine.
  578. if sname != r['name']:
  579. db_map[sname].append(r)
  580. # Build matches for each input person
  581. for index, p in enumerate(people):
  582. p_match = {}
  583. # Check Father
  584. fname = p.get('father_name')
  585. if fname and fname in db_map:
  586. candidates = db_map[fname]
  587. # Filter: Father should be Male usually, and older than child (if birthday available)
  588. valid_fathers = [c for c in candidates if c['sex'] == 1]
  589. if valid_fathers:
  590. p_match['father'] = valid_fathers # Return all candidates
  591. # Check Spouse
  592. sname = p.get('spouse_name')
  593. if sname and sname in db_map:
  594. candidates = db_map[sname]
  595. # Filter: Spouse usually opposite sex
  596. target_sex = 1 if p.get('sex') == '女' else 2
  597. valid_spouses = [c for c in candidates if c['sex'] == target_sex]
  598. if valid_spouses:
  599. p_match['spouse'] = valid_spouses
  600. if p_match:
  601. matches[index] = p_match
  602. return jsonify({"success": True, "matches": matches})
  603. finally:
  604. conn.close()
  605. @app.route('/manager/add_member', methods=['GET', 'POST'])
  606. def add_member():
  607. if 'user_id' not in session:
  608. return redirect(url_for('login'))
  609. conn = get_db_connection()
  610. try:
  611. # Check for source_record_id (from GET or POST)
  612. source_record_id = request.args.get('record_id') or request.form.get('source_record_id')
  613. prefilled_content = None
  614. source_oss_url = None
  615. if source_record_id:
  616. with conn.cursor() as cursor:
  617. cursor.execute("SELECT oss_url, ai_content, ai_status FROM genealogy_records WHERE id = %s", (source_record_id,))
  618. rec = cursor.fetchone()
  619. if rec:
  620. source_oss_url = rec['oss_url']
  621. # Check ai_status (2 = success)
  622. if rec['ai_status'] == 2 and rec['ai_content']:
  623. prefilled_content = rec['ai_content']
  624. if request.method == 'POST':
  625. # 处理生日转换为 Unix 时间戳
  626. birthday_str = request.form.get('birthday')
  627. birthday_ts = 0
  628. if birthday_str:
  629. try:
  630. birthday_ts = int(datetime.strptime(birthday_str, '%Y-%m-%d').timestamp())
  631. except ValueError:
  632. birthday_ts = 0
  633. # 关系数据
  634. related_mid = request.form.get('related_mid')
  635. relation_type = request.form.get('relation_type')
  636. sub_relation_type = request.form.get('sub_relation_type', 0)
  637. # 年龄校验逻辑
  638. if related_mid and relation_type in ['1', '2']: # 1:父子 2:母子
  639. with conn.cursor() as cursor:
  640. cursor.execute("SELECT name, birthday FROM family_member_info WHERE id = %s", (related_mid,))
  641. parent = cursor.fetchone()
  642. if parent and parent['birthday'] > 0 and birthday_ts > 0:
  643. if birthday_ts < parent['birthday']:
  644. error_msg = f"数据冲突:成员年龄不能比其父亲/母亲({parent['name']})大,请检查并修正出生日期。"
  645. flash(error_msg)
  646. # Re-fetch data for rendering
  647. cursor.execute("SELECT id, name FROM family_member_info ORDER BY name")
  648. all_members = cursor.fetchall()
  649. cursor.execute("SELECT * FROM genealogy_records ORDER BY page_number ASC")
  650. images = cursor.fetchall()
  651. if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
  652. return jsonify({
  653. "success": False,
  654. "message": error_msg
  655. }), 400
  656. return render_template('add_member.html', all_members=all_members, images=images,
  657. prefilled_content=prefilled_content, source_oss_url=source_oss_url, source_record_id=source_record_id)
  658. # 获取表单数据
  659. data = {
  660. 'name': request.form['name'],
  661. 'simplified_name': request.form.get('simplified_name'),
  662. 'former_name': request.form.get('former_name'),
  663. 'childhood_name': request.form.get('childhood_name'),
  664. 'name_word': request.form.get('name_word'),
  665. 'name_word_generation': ';'.join([g.strip() for g in request.form.getlist('lineage_generations[]') if g.strip()]),
  666. 'name_title': request.form.get('name_title'),
  667. 'sex': request.form['sex'],
  668. 'birthday': birthday_ts,
  669. 'is_pass_away': request.form.get('is_pass_away', 0),
  670. 'marital_status': request.form.get('marital_status', 0),
  671. 'birth_place': request.form.get('birth_place'),
  672. 'branch_family_hall': request.form.get('branch_family_hall'),
  673. 'cluster_place': request.form.get('cluster_place'),
  674. 'nation': request.form.get('nation'),
  675. 'residential_address': request.form.get('residential_address'),
  676. 'phone': request.form.get('phone'),
  677. 'mail': request.form.get('mail'),
  678. 'wechat_account': request.form.get('wechat_account'),
  679. 'id_number': request.form.get('id_number'),
  680. 'occupation': request.form.get('occupation'),
  681. 'educational': request.form.get('educational'),
  682. 'blood_type': request.form.get('blood_type'),
  683. 'religion': request.form.get('religion'),
  684. 'hobbies': request.form.get('hobbies'),
  685. 'personal_achievements': request.form.get('personal_achievements'),
  686. 'family_rank': request.form.get('family_rank'),
  687. 'tags': request.form.get('tags'),
  688. 'notes': request.form.get('notes'),
  689. 'source_record_id': request.form.get('source_record_id') or None # Save source record ID
  690. }
  691. # ... (rest of logic) ...
  692. with conn.cursor() as cursor:
  693. fields = ", ".join(data.keys())
  694. placeholders = ", ".join(["%s"] * len(data))
  695. sql = f"INSERT INTO family_member_info ({fields}) VALUES ({placeholders})"
  696. cursor.execute(sql, list(data.values()))
  697. member_id = cursor.lastrowid
  698. # 录入关系
  699. if related_mid and relation_type:
  700. rel_type = int(relation_type)
  701. parent_mid = int(related_mid)
  702. child_mid = member_id
  703. gen_diff = 1 if rel_type in [1, 2] else 0
  704. sql_relation = """
  705. INSERT INTO family_relation_info
  706. (parent_mid, child_mid, relation_type, sub_relation_type, source_mid, generation_diff)
  707. VALUES (%s, %s, %s, %s, %s, %s)
  708. """
  709. cursor.execute(sql_relation, (parent_mid, child_mid, rel_type, sub_relation_type, member_id, gen_diff))
  710. # Update AI Record Status if applicable
  711. source_record_id = data.get('source_record_id')
  712. source_index = request.form.get('source_index')
  713. if source_record_id and source_index and source_index.isdigit():
  714. try:
  715. idx = int(source_index)
  716. cursor.execute("SELECT ai_content FROM genealogy_records WHERE id = %s FOR UPDATE", (source_record_id,))
  717. rec = cursor.fetchone()
  718. if rec and rec['ai_content']:
  719. import json
  720. content = json.loads(rec['ai_content'])
  721. # Ensure content is a list (it might be a dict if single object, though we try to normalize)
  722. if isinstance(content, dict):
  723. content = [content]
  724. if isinstance(content, list):
  725. updated = False
  726. if 0 <= idx < len(content):
  727. if not content[idx].get('is_imported'): # Avoid redundant updates
  728. content[idx]['is_imported'] = True
  729. content[idx]['imported_member_id'] = member_id
  730. updated = True
  731. if updated:
  732. new_content = json.dumps(content, ensure_ascii=False)
  733. cursor.execute("UPDATE genealogy_records SET ai_content = %s WHERE id = %s", (new_content, source_record_id))
  734. except Exception as e:
  735. print(f"Error updating AI content status: {e}")
  736. conn.commit()
  737. if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
  738. return jsonify({"success": True, "message": "成员录入成功", "member_id": member_id})
  739. flash('成员录入成功')
  740. return redirect(url_for('members'))
  741. with conn.cursor() as cursor:
  742. cursor.execute("SELECT id, name FROM family_member_info ORDER BY name")
  743. all_members = cursor.fetchall()
  744. cursor.execute("SELECT * FROM genealogy_records ORDER BY page_number ASC")
  745. images = cursor.fetchall()
  746. except Exception as e:
  747. flash(f'发生错误: {e}')
  748. all_members = []
  749. images = []
  750. finally:
  751. conn.close()
  752. return render_template('add_member.html', all_members=all_members, images=images,
  753. prefilled_content=prefilled_content, source_oss_url=source_oss_url, source_record_id=source_record_id)
  754. @app.route('/manager/edit_member/<int:member_id>', methods=['GET', 'POST'])
  755. def edit_member(member_id):
  756. if 'user_id' not in session:
  757. return redirect(url_for('login'))
  758. conn = get_db_connection()
  759. try:
  760. if request.method == 'POST':
  761. birthday_str = request.form.get('birthday')
  762. birthday_ts = 0
  763. if birthday_str:
  764. try:
  765. birthday_ts = int(datetime.strptime(birthday_str, '%Y-%m-%d').timestamp())
  766. except ValueError:
  767. birthday_ts = 0
  768. # 关系数据
  769. related_mid = request.form.get('related_mid')
  770. relation_type = request.form.get('relation_type')
  771. sub_relation_type = request.form.get('sub_relation_type', 0)
  772. # 年龄校验逻辑
  773. if related_mid and relation_type in ['1', '2']:
  774. with conn.cursor() as cursor:
  775. cursor.execute("SELECT name, birthday FROM family_member_info WHERE id = %s", (related_mid,))
  776. parent = cursor.fetchone()
  777. if parent and parent['birthday'] > 0 and birthday_ts > 0:
  778. if birthday_ts < parent['birthday']:
  779. flash(f"数据冲突:成员年龄不能比其父亲/母亲({parent['name']})大,请检查并修正出生日期。")
  780. # 重新加载编辑页所需数据
  781. cursor.execute("SELECT * FROM family_member_info WHERE id = %s", (member_id,))
  782. member = cursor.fetchone()
  783. member['birthday_date'] = birthday_str # 保持用户输入
  784. cursor.execute("SELECT id, name FROM family_member_info WHERE id != %s ORDER BY name", (member_id,))
  785. all_members = cursor.fetchall()
  786. cursor.execute("SELECT * FROM genealogy_records ORDER BY page_number ASC")
  787. images = cursor.fetchall()
  788. if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
  789. return jsonify({
  790. "success": False,
  791. "message": f"数据冲突:成员年龄不能比其父亲/母亲({parent['name']})大,请检查并修正出生日期。"
  792. }), 400
  793. return render_template('add_member.html', member=member, images=images, all_members=all_members)
  794. data = {
  795. 'name': request.form['name'],
  796. 'simplified_name': request.form.get('simplified_name'),
  797. 'former_name': request.form.get('former_name'),
  798. 'childhood_name': request.form.get('childhood_name'),
  799. 'name_word': request.form.get('name_word'),
  800. 'name_word_generation': ';'.join([g.strip() for g in request.form.getlist('lineage_generations[]') if g.strip()]),
  801. 'name_title': request.form.get('name_title'),
  802. 'sex': request.form['sex'],
  803. 'birthday': birthday_ts,
  804. 'is_pass_away': request.form.get('is_pass_away', 0),
  805. 'marital_status': request.form.get('marital_status', 0),
  806. 'birth_place': request.form.get('birth_place'),
  807. 'branch_family_hall': request.form.get('branch_family_hall'),
  808. 'cluster_place': request.form.get('cluster_place'),
  809. 'nation': request.form.get('nation'),
  810. 'residential_address': request.form.get('residential_address'),
  811. 'phone': request.form.get('phone'),
  812. 'mail': request.form.get('mail'),
  813. 'wechat_account': request.form.get('wechat_account'),
  814. 'id_number': request.form.get('id_number'),
  815. 'occupation': request.form.get('occupation'),
  816. 'educational': request.form.get('educational'),
  817. 'blood_type': request.form.get('blood_type'),
  818. 'religion': request.form.get('religion'),
  819. 'hobbies': request.form.get('hobbies'),
  820. 'personal_achievements': request.form.get('personal_achievements'),
  821. 'family_rank': request.form.get('family_rank'),
  822. 'tags': request.form.get('tags'),
  823. 'notes': request.form.get('notes'),
  824. 'source_record_id': request.form.get('source_record_id') or None
  825. }
  826. # 关系数据
  827. related_mid = request.form.get('related_mid')
  828. relation_type = request.form.get('relation_type')
  829. sub_relation_type = request.form.get('sub_relation_type', 0)
  830. with conn.cursor() as cursor:
  831. update_parts = [f"{k} = %s" for k in data.keys()]
  832. sql = f"UPDATE family_member_info SET {', '.join(update_parts)} WHERE id = %s"
  833. cursor.execute(sql, list(data.values()) + [member_id])
  834. # 更新关系
  835. if related_mid and relation_type:
  836. rel_type = int(relation_type)
  837. cursor.execute("DELETE FROM family_relation_info WHERE source_mid = %s", (member_id,))
  838. parent_mid = int(related_mid)
  839. child_mid = member_id
  840. gen_diff = 1 if rel_type in [1, 2] else 0
  841. sql_relation = """
  842. INSERT INTO family_relation_info
  843. (parent_mid, child_mid, relation_type, sub_relation_type, source_mid, generation_diff)
  844. VALUES (%s, %s, %s, %s, %s, %s)
  845. """
  846. cursor.execute(sql_relation, (parent_mid, child_mid, rel_type, sub_relation_type, member_id, gen_diff))
  847. # Update AI Record Status if applicable
  848. source_record_id = data.get('source_record_id')
  849. source_index = request.form.get('source_index')
  850. if source_record_id and source_index and source_index.isdigit():
  851. try:
  852. idx = int(source_index)
  853. cursor.execute("SELECT ai_content FROM genealogy_records WHERE id = %s FOR UPDATE", (source_record_id,))
  854. rec = cursor.fetchone()
  855. if rec and rec['ai_content']:
  856. import json
  857. content = json.loads(rec['ai_content'])
  858. if isinstance(content, dict):
  859. content = [content]
  860. if isinstance(content, list):
  861. updated = False
  862. if 0 <= idx < len(content):
  863. if not content[idx].get('is_imported'): # Avoid redundant updates
  864. content[idx]['is_imported'] = True
  865. content[idx]['imported_member_id'] = member_id
  866. updated = True
  867. if updated:
  868. new_content = json.dumps(content, ensure_ascii=False)
  869. cursor.execute("UPDATE genealogy_records SET ai_content = %s WHERE id = %s", (new_content, source_record_id))
  870. except Exception as e:
  871. print(f"Error updating AI content status: {e}")
  872. conn.commit()
  873. if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
  874. return jsonify({"success": True, "message": "成员信息更新成功"})
  875. flash('成员信息更新成功')
  876. return redirect(url_for('members'))
  877. with conn.cursor() as cursor:
  878. cursor.execute("SELECT * FROM family_member_info WHERE id = %s", (member_id,))
  879. member = cursor.fetchone()
  880. if not member:
  881. flash('成员不存在')
  882. return redirect(url_for('members'))
  883. # 格式化日期供显示
  884. if member.get('birthday'):
  885. member['birthday_date'] = format_timestamp(member['birthday'])
  886. # 获取现有关系
  887. cursor.execute("SELECT * FROM family_relation_info WHERE source_mid = %s LIMIT 1", (member_id,))
  888. current_relation = cursor.fetchone()
  889. cursor.execute("SELECT id, name FROM family_member_info WHERE id != %s ORDER BY name", (member_id,))
  890. all_members = cursor.fetchall()
  891. cursor.execute("SELECT * FROM genealogy_records ORDER BY page_number ASC")
  892. images = cursor.fetchall()
  893. finally:
  894. conn.close()
  895. return render_template('add_member.html', member=member, images=images, all_members=all_members, current_relation=current_relation)
  896. @app.route('/manager/member_detail/<int:member_id>')
  897. def member_detail(member_id):
  898. if 'user_id' not in session:
  899. return redirect(url_for('login'))
  900. conn = get_db_connection()
  901. try:
  902. with conn.cursor() as cursor:
  903. # Join with genealogy_records to get source image info
  904. sql = """
  905. SELECT m.*, r.oss_url as source_image_url, r.page_number as source_page,
  906. r.genealogy_version, r.genealogy_source, r.upload_person
  907. FROM family_member_info m
  908. LEFT JOIN genealogy_records r ON m.source_record_id = r.id
  909. WHERE m.id = %s
  910. """
  911. cursor.execute(sql, (member_id,))
  912. member = cursor.fetchone()
  913. if not member:
  914. flash('成员不存在')
  915. return redirect(url_for('members'))
  916. member['birthday_str'] = format_timestamp(member.get('birthday'))
  917. # 获取关系
  918. cursor.execute("""
  919. SELECT m.id, m.name, r.relation_type
  920. FROM family_relation_info r
  921. JOIN family_member_info m ON r.parent_mid = m.id
  922. WHERE r.child_mid = %s
  923. """, (member_id,))
  924. parents = cursor.fetchall()
  925. cursor.execute("""
  926. SELECT m.id, m.name, r.relation_type
  927. FROM family_relation_info r
  928. JOIN family_member_info m ON r.child_mid = m.id
  929. WHERE r.parent_mid = %s
  930. """, (member_id,))
  931. children = cursor.fetchall()
  932. finally:
  933. conn.close()
  934. return render_template('member_detail.html', member=member, parents=parents, children=children)
  935. @app.route('/manager/delete_member/<int:member_id>', methods=['POST'])
  936. def delete_member(member_id):
  937. if 'user_id' not in session:
  938. return jsonify({"success": False, "message": "Unauthorized"}), 401
  939. conn = get_db_connection()
  940. try:
  941. with conn.cursor() as cursor:
  942. # 1. 删除关系表中关联该成员的所有记录
  943. cursor.execute("DELETE FROM family_relation_info WHERE parent_mid = %s OR child_mid = %s OR source_mid = %s",
  944. (member_id, member_id, member_id))
  945. # 2. 删除成员本身
  946. cursor.execute("DELETE FROM family_member_info WHERE id = %s", (member_id,))
  947. conn.commit()
  948. flash('成员及其关系已成功删除')
  949. return redirect(url_for('members'))
  950. except Exception as e:
  951. conn.rollback()
  952. flash(f'删除失败: {e}')
  953. return redirect(url_for('members'))
  954. finally:
  955. conn.close()
  956. @app.route('/manager/login', methods=['GET', 'POST'])
  957. def login():
  958. if request.method == 'POST':
  959. username = request.form['username']
  960. password = request.form['password']
  961. try:
  962. conn = get_db_connection()
  963. try:
  964. with conn.cursor() as cursor:
  965. cursor.execute("SELECT * FROM users WHERE username=%s AND password=%s", (username, password))
  966. user = cursor.fetchone()
  967. if user:
  968. session['user_id'] = user['id']
  969. session['username'] = user['username']
  970. return redirect(url_for('index'))
  971. else:
  972. flash('用户名或密码错误')
  973. finally:
  974. conn.close()
  975. except Exception as e:
  976. flash(f'数据库连接错误: {str(e)}')
  977. print(f'Login error: {str(e)}')
  978. return render_template('login.html')
  979. @app.route('/manager/logout')
  980. def logout():
  981. session.clear()
  982. return redirect(url_for('login'))
  983. @app.route('/manager/api/check_name')
  984. def check_name():
  985. if 'user_id' not in session:
  986. return jsonify({"success": False, "message": "Unauthorized"}), 401
  987. name = request.args.get('name', '').strip()
  988. if not name:
  989. return jsonify({"success": True, "exists": False})
  990. conn = get_db_connection()
  991. try:
  992. with conn.cursor() as cursor:
  993. # Check for name or simplified_name match
  994. cursor.execute("SELECT id, name, simplified_name, sex, birthday, is_pass_away FROM family_member_info WHERE name = %s OR simplified_name = %s", (name, name))
  995. matches = cursor.fetchall()
  996. if matches:
  997. # Format birthday for display
  998. for m in matches:
  999. if m.get('birthday'):
  1000. m['birthday_str'] = format_timestamp(m['birthday'])
  1001. else:
  1002. m['birthday_str'] = '未知'
  1003. return jsonify({"success": True, "exists": True, "matches": matches})
  1004. else:
  1005. return jsonify({"success": True, "exists": False})
  1006. except Exception as e:
  1007. return jsonify({"success": False, "error": str(e)}), 500
  1008. finally:
  1009. conn.close()
  1010. import requests
  1011. import json
  1012. import re
  1013. @app.route('/manager/api/recognize_image', methods=['POST'])
  1014. def recognize_image():
  1015. if 'user_id' not in session:
  1016. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1017. data = request.json
  1018. image_url = data.get('image_url')
  1019. if not image_url:
  1020. return jsonify({"success": False, "message": "No image URL provided"}), 400
  1021. api_key = "a1800657-9212-4afe-9b7c-b49f015c54d3"
  1022. api_url = "https://ark.cn-beijing.volces.com/api/v3/responses"
  1023. prompt = """
  1024. 请分析这张家谱图片,提取其中关于人物的信息。
  1025. 请务必将繁体字转换为简体字(original_name 字段除外)。
  1026. 特别注意:'name' 字段必须是纯简体中文,不能包含繁体字(例如:'學'应转换为'学','劉'应转换为'刘','萬'应转换为'万')。
  1027. 请提取以下字段(如果存在):
  1028. - original_name: 原始姓名(严格保持图片上的繁体字,不做任何修改或转换)
  1029. - name: 简体姓名(必须转换为简体中文,去除不需要的敬称)
  1030. - sex: 性别(男/女)
  1031. - birthday: 出生日期(尝试转换为YYYY-MM-DD格式,如果无法确定年份可只填月日)
  1032. - death_date: 逝世日期(如文本中出现“殁”、“葬”、“卒”等字眼及其对应的时间,请提取)
  1033. - father_name: 父亲姓名
  1034. - spouse_name: 配偶姓名
  1035. - generation: 第几世/代数
  1036. - name_word: 字辈(例如名字为“学勤公”,“学”为字辈;提取名字中的字辈信息)
  1037. - education: 学历/功名
  1038. - title: 官职/称号
  1039. 请严格以JSON列表格式返回,不要包含Markdown代码块标记(如 ```json ... ```),直接返回JSON数组。
  1040. 如果包含多个人物,请都提取出来。
  1041. """
  1042. ai_payload_url = get_normalized_base64_image(image_url)
  1043. payload = {
  1044. "model": "doubao-seed-1-8-251228",
  1045. "stream": True,
  1046. "input": [
  1047. {
  1048. "role": "user",
  1049. "content": [
  1050. {
  1051. "type": "input_image",
  1052. "image_url": ai_payload_url
  1053. },
  1054. {
  1055. "type": "input_text",
  1056. "text": prompt
  1057. }
  1058. ]
  1059. }
  1060. ]
  1061. }
  1062. headers = {
  1063. "Authorization": f"Bearer {api_key}",
  1064. "Content-Type": "application/json"
  1065. }
  1066. def generate():
  1067. yield "正在连接 AI 服务...\n"
  1068. try:
  1069. # 使用 stream=True, timeout=120
  1070. # 增加 verify=False 以防 SSL 问题(开发环境)
  1071. # 增加 proxies=None 以防本地代理干扰
  1072. with requests.post(
  1073. api_url,
  1074. json=payload,
  1075. headers=headers,
  1076. stream=True,
  1077. timeout=1200,
  1078. verify=False,
  1079. proxies={"http": None, "https": None}
  1080. ) as r:
  1081. if r.status_code != 200:
  1082. yield f"Error: API returned status code {r.status_code}. Response: {r.text}"
  1083. return
  1084. yield "连接成功,正在等待 AI 响应...\n"
  1085. full_reasoning = ""
  1086. json_started = False
  1087. for line in r.iter_lines():
  1088. if line:
  1089. line_str = line.decode('utf-8')
  1090. if line_str.startswith('data: '):
  1091. json_str = line_str[6:]
  1092. if json_str.strip() == '[DONE]':
  1093. break
  1094. try:
  1095. chunk = json.loads(json_str)
  1096. # 处理 standard OpenAI choices format (content)
  1097. if 'choices' in chunk and len(chunk['choices']) > 0:
  1098. delta = chunk['choices'][0].get('delta', {})
  1099. if 'content' in delta:
  1100. if not json_started:
  1101. yield "|||JSON_START|||"
  1102. json_started = True
  1103. yield delta['content']
  1104. # 处理 standard OpenAI choices format (reasoning_content) if any
  1105. if 'reasoning_content' in delta:
  1106. yield f"\n[推理]: {delta['reasoning_content']}"
  1107. # 处理 Doubao/Volcano specific formats
  1108. # Type: response.reasoning_summary_text.delta
  1109. if chunk.get('type') == 'response.reasoning_summary_text.delta':
  1110. if 'delta' in chunk:
  1111. yield chunk['delta']
  1112. # Type: response.text.delta
  1113. if chunk.get('type') == 'response.text.delta':
  1114. if 'delta' in chunk:
  1115. if not json_started:
  1116. yield "|||JSON_START|||"
  1117. json_started = True
  1118. yield chunk['delta']
  1119. # Type: response.output_item.added (May contain initial content or status)
  1120. # Type: response.reasoning_summary_part.added
  1121. except Exception as e:
  1122. print(f"Chunk parse error: {e}")
  1123. else:
  1124. # 尝试直接解析非 data: 开头的行
  1125. try:
  1126. chunk = json.loads(line_str)
  1127. if 'choices' in chunk and len(chunk['choices']) > 0:
  1128. content = chunk['choices'][0]['message']['content']
  1129. yield content
  1130. except:
  1131. pass
  1132. except Exception as e:
  1133. yield f"\n[Error: {str(e)}]"
  1134. return Response(stream_with_context(generate()), mimetype='text/plain')
  1135. @app.route('/manager/api/start_analysis/<int:record_id>', methods=['POST'])
  1136. def start_analysis(record_id):
  1137. if 'user_id' not in session:
  1138. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1139. conn = get_db_connection()
  1140. try:
  1141. with conn.cursor() as cursor:
  1142. # Check if record exists
  1143. cursor.execute("SELECT oss_url, ai_status FROM genealogy_records WHERE id = %s", (record_id,))
  1144. record = cursor.fetchone()
  1145. if not record:
  1146. return jsonify({"success": False, "message": "Record not found"}), 404
  1147. # Update status to processing (1)
  1148. cursor.execute("UPDATE genealogy_records SET ai_status = 1 WHERE id = %s", (record_id,))
  1149. conn.commit()
  1150. # Start background task
  1151. threading.Thread(target=process_ai_task, args=(record_id, record['oss_url'])).start()
  1152. return jsonify({"success": True, "message": "Analysis started"})
  1153. except Exception as e:
  1154. return jsonify({"success": False, "message": str(e)}), 500
  1155. finally:
  1156. conn.close()
  1157. def process_files_background(upload_folder, saved_files, manual_page, suggested_page, genealogy_version, genealogy_source, upload_person):
  1158. current_suggested_page = int(manual_page) if manual_page and str(manual_page).isdigit() else suggested_page
  1159. for item in saved_files:
  1160. if len(item) == 3:
  1161. filename, file_path, file_page = item
  1162. else:
  1163. filename, file_path = item
  1164. file_page = None
  1165. try:
  1166. if filename.lower().endswith('.pdf'):
  1167. doc = fitz.open(file_path)
  1168. for page_index in range(len(doc)):
  1169. img_path = None
  1170. try:
  1171. page = doc.load_page(page_index)
  1172. max_dim = max(page.rect.width, page.rect.height)
  1173. zoom = 2000 / max_dim if max_dim > 0 else 2.0
  1174. if zoom > 2.5: zoom = 2.5
  1175. mat = fitz.Matrix(zoom, zoom)
  1176. # Use get_pixmap with matrix directly
  1177. pix = page.get_pixmap(matrix=mat)
  1178. final_page = current_suggested_page
  1179. if genealogy_version and genealogy_source:
  1180. if final_page is not None and str(final_page).strip() != '':
  1181. img_filename = f"{genealogy_version}_{genealogy_source}_{final_page}.jpg"
  1182. else:
  1183. img_filename = f"{genealogy_version}_{genealogy_source}.jpg"
  1184. else:
  1185. img_filename = f"{os.path.splitext(filename)[0]}_page_{page_index+1}.jpg"
  1186. img_path = os.path.join(upload_folder, img_filename)
  1187. # Save the pixmap to the image path
  1188. pix.save(img_path)
  1189. oss_url = upload_to_oss(img_path, custom_filename=img_filename)
  1190. if oss_url:
  1191. conn = get_db_connection()
  1192. try:
  1193. with conn.cursor() as cursor:
  1194. sql = """INSERT INTO genealogy_records
  1195. (file_name, oss_url, page_number, ai_status, genealogy_version, genealogy_source, upload_person, file_type)
  1196. VALUES (%s, %s, %s, 1, %s, %s, %s, %s)"""
  1197. cursor.execute(sql, (img_filename, oss_url, final_page, genealogy_version, genealogy_source, upload_person, 'PDF'))
  1198. record_id = cursor.lastrowid
  1199. conn.commit()
  1200. threading.Thread(target=process_ai_task, args=(record_id, oss_url)).start()
  1201. current_suggested_page += 1
  1202. finally:
  1203. conn.close()
  1204. except Exception as page_e:
  1205. print(f"Error processing page {page_index} of {filename}: {page_e}")
  1206. finally:
  1207. if img_path and os.path.exists(img_path):
  1208. try:
  1209. os.remove(img_path)
  1210. except:
  1211. pass
  1212. doc.close()
  1213. else:
  1214. img_path = compress_image_if_needed(file_path)
  1215. # Use explicitly set page number if provided, otherwise extract from filename or auto-increment
  1216. if file_page and str(file_page).isdigit():
  1217. final_page = int(file_page)
  1218. current_suggested_page = final_page + 1
  1219. page_num = final_page
  1220. else:
  1221. page_num = extract_page_number(img_path)
  1222. final_page = page_num if page_num else current_suggested_page
  1223. ext = os.path.splitext(img_path)[1]
  1224. if genealogy_version and genealogy_source:
  1225. if final_page is not None and str(final_page).strip() != '':
  1226. img_filename = f"{genealogy_version}_{genealogy_source}_{final_page}{ext}"
  1227. else:
  1228. img_filename = f"{genealogy_version}_{genealogy_source}{ext}"
  1229. else:
  1230. img_filename = os.path.basename(img_path)
  1231. oss_url = upload_to_oss(img_path, custom_filename=img_filename)
  1232. if oss_url:
  1233. conn = get_db_connection()
  1234. try:
  1235. with conn.cursor() as cursor:
  1236. sql = """INSERT INTO genealogy_records
  1237. (file_name, oss_url, page_number, ai_status, genealogy_version, genealogy_source, upload_person, file_type)
  1238. VALUES (%s, %s, %s, 1, %s, %s, %s, %s)"""
  1239. cursor.execute(sql, (img_filename, oss_url, final_page, genealogy_version, genealogy_source, upload_person, '图片'))
  1240. record_id = cursor.lastrowid
  1241. conn.commit()
  1242. threading.Thread(target=process_ai_task, args=(record_id, oss_url)).start()
  1243. if page_num:
  1244. current_suggested_page = page_num + 1
  1245. else:
  1246. current_suggested_page += 1
  1247. finally:
  1248. conn.close()
  1249. if img_path and img_path != file_path and os.path.exists(img_path):
  1250. try:
  1251. os.remove(img_path)
  1252. except:
  1253. pass
  1254. except Exception as e:
  1255. print(f"Error processing file {filename}: {e}")
  1256. finally:
  1257. if os.path.exists(file_path):
  1258. try:
  1259. os.remove(file_path)
  1260. except:
  1261. pass
  1262. @app.route('/manager/upload', methods=['GET', 'POST'])
  1263. def upload():
  1264. if 'user_id' not in session:
  1265. return redirect(url_for('login'))
  1266. # 获取建议页码 (当前最大页码 + 1)
  1267. conn = get_db_connection()
  1268. suggested_page = 1
  1269. try:
  1270. with conn.cursor() as cursor:
  1271. cursor.execute("SELECT MAX(page_number) as max_p FROM genealogy_records")
  1272. result = cursor.fetchone()
  1273. if result and result['max_p']:
  1274. suggested_page = result['max_p'] + 1
  1275. finally:
  1276. conn.close()
  1277. if request.method == 'POST':
  1278. if 'file' not in request.files:
  1279. flash('未选择文件')
  1280. return redirect(request.url)
  1281. files = request.files.getlist('file')
  1282. if not files or files[0].filename == '':
  1283. flash('未选择文件')
  1284. return redirect(request.url)
  1285. manual_page = request.form.get('manual_page')
  1286. genealogy_version = request.form.get('genealogy_version', '')
  1287. genealogy_source = request.form.get('genealogy_source', '')
  1288. upload_person = request.form.get('upload_person', '')
  1289. if not upload_person:
  1290. upload_person = session.get('username', '')
  1291. import uuid
  1292. saved_files = []
  1293. for i, file in enumerate(files):
  1294. if not file or not file.filename:
  1295. continue
  1296. original_filename = file.filename
  1297. ext = os.path.splitext(original_filename)[1].lower()
  1298. base_name = secure_filename(original_filename)
  1299. # If secure_filename removes all characters (e.g., pure Chinese name) or just leaves 'pdf'
  1300. if not base_name or base_name == ext.strip('.'):
  1301. filename = f"upload_{uuid.uuid4().hex[:8]}{ext}"
  1302. else:
  1303. # Ensure the extension is preserved
  1304. if not base_name.lower().endswith(ext):
  1305. filename = f"{base_name}{ext}"
  1306. else:
  1307. filename = base_name
  1308. file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
  1309. file.save(file_path)
  1310. # Fetch individual page number if it exists
  1311. file_page = request.form.get(f'page_number_{i}')
  1312. saved_files.append((filename, file_path, file_page))
  1313. if saved_files:
  1314. threading.Thread(
  1315. target=process_files_background,
  1316. args=(app.config['UPLOAD_FOLDER'], saved_files, manual_page, suggested_page, genealogy_version, genealogy_source, upload_person)
  1317. ).start()
  1318. flash('上传完成,AI解析中,稍后查看')
  1319. time.sleep(1.5)
  1320. return redirect(url_for('index'))
  1321. return render_template('upload.html', suggested_page=suggested_page)
  1322. @app.route('/manager/save_upload', methods=['POST'])
  1323. def save_upload():
  1324. if 'user_id' not in session: return redirect(url_for('login'))
  1325. filename = request.form.get('filename')
  1326. oss_url = request.form.get('oss_url')
  1327. page_number = request.form.get('page_number')
  1328. genealogy_version = request.form.get('genealogy_version', '')
  1329. genealogy_source = request.form.get('genealogy_source', '')
  1330. upload_person = request.form.get('upload_person', session.get('username', ''))
  1331. file_type = request.form.get('file_type', '图片')
  1332. if not oss_url or not page_number:
  1333. flash('页码不能为空')
  1334. return redirect(url_for('upload'))
  1335. conn = get_db_connection()
  1336. try:
  1337. with conn.cursor() as cursor:
  1338. sql = """INSERT INTO genealogy_records
  1339. (file_name, oss_url, page_number, ai_status, genealogy_version, genealogy_source, upload_person, file_type)
  1340. VALUES (%s, %s, %s, 1, %s, %s, %s, %s)"""
  1341. cursor.execute(sql, (filename, oss_url, page_number, genealogy_version, genealogy_source, upload_person, file_type))
  1342. record_id = cursor.lastrowid
  1343. conn.commit()
  1344. # Start AI Task
  1345. threading.Thread(target=process_ai_task, args=(record_id, oss_url)).start()
  1346. flash('上传完成,AI解析中,稍后查看')
  1347. except Exception as e:
  1348. flash(f'保存失败: {e}')
  1349. finally:
  1350. conn.close()
  1351. return redirect(url_for('index'))
  1352. @app.route('/manager/delete_upload/<int:record_id>', methods=['POST'])
  1353. def delete_upload(record_id):
  1354. if 'user_id' not in session:
  1355. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1356. conn = get_db_connection()
  1357. try:
  1358. with conn.cursor() as cursor:
  1359. # 删除记录
  1360. cursor.execute("DELETE FROM genealogy_records WHERE id = %s", (record_id,))
  1361. conn.commit()
  1362. flash('文件记录已成功删除')
  1363. return redirect(url_for('index'))
  1364. except Exception as e:
  1365. conn.rollback()
  1366. flash(f'删除失败: {e}')
  1367. return redirect(url_for('index'))
  1368. finally:
  1369. conn.close()
  1370. if __name__ == '__main__':
  1371. app.run(debug=False, port=5001)