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