app.py 110 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469
  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": "root",
  26. "password": "csqz@20255",
  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. # 尝试使用数据库连接池,如果不可用则使用普通连接
  53. try:
  54. from DBUtils.PooledDB import PooledDB
  55. # 创建连接池
  56. pool = PooledDB(
  57. creator=pymysql,
  58. maxconnections=10, # 连接池最大连接数
  59. mincached=2, # 初始化时创建的空闲连接数
  60. maxcached=5, # 最大空闲连接数
  61. maxshared=3, # 最大共享连接数
  62. blocking=True, # 连接池满时是否阻塞等待
  63. maxusage=None, # 一个连接最多被重复使用的次数
  64. setsession=[], # 开始会话前执行的命令列表
  65. ping=0, # 用ping命令检查连接是否可用的频率
  66. **DB_CONFIG
  67. )
  68. def get_db_connection():
  69. conn = pool.connection()
  70. print(f"[Database] Got connection from pool: {id(conn)}")
  71. return conn
  72. print("[Database] Database connection pool initialized successfully")
  73. except ImportError:
  74. # 如果DBUtils不可用,使用普通连接
  75. def get_db_connection():
  76. conn = pymysql.connect(**DB_CONFIG)
  77. print(f"[Database] Created new connection: {id(conn)}")
  78. return conn
  79. print("[Database] DBUtils not available, using regular database connections")
  80. def format_timestamp(ts):
  81. if not ts: return '未知'
  82. try:
  83. # 兼容秒和毫秒
  84. if ts > 10000000000: # 超过2286年的秒数,通常认为是毫秒
  85. ts = ts / 1000
  86. return time.strftime('%Y-%m-%d', time.localtime(ts))
  87. except:
  88. return '未知'
  89. def manual_simplify(text):
  90. """
  91. Simple fallback for common Traditional to Simplified conversion
  92. if AI fails to convert specific characters.
  93. """
  94. if not text: return text
  95. mapping = {
  96. '學': '学', '國': '国', '萬': '万', '寶': '宝', '興': '兴',
  97. '華': '华', '會': '会', '葉': '叶', '藝': '艺', '號': '号',
  98. '處': '处', '見': '见', '視': '视', '言': '言', '語': '语',
  99. '貝': '贝', '車': '车', '長': '长', '門': '门', '韋': '韦',
  100. '頁': '页', '風': '风', '飛': '飞', '食': '食', '馬': '马',
  101. '魚': '鱼', '鳥': '鸟', '麥': '麦', '黃': '黄', '齊': '齐',
  102. '齒': '齿', '龍': '龙', '龜': '龟', '壽': '寿', '榮': '荣',
  103. '愛': '爱', '慶': '庆', '衛': '卫', '賢': '贤', '義': '义',
  104. '禮': '礼', '樂': '乐', '靈': '灵', '滅': '灭', '氣': '气',
  105. '智': '智', '信': '信', '仁': '仁', '勇': '勇', '嚴': '严',
  106. '銳': '锐', '優': '优', '楊': '杨', '吳': '吴', '銀': '银'
  107. }
  108. result = ""
  109. for char in text:
  110. result += mapping.get(char, char)
  111. return result
  112. def _build_reverse_simplify_map():
  113. """
  114. Build a reverse map from simplified char -> list of traditional chars
  115. based on the fallback manual_simplify mapping.
  116. """
  117. mapping = {
  118. '學': '学', '國': '国', '萬': '万', '寶': '宝', '興': '兴',
  119. '華': '华', '會': '会', '葉': '叶', '藝': '艺', '號': '号',
  120. '處': '处', '見': '见', '視': '视', '言': '言', '語': '语',
  121. '貝': '贝', '車': '车', '長': '长', '門': '门', '韋': '韦',
  122. '頁': '页', '風': '风', '飛': '飞', '食': '食', '馬': '马',
  123. '魚': '鱼', '鳥': '鸟', '麥': '麦', '黃': '黄', '齊': '齐',
  124. '齒': '齿', '龍': '龙', '龜': '龟', '壽': '寿', '榮': '荣',
  125. '愛': '爱', '慶': '庆', '衛': '卫', '賢': '贤', '義': '义',
  126. '禮': '礼', '樂': '乐', '靈': '灵', '滅': '灭', '氣': '气',
  127. '智': '智', '信': '信', '仁': '仁', '勇': '勇', '嚴': '严',
  128. '銳': '锐', '優': '优', '楊': '杨', '吳': '吴', '銀': '银'
  129. }
  130. rev = {}
  131. for trad, simp in mapping.items():
  132. rev.setdefault(simp, [])
  133. if trad not in rev[simp]:
  134. rev[simp].append(trad)
  135. return rev
  136. _REVERSE_SIMPLIFY_MAP = _build_reverse_simplify_map()
  137. def expand_name_search_variants(keyword, max_variants=60):
  138. """
  139. Expand keyword into a small set of variants so Simplified/Traditional
  140. searches can match both `name` and `simplified_name`.
  141. - Always includes original keyword
  142. - Includes fallback-trad->simp conversion
  143. - Includes best-effort simp->trad expansions based on reverse map
  144. """
  145. if not keyword:
  146. return []
  147. kw = str(keyword).strip()
  148. if not kw:
  149. return []
  150. variants = set([kw])
  151. variants.add(manual_simplify(kw))
  152. # Build possible traditional variants when the input is simplified.
  153. # For each char, if we have traditional candidates, branch; otherwise keep itself.
  154. choices = []
  155. for ch in kw:
  156. cand = _REVERSE_SIMPLIFY_MAP.get(ch)
  157. if cand:
  158. # include itself too (covers already-traditional or neutral chars)
  159. choices.append([ch] + cand)
  160. else:
  161. choices.append([ch])
  162. # Cartesian product with early stop.
  163. results = ['']
  164. for opts in choices:
  165. new_results = []
  166. for prefix in results:
  167. for opt in opts:
  168. new_results.append(prefix + opt)
  169. if len(new_results) >= max_variants:
  170. break
  171. if len(new_results) >= max_variants:
  172. break
  173. results = new_results
  174. if len(results) >= max_variants:
  175. break
  176. for r in results:
  177. if r:
  178. variants.add(r)
  179. variants.add(manual_simplify(r))
  180. # Keep deterministic order for stable SQL params
  181. ordered = []
  182. for v in variants:
  183. v2 = (v or '').strip()
  184. if v2 and v2 not in ordered:
  185. ordered.append(v2)
  186. if len(ordered) >= max_variants:
  187. break
  188. return ordered
  189. def clean_name(name):
  190. """
  191. Clean name according to Liu family genealogy rules:
  192. 1. If name is '学公' or '留学公', keep 'Gong' (exception).
  193. 2. Otherwise, if name ends with '公', remove '公'.
  194. 3. If name does not start with '留', prepend '留'.
  195. """
  196. if not name: return name
  197. name = name.strip()
  198. # Pre-process: Ensure Simplified Chinese for specific chars
  199. name = manual_simplify(name)
  200. # 1. Check exceptions (names that SHOULD keep 'Gong')
  201. exceptions = ['学公', '留学公']
  202. if name in exceptions:
  203. if not name.startswith('留'):
  204. name = '留' + name
  205. return name
  206. # 2. General Rule: Remove 'Gong' suffix
  207. if name.endswith('公'):
  208. name = name[:-1]
  209. # 3. Ensure 'Liu' surname
  210. if not name.startswith('留'):
  211. name = '留' + name
  212. return name
  213. def is_female_value(sex_value):
  214. """Return True when sex value represents female."""
  215. if sex_value is None:
  216. return False
  217. s = str(sex_value).strip().lower()
  218. return s in ('女', '2', 'female', 'f')
  219. def normalize_lookup_name(name):
  220. """Normalize names for loose matching in AI parsed content."""
  221. if not name:
  222. return ''
  223. return manual_simplify(str(name)).strip()
  224. def should_skip_liu_prefix_for_person(person, spouse_name_set):
  225. """
  226. Female spouse records should not auto-prepend '留' in simplified_name.
  227. We treat a person as female spouse if:
  228. 1) sex is female, and
  229. 2) has spouse_name field OR appears in another person's spouse_name list.
  230. """
  231. if not isinstance(person, dict):
  232. return False
  233. if not is_female_value(person.get('sex')):
  234. return False
  235. own_names = set()
  236. own_names.add(normalize_lookup_name(person.get('name')))
  237. own_names.add(normalize_lookup_name(person.get('original_name')))
  238. own_names.discard('')
  239. has_spouse_name = bool(normalize_lookup_name(person.get('spouse_name')))
  240. referenced_by_other = any(n in spouse_name_set for n in own_names)
  241. return has_spouse_name or referenced_by_other
  242. def get_normalized_base64_image(image_url):
  243. """Download image, normalize to JPEG, and return base64 data URI for AI payload."""
  244. import io
  245. import base64
  246. import requests
  247. from PIL import Image
  248. try:
  249. response = requests.get(image_url, timeout=30)
  250. response.raise_for_status()
  251. with Image.open(io.BytesIO(response.content)) as img:
  252. # Convert to RGB to ensure JPEG compatibility
  253. if img.mode != 'RGB':
  254. img = img.convert('RGB')
  255. # Resize if too large
  256. max_dim = 2000
  257. if max(img.width, img.height) > max_dim:
  258. ratio = max_dim / max(img.width, img.height)
  259. new_size = (int(img.width * ratio), int(img.height * ratio))
  260. img = img.resize(new_size, Image.Resampling.LANCZOS)
  261. # Save as JPEG in memory
  262. buffer = io.BytesIO()
  263. img.save(buffer, format='JPEG', quality=85)
  264. b64_str = base64.b64encode(buffer.getvalue()).decode('utf-8')
  265. return f"data:image/jpeg;base64,{b64_str}"
  266. except Exception as e:
  267. print(f"Error normalizing image from {image_url}: {e}")
  268. return image_url # Fallback to original URL if processing fails
  269. def process_ai_task(record_id, image_url):
  270. """Background task to process image with AI and store result."""
  271. print(f"[AI Task] Starting task for record {record_id}...")
  272. conn = get_db_connection()
  273. try:
  274. with conn.cursor() as cursor:
  275. cursor.execute("UPDATE genealogy_records SET ai_status = 1 WHERE id = %s", (record_id,))
  276. conn.commit()
  277. print(f"[AI Task] Status updated to 'Processing' for record {record_id}")
  278. api_key = "a1800657-9212-4afe-9b7c-b49f015c54d3"
  279. api_url = "https://ark.cn-beijing.volces.com/api/v3/responses"
  280. prompt = """
  281. 请分析这张家谱图片,提取其中关于人物的信息。
  282. 请务必将繁体字转换为简体字(original_name 字段除外)。
  283. 特别注意:'name' 字段必须是纯简体中文,不能包含繁体字(例如:'學'应转换为'学','劉'应转换为'刘','萬'应转换为'万')。
  284. 请提取以下字段(如果存在):
  285. - original_name: 原始姓名(严格保持图片上的繁体字,不做任何修改或转换)
  286. - name: 简体姓名(必须转换为简体中文,去除不需要的敬称)
  287. - sex: 性别(男/女)
  288. - birthday: 出生日期(尝试转换为YYYY-MM-DD格式,如果无法确定年份可只填月日)
  289. - death_date: 逝世日期(如文本中出现“殁”、“葬”、“卒”等字眼及其对应的时间,请提取)
  290. - father_name: 父亲姓名
  291. - spouse_name: 配偶姓名
  292. - generation: 第几世/代数
  293. - name_word: 字辈(例如名字为“学勤公”,“学”为字辈;提取名字中的字辈信息)
  294. - education: 学历/功名
  295. - title: 官职/称号
  296. 请严格以JSON列表格式返回,不要包含Markdown代码块标记(如 ```json ... ```),直接返回JSON数组。
  297. 如果包含多个人物,请都提取出来。
  298. Do not output any reasoning or explanation, just the JSON.
  299. """
  300. ai_payload_url = get_normalized_base64_image(image_url)
  301. payload = {
  302. "model": "doubao-seed-1-8-251228",
  303. "stream": True, # Streaming for robust handling
  304. "input": [
  305. {
  306. "role": "user",
  307. "content": [
  308. {"type": "input_image", "image_url": ai_payload_url},
  309. {"type": "input_text", "text": prompt}
  310. ]
  311. }
  312. ]
  313. }
  314. headers = {
  315. "Authorization": f"Bearer {api_key}",
  316. "Content-Type": "application/json"
  317. }
  318. max_retries = 3
  319. last_exception = None
  320. for attempt in range(max_retries):
  321. try:
  322. print(f"[AI Task] Attempt {attempt+1}/{max_retries} connecting to API for record {record_id}...")
  323. response = requests.post(
  324. api_url,
  325. json=payload,
  326. headers=headers,
  327. timeout=1200,
  328. stream=True,
  329. verify=False,
  330. proxies={"http": None, "https": None}
  331. )
  332. if response.status_code == 200:
  333. print(f"[AI Task] Connection established for record {record_id}, receiving stream...")
  334. full_content = ""
  335. for line in response.iter_lines():
  336. if not line: continue
  337. line_str = line.decode('utf-8')
  338. # Debug: Print full line to understand event flow
  339. print(f"[AI Task Debug] Raw Line: {line_str[:500]}") # Truncate very long lines
  340. if line_str.startswith('data: '):
  341. json_str = line_str[6:]
  342. if json_str.strip() == '[DONE]':
  343. print("[AI Task Debug] Received [DONE]")
  344. break
  345. try:
  346. chunk = json.loads(json_str)
  347. chunk_type = chunk.get('type')
  348. # Standard OpenAI format (choices)
  349. if 'choices' in chunk and len(chunk['choices']) > 0:
  350. delta = chunk['choices'][0].get('delta', {})
  351. if 'content' in delta:
  352. full_content += delta['content']
  353. # Doubao/Volcengine specific formats (delta)
  354. elif chunk_type == 'response.text.delta':
  355. full_content += chunk.get('delta', '')
  356. # Check response.completed if empty
  357. elif chunk_type == 'response.completed' and not full_content:
  358. output = chunk.get('response', {}).get('output', [])
  359. for item in output:
  360. # Also extract from reasoning if it contains JSON-like text
  361. if item.get('type') == 'reasoning':
  362. summary = item.get('summary', [])
  363. for sum_item in summary:
  364. if sum_item.get('type') == 'summary_text':
  365. full_content += sum_item.get('text', '')
  366. elif item.get('type') == 'message':
  367. content = item.get('content')
  368. if isinstance(content, str):
  369. full_content += content
  370. elif isinstance(content, list):
  371. for part in content:
  372. if isinstance(part, dict) and part.get('type') == 'text':
  373. full_content += part.get('text', '')
  374. # Fallback: output_item.added
  375. elif chunk_type == 'response.output_item.added':
  376. item = chunk.get('item', {})
  377. if item.get('role') == 'assistant':
  378. content_field = item.get('content', [])
  379. if isinstance(content_field, str):
  380. full_content += content_field
  381. elif isinstance(content_field, list):
  382. for part in content_field:
  383. if isinstance(part, dict) and part.get('type') == 'text':
  384. full_content += part.get('text', '')
  385. except Exception as e:
  386. print(f"[AI Task] Chunk parse error: {e}")
  387. else:
  388. # Fallback for non-SSE
  389. try:
  390. chunk = json.loads(line_str)
  391. if 'choices' in chunk and len(chunk['choices']) > 0:
  392. content = chunk['choices'][0]['message']['content']
  393. full_content += content
  394. except:
  395. pass
  396. print(f"[AI Task] Stream finished. Content length: {len(full_content)}")
  397. if len(full_content) == 0:
  398. print(f"[AI Task] WARNING: No content received from AI stream.")
  399. # Continue to JSON parse to fail gracefully
  400. # Clean JSON
  401. try:
  402. # 1. Try finding [...] array
  403. start = full_content.find('[')
  404. end = full_content.rfind(']')
  405. # 2. If not found, try finding {...} object and wrap it
  406. is_single_object = False
  407. if start == -1 or end == -1 or end <= start:
  408. start = full_content.find('{')
  409. end = full_content.rfind('}')
  410. is_single_object = True
  411. if start != -1 and end != -1 and end > start:
  412. content_clean = full_content[start:end+1]
  413. else:
  414. # Fallback to regex or raw
  415. content_clean = re.sub(r'^```json\s*', '', full_content)
  416. content_clean = re.sub(r'```$', '', content_clean)
  417. parsed = json.loads(content_clean)
  418. # Normalize single object to list
  419. if is_single_object and isinstance(parsed, dict):
  420. parsed = [parsed]
  421. content_clean = json.dumps(parsed, ensure_ascii=False)
  422. elif isinstance(parsed, dict) and not isinstance(parsed, list):
  423. # Just in case json.loads parsed a dict even if we looked for []
  424. parsed = [parsed]
  425. content_clean = json.dumps(parsed, ensure_ascii=False)
  426. # Build spouse name lookup for "female spouse" detection
  427. spouse_name_set = set()
  428. if isinstance(parsed, list):
  429. for person in parsed:
  430. n = normalize_lookup_name(person.get('spouse_name'))
  431. if n:
  432. spouse_name_set.add(n)
  433. # Clean names in parsed content
  434. if isinstance(parsed, list):
  435. for person in parsed:
  436. # Process Name: 'name' is Simplified from AI, 'original_name' is Traditional/Raw from AI
  437. simplified_name = person.get('name', '') or person.get('original_name', '')
  438. original_name = person.get('original_name', '')
  439. # Female spouse: only simplify Chinese, do NOT prepend '留'
  440. if should_skip_liu_prefix_for_person(person, spouse_name_set):
  441. cleaned_simplified = manual_simplify(simplified_name)
  442. else:
  443. # Same-clan default: prepend '留' and handle trailing '公'
  444. cleaned_simplified = clean_name(simplified_name)
  445. person['simplified_name'] = cleaned_simplified
  446. # Store raw name in 'name' field (as requested)
  447. if original_name:
  448. person['name'] = original_name
  449. else:
  450. # Fallback: if no original_name returned, use the uncleaned name as 'name'
  451. # or keep existing logic. But user wants raw in 'name'.
  452. # If AI didn't return original_name, 'name' is likely simplified.
  453. pass # Keep 'name' as is (which is Simplified) if original_name missing
  454. # Father name:同族,需要按“留”姓规则清洗
  455. if 'father_name' in person and person['father_name']:
  456. person['father_name'] = clean_name(person['father_name'])
  457. # Spouse name:只做繁转简,不拼接“留”姓,也不去“公”
  458. if 'spouse_name' in person and person['spouse_name']:
  459. person['spouse_name'] = manual_simplify(person['spouse_name'])
  460. # Re-serialize
  461. content_clean = json.dumps(parsed, ensure_ascii=False)
  462. with conn.cursor() as cursor:
  463. cursor.execute("UPDATE genealogy_records SET ai_status = 2, ai_content = %s WHERE id = %s", (content_clean, record_id))
  464. conn.commit()
  465. print(f"[AI Task] SUCCESS: Record {record_id} processed and saved.")
  466. return # Success
  467. except json.JSONDecodeError as err:
  468. raise Exception(f"JSON Parse Error: {str(err)}. Raw: {full_content}")
  469. else:
  470. raise Exception(f"API Error {response.status_code}: {response.text}")
  471. except Exception as e:
  472. print(f"[AI Task] Attempt {attempt+1} failed for record {record_id}: {e}")
  473. last_exception = e
  474. if attempt < max_retries - 1:
  475. wait_time = 2 * (attempt + 1)
  476. print(f"[AI Task] Waiting {wait_time}s before retry...")
  477. time.sleep(wait_time)
  478. raise last_exception or Exception("Unknown error")
  479. except Exception as e:
  480. print(f"[AI Task] FINAL FAILURE for record {record_id}: {e}")
  481. try:
  482. with conn.cursor() as cursor:
  483. cursor.execute("UPDATE genealogy_records SET ai_status = 3, ai_content = %s WHERE id = %s", (f"Max Retries Exceeded. Error: {str(e)}", record_id))
  484. conn.commit()
  485. except:
  486. pass
  487. finally:
  488. conn.close()
  489. print(f"[AI Task] Task finished for record {record_id}")
  490. def ensure_pdf_table():
  491. conn = get_db_connection()
  492. try:
  493. with conn.cursor() as cursor:
  494. cursor.execute("""
  495. CREATE TABLE IF NOT EXISTS genealogy_pdfs (
  496. id INT AUTO_INCREMENT PRIMARY KEY,
  497. file_name VARCHAR(255) NOT NULL,
  498. oss_url TEXT NOT NULL,
  499. description VARCHAR(500) DEFAULT '',
  500. upload_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  501. uploader VARCHAR(100) DEFAULT '',
  502. version_name VARCHAR(255) DEFAULT '',
  503. version_source VARCHAR(255) DEFAULT '',
  504. file_provider VARCHAR(100) DEFAULT '',
  505. parse_status INT DEFAULT 0
  506. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  507. """)
  508. # 检查是否存在parse_status字段,如果不存在则添加
  509. cursor.execute("SHOW COLUMNS FROM genealogy_pdfs LIKE 'parse_status'")
  510. if not cursor.fetchone():
  511. cursor.execute("ALTER TABLE genealogy_pdfs ADD COLUMN parse_status INT DEFAULT 0")
  512. # 检查是否存在version_name字段,如果不存在则添加
  513. cursor.execute("SHOW COLUMNS FROM genealogy_pdfs LIKE 'version_name'")
  514. if not cursor.fetchone():
  515. cursor.execute("ALTER TABLE genealogy_pdfs ADD COLUMN version_name VARCHAR(255) DEFAULT ''")
  516. # 检查是否存在version_source字段,如果不存在则添加
  517. cursor.execute("SHOW COLUMNS FROM genealogy_pdfs LIKE 'version_source'")
  518. if not cursor.fetchone():
  519. cursor.execute("ALTER TABLE genealogy_pdfs ADD COLUMN version_source VARCHAR(255) DEFAULT ''")
  520. # 检查是否存在file_provider字段,如果不存在则添加
  521. cursor.execute("SHOW COLUMNS FROM genealogy_pdfs LIKE 'file_provider'")
  522. if not cursor.fetchone():
  523. cursor.execute("ALTER TABLE genealogy_pdfs ADD COLUMN file_provider VARCHAR(100) DEFAULT ''")
  524. conn.commit()
  525. finally:
  526. conn.close()
  527. @app.route('/manager/pdf_management')
  528. def pdf_management():
  529. if 'user_id' not in session:
  530. return redirect(url_for('login'))
  531. ensure_pdf_table()
  532. view_id = request.args.get('view', type=int)
  533. preview = request.args.get('preview', type=bool, default=False)
  534. selected_pdf = None
  535. conn = get_db_connection()
  536. try:
  537. with conn.cursor() as cursor:
  538. cursor.execute("SELECT * FROM genealogy_pdfs ORDER BY upload_time DESC")
  539. pdfs = cursor.fetchall()
  540. if view_id and preview:
  541. cursor.execute("SELECT * FROM genealogy_pdfs WHERE id = %s", (view_id,))
  542. selected_pdf = cursor.fetchone()
  543. finally:
  544. conn.close()
  545. return render_template('pdf_management.html', pdfs=pdfs, selected_pdf=selected_pdf)
  546. @app.route('/manager/parse_pdf/<int:pdf_id>', methods=['POST'])
  547. def parse_pdf(pdf_id):
  548. if 'user_id' not in session:
  549. return jsonify({"success": False, "message": "Unauthorized"}), 401
  550. # 标记PDF为解析中
  551. conn = get_db_connection()
  552. try:
  553. with conn.cursor() as cursor:
  554. cursor.execute("UPDATE genealogy_pdfs SET parse_status = 1 WHERE id = %s", (pdf_id,))
  555. conn.commit()
  556. finally:
  557. conn.close()
  558. # 异步执行PDF解析
  559. def parse_pdf_async():
  560. try:
  561. # 获取PDF信息
  562. conn = get_db_connection()
  563. pdf_info = None
  564. try:
  565. with conn.cursor() as cursor:
  566. cursor.execute("SELECT * FROM genealogy_pdfs WHERE id = %s", (pdf_id,))
  567. pdf_info = cursor.fetchone()
  568. finally:
  569. conn.close()
  570. if not pdf_info:
  571. return
  572. # 下载PDF并拆分
  573. pdf_url = pdf_info['oss_url']
  574. response = requests.get(pdf_url)
  575. response.raise_for_status()
  576. # 保存临时PDF文件
  577. temp_pdf_path = f"/tmp/{pdf_info['file_name']}"
  578. with open(temp_pdf_path, 'wb') as f:
  579. f.write(response.content)
  580. # 使用PyMuPDF拆分PDF
  581. doc = fitz.open(temp_pdf_path)
  582. page_count = doc.page_count
  583. # 每个PDF的页码从1开始计算
  584. max_page = 0
  585. # 逐页处理
  586. for i in range(page_count):
  587. page = doc[i]
  588. pix = page.get_pixmap()
  589. image_path = f"/tmp/{pdf_info['file_name']}_page_{i+1}.png"
  590. pix.save(image_path)
  591. # 上传图片到OSS
  592. image_oss_url = upload_to_oss(image_path, f"{pdf_info['file_name']}_page_{i+1}.png")
  593. # 检查上传是否成功
  594. if not image_oss_url:
  595. raise Exception(f"Failed to upload image to OSS: {image_path}")
  596. # 保存到genealogy_records表
  597. conn = get_db_connection()
  598. try:
  599. with conn.cursor() as cursor:
  600. cursor.execute("""
  601. INSERT INTO genealogy_records
  602. (file_name, oss_url, file_type, page_number, genealogy_version, genealogy_source, upload_person, upload_time)
  603. VALUES (%s, %s, %s, %s, %s, %s, %s, CURRENT_TIMESTAMP)
  604. """, (
  605. f"{pdf_info['file_name']}_page_{i+1}.png",
  606. image_oss_url,
  607. '图片',
  608. max_page + i + 1,
  609. pdf_info['version_name'],
  610. pdf_info['version_source'],
  611. pdf_info['file_provider']
  612. ))
  613. conn.commit()
  614. finally:
  615. conn.close()
  616. # 删除临时图片文件
  617. if os.path.exists(image_path):
  618. os.remove(image_path)
  619. # 删除临时PDF文件
  620. if os.path.exists(temp_pdf_path):
  621. os.remove(temp_pdf_path)
  622. # 更新PDF解析状态为成功
  623. conn = get_db_connection()
  624. try:
  625. with conn.cursor() as cursor:
  626. cursor.execute("UPDATE genealogy_pdfs SET parse_status = 2 WHERE id = %s", (pdf_id,))
  627. conn.commit()
  628. finally:
  629. conn.close()
  630. except Exception as e:
  631. # 更新PDF解析状态为失败
  632. conn = get_db_connection()
  633. try:
  634. with conn.cursor() as cursor:
  635. cursor.execute("UPDATE genealogy_pdfs SET parse_status = 3 WHERE id = %s", (pdf_id,))
  636. conn.commit()
  637. finally:
  638. conn.close()
  639. print(f"PDF解析失败: {e}")
  640. # 启动异步任务
  641. thread = threading.Thread(target=parse_pdf_async)
  642. thread.daemon = True
  643. thread.start()
  644. return jsonify({"success": True, "message": "PDF解析已开始,将在后台执行"})
  645. @app.route('/manager/batch_ai_parse', methods=['GET'])
  646. def batch_ai_parse():
  647. """Batch AI parse for unprocessed records."""
  648. if 'user_id' not in session:
  649. return jsonify({"success": False, "message": "Unauthorized"}), 401
  650. # Start background thread
  651. thread = threading.Thread(target=batch_ai_parse_async)
  652. thread.daemon = True
  653. thread.start()
  654. return jsonify({"success": True, "message": "批量AI解析已开始,请稍候查看结果"})
  655. def batch_ai_parse_async():
  656. """Background task to batch AI parse unprocessed records."""
  657. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  658. print(f"[{timestamp}] [Batch AI Parse] Starting batch AI parse task...")
  659. # Get unprocessed records (ai_status = 0)
  660. conn = None
  661. unprocessed_records = []
  662. try:
  663. conn = get_db_connection()
  664. with conn.cursor() as cursor:
  665. cursor.execute("SELECT id, oss_url FROM genealogy_records WHERE ai_status = 0 order by page_number")
  666. unprocessed_records = cursor.fetchall()
  667. conn.close()
  668. conn = None
  669. total_records = len(unprocessed_records)
  670. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  671. print(f"[{timestamp}] [Batch AI Parse] Found {total_records} unprocessed records")
  672. if total_records == 0:
  673. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  674. print(f"[{timestamp}] [Batch AI Parse] No unprocessed records found")
  675. return
  676. # Control concurrency to 5
  677. max_concurrency = 5
  678. semaphore = threading.Semaphore(max_concurrency)
  679. threads = []
  680. def process_record(record):
  681. """Process a single record with semaphore."""
  682. with semaphore:
  683. try:
  684. record_id = record['id']
  685. image_url = record['oss_url']
  686. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  687. print(f"[{timestamp}] [Batch AI Parse] Processing record {record_id}")
  688. process_ai_task(record_id, image_url)
  689. except Exception as e:
  690. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  691. print(f"[{timestamp}] [Batch AI Parse] Error processing record {record['id']}: {e}")
  692. # If failed, we'll handle it in the next batch
  693. # Start threads for each record
  694. for record in unprocessed_records:
  695. thread = threading.Thread(target=process_record, args=(record,))
  696. thread.daemon = True
  697. thread.start()
  698. threads.append(thread)
  699. # Wait for all threads to complete
  700. for thread in threads:
  701. thread.join()
  702. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  703. print(f"[{timestamp}] [Batch AI Parse] Batch processing completed. Processed {total_records} records")
  704. # Check for failed records and restart them
  705. check_failed_records()
  706. except Exception as e:
  707. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  708. print(f"[{timestamp}] [Batch AI Parse] Error: {e}")
  709. finally:
  710. if conn:
  711. try:
  712. conn.close()
  713. except:
  714. pass
  715. def check_failed_records():
  716. """Check for failed records and restart them."""
  717. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  718. print(f"[{timestamp}] [Batch AI Parse] Checking for failed records...")
  719. conn = None
  720. failed_records = []
  721. try:
  722. conn = get_db_connection()
  723. with conn.cursor() as cursor:
  724. cursor.execute("SELECT id, oss_url FROM genealogy_records WHERE ai_status = 3")
  725. failed_records = cursor.fetchall()
  726. conn.close()
  727. conn = None
  728. total_failed = len(failed_records)
  729. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  730. print(f"[{timestamp}] [Batch AI Parse] Found {total_failed} failed records")
  731. if total_failed == 0:
  732. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  733. print(f"[{timestamp}] [Batch AI Parse] No failed records found")
  734. return
  735. # Control concurrency to 5 for failed records
  736. max_concurrency = 5
  737. semaphore = threading.Semaphore(max_concurrency)
  738. threads = []
  739. def process_failed_record(record):
  740. """Process a failed record with semaphore."""
  741. with semaphore:
  742. retry_conn = None
  743. try:
  744. record_id = record['id']
  745. image_url = record['oss_url']
  746. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  747. print(f"[{timestamp}] [Batch AI Parse] Retrying failed record {record_id}")
  748. # Reset status to processing
  749. retry_conn = get_db_connection()
  750. with retry_conn.cursor() as cursor:
  751. cursor.execute("UPDATE genealogy_records SET ai_status = 1 WHERE id = %s", (record_id,))
  752. retry_conn.commit()
  753. retry_conn.close()
  754. retry_conn = None
  755. process_ai_task(record_id, image_url)
  756. except Exception as e:
  757. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  758. print(f"[{timestamp}] [Batch AI Parse] Error retrying record {record['id']}: {e}")
  759. finally:
  760. if retry_conn:
  761. try:
  762. retry_conn.close()
  763. except:
  764. pass
  765. # Start threads for each failed record
  766. for record in failed_records:
  767. thread = threading.Thread(target=process_failed_record, args=(record,))
  768. thread.daemon = True
  769. thread.start()
  770. threads.append(thread)
  771. # Wait for all threads to complete
  772. for thread in threads:
  773. thread.join()
  774. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  775. print(f"[{timestamp}] [Batch AI Parse] Retry processing completed. Retried {total_failed} failed records")
  776. except Exception as e:
  777. timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
  778. print(f"[{timestamp}] [Batch AI Parse] Error checking failed records: {e}")
  779. finally:
  780. if conn:
  781. try:
  782. conn.close()
  783. except:
  784. pass
  785. @app.route('/manager/delete_pdf/<int:pdf_id>', methods=['POST'])
  786. def delete_pdf(pdf_id):
  787. if 'user_id' not in session:
  788. return jsonify({"success": False, "message": "Unauthorized"}), 401
  789. conn = get_db_connection()
  790. try:
  791. with conn.cursor() as cursor:
  792. cursor.execute("DELETE FROM genealogy_pdfs WHERE id = %s", (pdf_id,))
  793. conn.commit()
  794. flash('PDF文件记录已删除')
  795. except Exception as e:
  796. flash(f'删除失败: {e}')
  797. finally:
  798. conn.close()
  799. return redirect(url_for('pdf_management'))
  800. @app.route('/manager/')
  801. def index():
  802. if 'user_id' not in session:
  803. return redirect(url_for('login'))
  804. page = request.args.get('page', 1, type=int)
  805. version = request.args.get('version', '').strip()
  806. print(f"Received version parameter: '{version}'")
  807. source = request.args.get('source', '').strip()
  808. person = request.args.get('person', '').strip()
  809. file_type = request.args.get('file_type', '').strip()
  810. per_page = 10
  811. offset = (page - 1) * per_page
  812. conn = get_db_connection()
  813. try:
  814. with conn.cursor() as cursor:
  815. query_conditions = []
  816. params = []
  817. if version:
  818. query_conditions.append("genealogy_version LIKE %s")
  819. params.append(f"%{version}%")
  820. if source:
  821. query_conditions.append("genealogy_source LIKE %s")
  822. params.append(f"%{source}%")
  823. if person:
  824. query_conditions.append("upload_person LIKE %s")
  825. params.append(f"%{person}%")
  826. if file_type:
  827. query_conditions.append("file_type = %s")
  828. params.append(file_type)
  829. where_clause = ""
  830. if query_conditions:
  831. where_clause = "WHERE " + " AND ".join(query_conditions)
  832. count_sql = f"SELECT COUNT(*) as count FROM genealogy_records {where_clause}"
  833. cursor.execute(count_sql, params)
  834. total = cursor.fetchone()['count']
  835. sql = f"SELECT * FROM genealogy_records {where_clause} ORDER BY page_number ASC LIMIT %s OFFSET %s"
  836. cursor.execute(sql, params + [per_page, offset])
  837. records = cursor.fetchall()
  838. total_pages = (total + per_page - 1) // per_page
  839. finally:
  840. conn.close()
  841. 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)
  842. @app.route('/manager/members')
  843. def members():
  844. if 'user_id' not in session:
  845. return redirect(url_for('login'))
  846. search_name = request.args.get('name', '').strip()
  847. page = request.args.get('page', 1, type=int)
  848. per_page = 10
  849. offset = (page - 1) * per_page
  850. print(f"[Members List] Fetching members page: {page}, search: '{search_name}', per_page: {per_page}")
  851. conn = get_db_connection()
  852. try:
  853. with conn.cursor() as cursor:
  854. # 1. Get total count
  855. if search_name:
  856. variants = expand_name_search_variants(search_name)
  857. where_parts = []
  858. params = []
  859. for v in variants:
  860. where_parts.append("(name LIKE %s OR simplified_name LIKE %s)")
  861. like = f"%{v}%"
  862. params.extend([like, like])
  863. where_clause = " OR ".join(where_parts) if where_parts else "name LIKE %s"
  864. if not where_parts:
  865. params = [f"%{search_name}%"]
  866. count_sql = f"SELECT COUNT(*) as count FROM family_member_info WHERE {where_clause}"
  867. print(f"[Members List] Executing count SQL: {count_sql}")
  868. print(f"[Members List] Count SQL parameters: {params}")
  869. cursor.execute(count_sql, tuple(params))
  870. else:
  871. count_sql = "SELECT COUNT(*) as count FROM family_member_info"
  872. print(f"[Members List] Executing count SQL: {count_sql}")
  873. cursor.execute(count_sql)
  874. result = cursor.fetchone()
  875. total = result['count'] if result else 0
  876. total_pages = (total + per_page - 1) // per_page
  877. print(f"[Members List] Total members: {total}, total pages: {total_pages}")
  878. # 2. Get paginated results, ordered by modified_time DESC (or create_time if modified is null/same)
  879. # Using COALESCE to ensure sort works even if modified_time is NULL
  880. order_clause = "ORDER BY COALESCE(modified_time, create_time) DESC"
  881. if search_name:
  882. variants = expand_name_search_variants(search_name)
  883. where_parts = []
  884. params = []
  885. for v in variants:
  886. where_parts.append("(name LIKE %s OR simplified_name LIKE %s)")
  887. like = f"%{v}%"
  888. params.extend([like, like])
  889. where_clause = " OR ".join(where_parts) if where_parts else "(name LIKE %s OR simplified_name LIKE %s)"
  890. if not where_parts:
  891. like = f"%{search_name}%"
  892. params = [like, like]
  893. sql = f"SELECT id, name, simplified_name, sex, name_word_generation, birthday, occupation, family_rank, branch_family_hall, residential_address, is_pass_away, create_time, modified_time FROM family_member_info WHERE {where_clause} {order_clause} LIMIT %s OFFSET %s"
  894. print(f"[Members List] Executing members SQL: {sql}")
  895. print(f"[Members List] Members SQL parameters: {params + [per_page, offset]}")
  896. cursor.execute(sql, tuple(params + [per_page, offset]))
  897. else:
  898. sql = f"SELECT id, name, simplified_name, sex, name_word_generation, birthday, occupation, family_rank, branch_family_hall, residential_address, is_pass_away, create_time, modified_time FROM family_member_info {order_clause} LIMIT %s OFFSET %s"
  899. print(f"[Members List] Executing members SQL: {sql}")
  900. print(f"[Members List] Members SQL parameters: {[per_page, offset]}")
  901. cursor.execute(sql, (per_page, offset))
  902. members = cursor.fetchall()
  903. print(f"[Members List] Fetched {len(members)} members")
  904. # 格式化日期
  905. for m in members:
  906. m['birthday_str'] = format_timestamp(m.get('birthday'))
  907. # 格式化创建时间 (针对 TIMESTAMP 字段)
  908. if m.get('create_time'):
  909. m['create_time_str'] = m['create_time'].strftime('%Y-%m-%d')
  910. if m.get('modified_time'):
  911. m['modified_time_str'] = m['modified_time'].strftime('%Y-%m-%d %H:%M')
  912. finally:
  913. print(f"[Members List] Closing database connection")
  914. conn.close()
  915. return render_template('members.html', members=members, search_name=search_name, page=page, total_pages=total_pages, total=total)
  916. @app.route('/manager/suspected_errors')
  917. def suspected_errors():
  918. if 'user_id' not in session:
  919. return redirect(url_for('login'))
  920. search_name = request.args.get('name', '').strip()
  921. page = request.args.get('page', 1, type=int)
  922. per_page = 20
  923. offset = (page - 1) * per_page
  924. conn = get_db_connection()
  925. try:
  926. with conn.cursor() as cursor:
  927. # Base query with condition for non-empty suspected_error (using TRIM to remove whitespace)
  928. base_query = "SELECT id, name, simplified_name, sex, name_word_generation, birthday, suspected_error FROM family_member_info WHERE suspected_error IS NOT NULL AND TRIM(suspected_error) != ''"
  929. count_query = "SELECT COUNT(*) as count FROM family_member_info WHERE suspected_error IS NOT NULL AND TRIM(suspected_error) != ''"
  930. # Add search condition if provided
  931. params = []
  932. if search_name:
  933. # Support both traditional and simplified name search
  934. base_query += " AND (name LIKE %s OR simplified_name LIKE %s)"
  935. count_query += " AND (name LIKE %s OR simplified_name LIKE %s)"
  936. search_param = f"%{search_name}%"
  937. params.extend([search_param, search_param])
  938. # Get total count
  939. cursor.execute(count_query, params)
  940. result = cursor.fetchone()
  941. total = result['count'] if result else 0
  942. total_pages = (total + per_page - 1) // per_page
  943. # Get members with pagination
  944. base_query += " ORDER BY name LIMIT %s OFFSET %s"
  945. params.extend([per_page, offset])
  946. cursor.execute(base_query, params)
  947. members = cursor.fetchall()
  948. # Format birthday for display
  949. for member in members:
  950. if member['birthday']:
  951. member['birthday_str'] = format_timestamp(member['birthday'])
  952. else:
  953. member['birthday_str'] = '未知'
  954. finally:
  955. conn.close()
  956. return render_template('suspected_errors.html', members=members, search_name=search_name, page=page, total_pages=total_pages, total=total)
  957. @app.route('/manager/tree')
  958. def tree():
  959. if 'user_id' not in session:
  960. return redirect(url_for('login'))
  961. return render_template('tree.html')
  962. @app.route('/manager/tree_classic')
  963. def tree_classic():
  964. if 'user_id' not in session:
  965. return redirect(url_for('login'))
  966. return render_template('tree_classic.html')
  967. @app.route('/manager/api/tree_data')
  968. def tree_data():
  969. if 'user_id' not in session:
  970. return jsonify({"error": "Unauthorized"}), 401
  971. conn = get_db_connection()
  972. try:
  973. with conn.cursor() as cursor:
  974. # 获取所有成员
  975. cursor.execute("SELECT id, name, simplified_name, sex, family_rank, name_word_generation FROM family_member_info")
  976. members = cursor.fetchall()
  977. # 获取所有关系 (1:父子 2:母子 10:夫妻 11:兄弟 12:姐妹)
  978. cursor.execute("SELECT parent_mid, child_mid, relation_type FROM family_relation_info")
  979. relations = cursor.fetchall()
  980. return jsonify({"members": members, "relations": relations})
  981. finally:
  982. conn.close()
  983. @app.route('/manager/api/save_relation', methods=['POST'])
  984. def save_relation():
  985. if 'user_id' not in session:
  986. return jsonify({"success": False, "message": "Unauthorized"}), 401
  987. data = request.json
  988. source_mid = data.get('source_mid') # The member being dragged
  989. target_mid = data.get('target_mid') # The member being dropped onto
  990. rel_type = int(data.get('relation_type'))
  991. sub_rel_type = int(data.get('sub_relation_type', 0))
  992. if not source_mid or not target_mid or not rel_type:
  993. return jsonify({"success": False, "message": "参数不完整"}), 400
  994. conn = get_db_connection()
  995. try:
  996. with conn.cursor() as cursor:
  997. # 简单处理:如果是父子/母子关系
  998. # target_mid 是父辈,source_mid 是子辈
  999. parent_mid = target_mid
  1000. child_mid = source_mid
  1001. gen_diff = 1
  1002. if rel_type == 10: # 夫妻
  1003. # 夫妻关系中,我们通常把关联人设为 parent_mid
  1004. parent_mid = target_mid
  1005. child_mid = source_mid
  1006. gen_diff = 0
  1007. elif rel_type in [11, 12]: # 兄弟姐妹
  1008. # 这里逻辑上比较复杂,通常兄弟姐妹有共同父母。
  1009. # 简化处理:暂时存为同级关系 (gen_diff=0)
  1010. parent_mid = target_mid
  1011. child_mid = source_mid
  1012. gen_diff = 0
  1013. # 删除旧关系
  1014. cursor.execute("DELETE FROM family_relation_info WHERE source_mid = %s", (source_mid,))
  1015. # 插入新关系
  1016. sql = """
  1017. INSERT INTO family_relation_info
  1018. (parent_mid, child_mid, relation_type, sub_relation_type, source_mid, generation_diff)
  1019. VALUES (%s, %s, %s, %s, %s, %s)
  1020. """
  1021. cursor.execute(sql, (parent_mid, child_mid, rel_type, sub_rel_type, source_mid, gen_diff))
  1022. conn.commit()
  1023. return jsonify({"success": True, "message": "关系已保存"})
  1024. except Exception as e:
  1025. return jsonify({"success": False, "message": str(e)}), 500
  1026. finally:
  1027. conn.close()
  1028. @app.route('/manager/api/members')
  1029. def get_members():
  1030. if 'user_id' not in session:
  1031. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1032. page = int(request.args.get('page', 1))
  1033. search = request.args.get('search', '')
  1034. per_page = 10
  1035. offset = (page - 1) * per_page
  1036. conn = get_db_connection()
  1037. try:
  1038. with conn.cursor() as cursor:
  1039. # Count total members
  1040. if search:
  1041. cursor.execute("SELECT COUNT(*) as total FROM family_member_info WHERE name LIKE %s OR simplified_name LIKE %s",
  1042. (f'%{search}%', f'%{search}%'))
  1043. else:
  1044. cursor.execute("SELECT COUNT(*) as total FROM family_member_info")
  1045. total_result = cursor.fetchone()
  1046. total = total_result['total'] if total_result else 0
  1047. # Get members for current page with father information
  1048. if search:
  1049. cursor.execute("""
  1050. SELECT
  1051. fmi.id, fmi.name, fmi.simplified_name, fmi.sex, fmi.name_word_generation,
  1052. father.name as father_name, father.simplified_name as father_simplified_name, father.name_word_generation as father_generation
  1053. FROM family_member_info fmi
  1054. LEFT JOIN family_relation_info fri ON fmi.id = fri.child_mid AND fri.relation_type IN (1, 2)
  1055. LEFT JOIN family_member_info father ON fri.parent_mid = father.id
  1056. WHERE fmi.name LIKE %s OR fmi.simplified_name LIKE %s
  1057. LIMIT %s OFFSET %s
  1058. """, (f'%{search}%', f'%{search}%', per_page, offset))
  1059. else:
  1060. cursor.execute("""
  1061. SELECT
  1062. fmi.id, fmi.name, fmi.simplified_name, fmi.sex, fmi.name_word_generation,
  1063. father.name as father_name, father.simplified_name as father_simplified_name, father.name_word_generation as father_generation
  1064. FROM family_member_info fmi
  1065. LEFT JOIN family_relation_info fri ON fmi.id = fri.child_mid AND fri.relation_type IN (1, 2)
  1066. LEFT JOIN family_member_info father ON fri.parent_mid = father.id
  1067. LIMIT %s OFFSET %s
  1068. """, (per_page, offset))
  1069. members = cursor.fetchall()
  1070. # Convert to list of dictionaries if needed
  1071. members_list = []
  1072. for member in members:
  1073. members_list.append({
  1074. 'id': member['id'],
  1075. 'name': member['name'],
  1076. 'simplified_name': member['simplified_name'],
  1077. 'sex': member['sex'],
  1078. 'name_word_generation': member.get('name_word_generation'),
  1079. 'father_name': member.get('father_name'),
  1080. 'father_simplified_name': member.get('father_simplified_name'),
  1081. 'father_generation': member.get('father_generation')
  1082. })
  1083. return jsonify({"success": True, "members": members_list, "total": total})
  1084. except Exception as e:
  1085. return jsonify({"success": False, "message": f"获取成员失败: {e}"}), 500
  1086. finally:
  1087. conn.close()
  1088. @app.route('/manager/api/member/<int:member_id>')
  1089. def get_member(member_id):
  1090. if 'user_id' not in session:
  1091. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1092. conn = get_db_connection()
  1093. try:
  1094. with conn.cursor() as cursor:
  1095. cursor.execute("SELECT id, name, name_word_generation, source_record_id FROM family_member_info WHERE id = %s", (member_id,))
  1096. member = cursor.fetchone()
  1097. if not member:
  1098. return jsonify({"success": False, "message": "成员不存在"}), 404
  1099. return jsonify({"member": member})
  1100. except Exception as e:
  1101. return jsonify({"success": False, "message": f"获取成员失败: {e}"}), 500
  1102. finally:
  1103. conn.close()
  1104. @app.route('/manager/api/check_relations', methods=['POST'])
  1105. def check_relations():
  1106. if 'user_id' not in session:
  1107. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1108. data = request.json
  1109. people = data.get('people', [])
  1110. if not people:
  1111. return jsonify({"success": False, "matches": {}})
  1112. conn = get_db_connection()
  1113. matches = {}
  1114. try:
  1115. with conn.cursor() as cursor:
  1116. # Collect all father names and spouse names to query
  1117. names_to_check = set()
  1118. for p in people:
  1119. if p.get('father_name'): names_to_check.add(p['father_name'])
  1120. if p.get('spouse_name'): names_to_check.add(p['spouse_name'])
  1121. if not names_to_check:
  1122. return jsonify({"success": True, "matches": {}})
  1123. # Query DB
  1124. format_strings = ','.join(['%s'] * len(names_to_check))
  1125. if names_to_check:
  1126. 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)
  1127. cursor.execute(sql, tuple(names_to_check) * 2)
  1128. results = cursor.fetchall()
  1129. else:
  1130. results = []
  1131. # Organize by name
  1132. db_map = {} # name -> [list of members]
  1133. for r in results:
  1134. # Add under 'name' (Traditional/Old Simplified)
  1135. if r['name'] not in db_map: db_map[r['name']] = []
  1136. db_map[r['name']].append(r)
  1137. # Add under 'simplified_name' if exists
  1138. if r.get('simplified_name'):
  1139. sname = r['simplified_name']
  1140. if sname not in db_map: db_map[sname] = []
  1141. # Avoid duplicates if simplified_name is same as name?
  1142. # The list might contain same object reference, which is fine.
  1143. if sname != r['name']:
  1144. db_map[sname].append(r)
  1145. # Build matches for each input person
  1146. for index, p in enumerate(people):
  1147. p_match = {}
  1148. # Check Father
  1149. fname = p.get('father_name')
  1150. if fname and fname in db_map:
  1151. candidates = db_map[fname]
  1152. # Filter: Father should be Male usually, and older than child (if birthday available)
  1153. valid_fathers = [c for c in candidates if c['sex'] == 1]
  1154. if valid_fathers:
  1155. p_match['father'] = valid_fathers # Return all candidates
  1156. # Check Spouse
  1157. sname = p.get('spouse_name')
  1158. if sname and sname in db_map:
  1159. candidates = db_map[sname]
  1160. # Filter: Spouse usually opposite sex
  1161. target_sex = 1 if p.get('sex') == '女' else 2
  1162. valid_spouses = [c for c in candidates if c['sex'] == target_sex]
  1163. if valid_spouses:
  1164. p_match['spouse'] = valid_spouses
  1165. if p_match:
  1166. matches[index] = p_match
  1167. return jsonify({"success": True, "matches": matches})
  1168. finally:
  1169. conn.close()
  1170. @app.route('/manager/add_member', methods=['GET', 'POST'])
  1171. def add_member():
  1172. if 'user_id' not in session:
  1173. return redirect(url_for('login'))
  1174. conn = get_db_connection()
  1175. try:
  1176. # Check for source_record_id (from GET or POST)
  1177. source_record_id = request.args.get('record_id') or request.form.get('source_record_id')
  1178. prefilled_content = None
  1179. source_oss_url = None
  1180. if source_record_id:
  1181. with conn.cursor() as cursor:
  1182. cursor.execute("SELECT oss_url, ai_content, ai_status FROM genealogy_records WHERE id = %s", (source_record_id,))
  1183. rec = cursor.fetchone()
  1184. if rec:
  1185. source_oss_url = rec['oss_url']
  1186. # Check ai_status (2 = success)
  1187. if rec['ai_status'] == 2 and rec['ai_content']:
  1188. prefilled_content = rec['ai_content']
  1189. if request.method == 'POST':
  1190. # 处理生日转换为 Unix 时间戳
  1191. birthday_str = request.form.get('birthday')
  1192. birthday_ts = 0
  1193. if birthday_str:
  1194. try:
  1195. birthday_ts = int(datetime.strptime(birthday_str, '%Y-%m-%d').timestamp())
  1196. except ValueError:
  1197. birthday_ts = 0
  1198. # 关系数据
  1199. related_mid = request.form.get('related_mid')
  1200. relation_type = request.form.get('relation_type')
  1201. sub_relation_type = request.form.get('sub_relation_type', 0)
  1202. # 年龄校验逻辑
  1203. if related_mid and relation_type in ['1', '2']: # 1:父子 2:母子
  1204. with conn.cursor() as cursor:
  1205. cursor.execute("SELECT name, birthday FROM family_member_info WHERE id = %s", (related_mid,))
  1206. parent = cursor.fetchone()
  1207. if parent and parent['birthday'] > 0 and birthday_ts > 0:
  1208. if birthday_ts < parent['birthday']:
  1209. error_msg = f"数据冲突:成员年龄不能比其父亲/母亲({parent['name']})大,请检查并修正出生日期。"
  1210. flash(error_msg)
  1211. # Re-fetch data for rendering
  1212. cursor.execute("SELECT id, name FROM family_member_info ORDER BY name")
  1213. all_members = cursor.fetchall()
  1214. cursor.execute("SELECT * FROM genealogy_records ORDER BY page_number ASC")
  1215. images = cursor.fetchall()
  1216. if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
  1217. return jsonify({
  1218. "success": False,
  1219. "message": error_msg
  1220. }), 400
  1221. selected_member_name = ''
  1222. return render_template('add_member.html', all_members=all_members, images=images,
  1223. prefilled_content=prefilled_content, source_oss_url=source_oss_url, source_record_id=source_record_id, selected_member_name=selected_member_name)
  1224. # 获取表单数据
  1225. data = {
  1226. 'name': request.form['name'],
  1227. 'simplified_name': request.form.get('simplified_name'),
  1228. 'former_name': request.form.get('former_name'),
  1229. 'childhood_name': request.form.get('childhood_name'),
  1230. 'name_word': request.form.get('name_word'),
  1231. 'name_word_generation': ';'.join([g.strip() for g in request.form.getlist('lineage_generations[]') if g.strip()]),
  1232. 'name_title': request.form.get('name_title'),
  1233. 'sex': request.form['sex'],
  1234. 'birthday': birthday_ts,
  1235. 'is_pass_away': request.form.get('is_pass_away', 0),
  1236. 'marital_status': request.form.get('marital_status', 0),
  1237. 'birth_place': request.form.get('birth_place'),
  1238. 'branch_family_hall': request.form.get('branch_family_hall'),
  1239. 'cluster_place': request.form.get('cluster_place'),
  1240. 'nation': request.form.get('nation'),
  1241. 'residential_address': request.form.get('residential_address'),
  1242. 'phone': request.form.get('phone'),
  1243. 'mail': request.form.get('mail'),
  1244. 'wechat_account': request.form.get('wechat_account'),
  1245. 'id_number': request.form.get('id_number'),
  1246. 'occupation': request.form.get('occupation'),
  1247. 'educational': request.form.get('educational'),
  1248. 'blood_type': request.form.get('blood_type'),
  1249. 'religion': request.form.get('religion'),
  1250. 'hobbies': request.form.get('hobbies'),
  1251. 'personal_achievements': request.form.get('personal_achievements'),
  1252. 'family_rank': request.form.get('family_rank'),
  1253. 'tags': request.form.get('tags'),
  1254. 'notes': request.form.get('notes'),
  1255. 'suspected_error': request.form.get('suspected_error').strip() if request.form.get('suspected_error') else '',
  1256. 'source_record_id': request.form.get('source_record_id') or None, # Save source record ID
  1257. 'create_uid': session['user_id'] # 记录当前操作人
  1258. }
  1259. # ... (rest of logic) ...
  1260. with conn.cursor() as cursor:
  1261. print(f"[Add Member] Inserting member data: {data}")
  1262. fields = ", ".join(data.keys())
  1263. placeholders = ", ".join(["%s"] * len(data))
  1264. sql = f"INSERT INTO family_member_info ({fields}) VALUES ({placeholders})"
  1265. print(f"[Add Member] Executing SQL: {sql}")
  1266. print(f"[Add Member] SQL parameters: {list(data.values())}")
  1267. cursor.execute(sql, list(data.values()))
  1268. member_id = cursor.lastrowid
  1269. print(f"[Add Member] Inserted member with ID: {member_id}")
  1270. # 录入关系
  1271. if related_mid and relation_type:
  1272. rel_type = int(relation_type)
  1273. parent_mid = int(related_mid)
  1274. child_mid = member_id
  1275. gen_diff = 1 if rel_type in [1, 2] else 0
  1276. sql_relation = """
  1277. INSERT INTO family_relation_info
  1278. (parent_mid, child_mid, relation_type, sub_relation_type, source_mid, generation_diff)
  1279. VALUES (%s, %s, %s, %s, %s, %s)
  1280. """
  1281. print(f"[Add Member] Inserting relation: parent_mid={parent_mid}, child_mid={child_mid}, relation_type={rel_type}")
  1282. cursor.execute(sql_relation, (parent_mid, child_mid, rel_type, sub_relation_type, member_id, gen_diff))
  1283. # Update AI Record Status if applicable
  1284. source_record_id = data.get('source_record_id')
  1285. source_index = request.form.get('source_index')
  1286. if source_record_id and source_index and source_index.isdigit():
  1287. try:
  1288. idx = int(source_index)
  1289. print(f"[Add Member] Updating AI record status: record_id={source_record_id}, index={idx}")
  1290. cursor.execute("SELECT ai_content FROM genealogy_records WHERE id = %s FOR UPDATE", (source_record_id,))
  1291. rec = cursor.fetchone()
  1292. if rec and rec['ai_content']:
  1293. import json
  1294. content = json.loads(rec['ai_content'])
  1295. # Ensure content is a list (it might be a dict if single object, though we try to normalize)
  1296. if isinstance(content, dict):
  1297. content = [content]
  1298. if isinstance(content, list):
  1299. updated = False
  1300. if 0 <= idx < len(content):
  1301. # Always update the status regardless of current value
  1302. content[idx]['is_imported'] = True
  1303. content[idx]['imported_member_id'] = member_id
  1304. updated = True
  1305. if updated:
  1306. new_content = json.dumps(content, ensure_ascii=False)
  1307. cursor.execute("UPDATE genealogy_records SET ai_content = %s WHERE id = %s", (new_content, source_record_id))
  1308. print(f"[Add Member] Updated AI record status")
  1309. except Exception as e:
  1310. print(f"[Add Member] Error updating AI content status: {e}")
  1311. print(f"[Add Member] Committing transaction")
  1312. conn.commit()
  1313. print(f"[Add Member] Transaction committed successfully")
  1314. if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
  1315. return jsonify({"success": True, "message": "成员录入成功", "member_id": member_id})
  1316. flash('成员录入成功')
  1317. return redirect(url_for('members'))
  1318. with conn.cursor() as cursor:
  1319. cursor.execute("SELECT id, name FROM family_member_info ORDER BY name")
  1320. all_members = cursor.fetchall()
  1321. cursor.execute("SELECT * FROM genealogy_records ORDER BY page_number ASC")
  1322. images = cursor.fetchall()
  1323. except Exception as e:
  1324. flash(f'发生错误: {e}')
  1325. all_members = []
  1326. images = []
  1327. finally:
  1328. conn.close()
  1329. selected_member_name = ''
  1330. return render_template('add_member.html', all_members=all_members, images=images,
  1331. prefilled_content=prefilled_content, source_oss_url=source_oss_url, source_record_id=source_record_id, selected_member_name=selected_member_name)
  1332. @app.route('/manager/edit_member/<int:member_id>', methods=['GET', 'POST'])
  1333. def edit_member(member_id):
  1334. if 'user_id' not in session:
  1335. return redirect(url_for('login'))
  1336. conn = get_db_connection()
  1337. try:
  1338. if request.method == 'POST':
  1339. birthday_str = request.form.get('birthday')
  1340. birthday_ts = 0
  1341. if birthday_str:
  1342. try:
  1343. birthday_ts = int(datetime.strptime(birthday_str, '%Y-%m-%d').timestamp())
  1344. except ValueError:
  1345. birthday_ts = 0
  1346. # 关系数据
  1347. related_mid = request.form.get('related_mid')
  1348. relation_type = request.form.get('relation_type')
  1349. sub_relation_type = request.form.get('sub_relation_type', 0)
  1350. # 年龄校验逻辑
  1351. if related_mid and relation_type in ['1', '2']:
  1352. with conn.cursor() as cursor:
  1353. cursor.execute("SELECT name, birthday FROM family_member_info WHERE id = %s", (related_mid,))
  1354. parent = cursor.fetchone()
  1355. if parent and parent['birthday'] > 0 and birthday_ts > 0:
  1356. if birthday_ts < parent['birthday']:
  1357. flash(f"数据冲突:成员年龄不能比其父亲/母亲({parent['name']})大,请检查并修正出生日期。")
  1358. # 重新加载编辑页所需数据
  1359. cursor.execute("SELECT * FROM family_member_info WHERE id = %s", (member_id,))
  1360. member = cursor.fetchone()
  1361. member['birthday_date'] = birthday_str # 保持用户输入
  1362. cursor.execute("SELECT id, name FROM family_member_info WHERE id != %s ORDER BY name", (member_id,))
  1363. all_members = cursor.fetchall()
  1364. cursor.execute("SELECT * FROM genealogy_records ORDER BY page_number ASC")
  1365. images = cursor.fetchall()
  1366. if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
  1367. return jsonify({
  1368. "success": False,
  1369. "message": f"数据冲突:成员年龄不能比其父亲/母亲({parent['name']})大,请检查并修正出生日期。"
  1370. }), 400
  1371. selected_member_name = ''
  1372. return render_template('add_member.html', member=member, images=images, all_members=all_members, selected_member_name=selected_member_name)
  1373. data = {
  1374. 'name': request.form['name'],
  1375. 'simplified_name': request.form.get('simplified_name'),
  1376. 'former_name': request.form.get('former_name'),
  1377. 'childhood_name': request.form.get('childhood_name'),
  1378. 'name_word': request.form.get('name_word'),
  1379. 'name_word_generation': ';'.join([g.strip() for g in request.form.getlist('lineage_generations[]') if g.strip()]),
  1380. 'name_title': request.form.get('name_title'),
  1381. 'sex': request.form['sex'],
  1382. 'birthday': birthday_ts,
  1383. 'is_pass_away': request.form.get('is_pass_away', 0),
  1384. 'marital_status': request.form.get('marital_status', 0),
  1385. 'birth_place': request.form.get('birth_place'),
  1386. 'branch_family_hall': request.form.get('branch_family_hall'),
  1387. 'cluster_place': request.form.get('cluster_place'),
  1388. 'nation': request.form.get('nation'),
  1389. 'residential_address': request.form.get('residential_address'),
  1390. 'phone': request.form.get('phone'),
  1391. 'mail': request.form.get('mail'),
  1392. 'wechat_account': request.form.get('wechat_account'),
  1393. 'id_number': request.form.get('id_number'),
  1394. 'occupation': request.form.get('occupation'),
  1395. 'educational': request.form.get('educational'),
  1396. 'blood_type': request.form.get('blood_type'),
  1397. 'religion': request.form.get('religion'),
  1398. 'hobbies': request.form.get('hobbies'),
  1399. 'personal_achievements': request.form.get('personal_achievements'),
  1400. 'family_rank': request.form.get('family_rank'),
  1401. 'tags': request.form.get('tags'),
  1402. 'notes': request.form.get('notes'),
  1403. 'suspected_error': request.form.get('suspected_error').strip() if request.form.get('suspected_error') else '',
  1404. 'source_record_id': request.form.get('source_record_id') or None,
  1405. 'create_uid': session['user_id'] # 记录当前操作人
  1406. }
  1407. # 关系数据
  1408. related_mid = request.form.get('related_mid')
  1409. relation_type = request.form.get('relation_type')
  1410. sub_relation_type = request.form.get('sub_relation_type', 0)
  1411. with conn.cursor() as cursor:
  1412. print(f"[Edit Member] Updating member data: {data}")
  1413. update_parts = [f"{k} = %s" for k in data.keys()]
  1414. sql = f"UPDATE family_member_info SET {', '.join(update_parts)} WHERE id = %s"
  1415. print(f"[Edit Member] Executing SQL: {sql}")
  1416. print(f"[Edit Member] SQL parameters: {list(data.values()) + [member_id]}")
  1417. cursor.execute(sql, list(data.values()) + [member_id])
  1418. print(f"[Edit Member] Updated member with ID: {member_id}")
  1419. # 更新关系
  1420. if related_mid and relation_type:
  1421. rel_type = int(relation_type)
  1422. print(f"[Edit Member] Deleting existing relations for member ID: {member_id}")
  1423. cursor.execute("DELETE FROM family_relation_info WHERE source_mid = %s", (member_id,))
  1424. parent_mid = int(related_mid)
  1425. child_mid = member_id
  1426. gen_diff = 1 if rel_type in [1, 2] else 0
  1427. sql_relation = """
  1428. INSERT INTO family_relation_info
  1429. (parent_mid, child_mid, relation_type, sub_relation_type, source_mid, generation_diff)
  1430. VALUES (%s, %s, %s, %s, %s, %s)
  1431. """
  1432. print(f"[Edit Member] Inserting relation: parent_mid={parent_mid}, child_mid={child_mid}, relation_type={rel_type}")
  1433. cursor.execute(sql_relation, (parent_mid, child_mid, rel_type, sub_relation_type, member_id, gen_diff))
  1434. # Update AI Record Status if applicable
  1435. source_record_id = data.get('source_record_id')
  1436. source_index = request.form.get('source_index')
  1437. if source_record_id and source_index and source_index.isdigit():
  1438. try:
  1439. idx = int(source_index)
  1440. print(f"[Edit Member] Updating AI record status: record_id={source_record_id}, index={idx}")
  1441. cursor.execute("SELECT ai_content FROM genealogy_records WHERE id = %s FOR UPDATE", (source_record_id,))
  1442. rec = cursor.fetchone()
  1443. if rec and rec['ai_content']:
  1444. import json
  1445. content = json.loads(rec['ai_content'])
  1446. if isinstance(content, dict):
  1447. content = [content]
  1448. if isinstance(content, list):
  1449. updated = False
  1450. if 0 <= idx < len(content):
  1451. # Always update the status regardless of current value
  1452. content[idx]['is_imported'] = True
  1453. content[idx]['imported_member_id'] = member_id
  1454. updated = True
  1455. if updated:
  1456. new_content = json.dumps(content, ensure_ascii=False)
  1457. cursor.execute("UPDATE genealogy_records SET ai_content = %s WHERE id = %s", (new_content, source_record_id))
  1458. print(f"[Edit Member] Updated AI record status")
  1459. except Exception as e:
  1460. print(f"[Edit Member] Error updating AI content status: {e}")
  1461. print(f"[Edit Member] Committing transaction")
  1462. conn.commit()
  1463. print(f"[Edit Member] Transaction committed successfully")
  1464. if request.headers.get('X-Requested-With') == 'XMLHttpRequest' or request.is_json:
  1465. return jsonify({"success": True, "message": "成员信息更新成功"})
  1466. flash('成员信息更新成功')
  1467. return redirect(url_for('members'))
  1468. with conn.cursor() as cursor:
  1469. cursor.execute("SELECT * FROM family_member_info WHERE id = %s", (member_id,))
  1470. member = cursor.fetchone()
  1471. if not member:
  1472. flash('成员不存在')
  1473. return redirect(url_for('members'))
  1474. # 格式化日期供显示
  1475. if member.get('birthday'):
  1476. member['birthday_date'] = format_timestamp(member['birthday'])
  1477. # 获取现有关系
  1478. cursor.execute("SELECT * FROM family_relation_info WHERE source_mid = %s LIMIT 1", (member_id,))
  1479. current_relation = cursor.fetchone()
  1480. cursor.execute("SELECT id, name FROM family_member_info WHERE id != %s ORDER BY name", (member_id,))
  1481. all_members = cursor.fetchall()
  1482. cursor.execute("SELECT * FROM genealogy_records ORDER BY page_number ASC")
  1483. images = cursor.fetchall()
  1484. finally:
  1485. conn.close()
  1486. # Calculate selected_member_name based on current_relation
  1487. selected_member_name = ''
  1488. if current_relation and current_relation['parent_mid']:
  1489. for m in all_members:
  1490. if m['id'] == current_relation['parent_mid']:
  1491. selected_member_name = m['name']
  1492. break
  1493. # Get source_record_id from member data
  1494. source_record_id = member.get('source_record_id') if member else None
  1495. return render_template('add_member.html', member=member, images=images, all_members=all_members, current_relation=current_relation, selected_member_name=selected_member_name, source_record_id=source_record_id)
  1496. @app.route('/manager/member_detail/<int:member_id>')
  1497. def member_detail(member_id):
  1498. if 'user_id' not in session:
  1499. return redirect(url_for('login'))
  1500. conn = get_db_connection()
  1501. try:
  1502. with conn.cursor() as cursor:
  1503. # Join with genealogy_records to get source image info
  1504. sql = """
  1505. SELECT m.*, r.oss_url as source_image_url, r.page_number as source_page,
  1506. r.genealogy_version, r.genealogy_source, r.upload_person
  1507. FROM family_member_info m
  1508. LEFT JOIN genealogy_records r ON m.source_record_id = r.id
  1509. WHERE m.id = %s
  1510. """
  1511. cursor.execute(sql, (member_id,))
  1512. member = cursor.fetchone()
  1513. if not member:
  1514. flash('成员不存在')
  1515. return redirect(url_for('members'))
  1516. member['birthday_str'] = format_timestamp(member.get('birthday'))
  1517. # 获取关系
  1518. cursor.execute("""
  1519. SELECT m.id, m.name, r.relation_type
  1520. FROM family_relation_info r
  1521. JOIN family_member_info m ON r.parent_mid = m.id
  1522. WHERE r.child_mid = %s
  1523. """, (member_id,))
  1524. parents = cursor.fetchall()
  1525. cursor.execute("""
  1526. SELECT m.id, m.name, r.relation_type
  1527. FROM family_relation_info r
  1528. JOIN family_member_info m ON r.child_mid = m.id
  1529. WHERE r.parent_mid = %s
  1530. """, (member_id,))
  1531. children = cursor.fetchall()
  1532. finally:
  1533. conn.close()
  1534. return render_template('member_detail.html', member=member, parents=parents, children=children)
  1535. @app.route('/manager/delete_member/<int:member_id>', methods=['POST'])
  1536. def delete_member(member_id):
  1537. if 'user_id' not in session:
  1538. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1539. conn = get_db_connection()
  1540. try:
  1541. with conn.cursor() as cursor:
  1542. # 1. 删除关系表中关联该成员的所有记录
  1543. cursor.execute("DELETE FROM family_relation_info WHERE parent_mid = %s OR child_mid = %s OR source_mid = %s",
  1544. (member_id, member_id, member_id))
  1545. # 2. 删除成员本身
  1546. cursor.execute("DELETE FROM family_member_info WHERE id = %s", (member_id,))
  1547. conn.commit()
  1548. flash('成员及其关系已成功删除')
  1549. return redirect(url_for('members'))
  1550. except Exception as e:
  1551. conn.rollback()
  1552. flash(f'删除失败: {e}')
  1553. return redirect(url_for('members'))
  1554. finally:
  1555. conn.close()
  1556. @app.route('/manager/login', methods=['GET', 'POST'])
  1557. def login():
  1558. if request.method == 'POST':
  1559. username = request.form['username']
  1560. password = request.form['password']
  1561. try:
  1562. conn = get_db_connection()
  1563. try:
  1564. with conn.cursor() as cursor:
  1565. cursor.execute("SELECT * FROM users WHERE username=%s AND password=%s", (username, password))
  1566. user = cursor.fetchone()
  1567. if user:
  1568. session['user_id'] = user['id']
  1569. session['username'] = user['username']
  1570. return redirect(url_for('index'))
  1571. else:
  1572. flash('用户名或密码错误')
  1573. finally:
  1574. conn.close()
  1575. except Exception as e:
  1576. flash(f'数据库连接错误: {str(e)}')
  1577. print(f'Login error: {str(e)}')
  1578. return render_template('login.html')
  1579. @app.route('/manager/logout')
  1580. def logout():
  1581. session.clear()
  1582. return redirect(url_for('login'))
  1583. @app.route('/manager/api/check_name')
  1584. def check_name():
  1585. if 'user_id' not in session:
  1586. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1587. name = request.args.get('name', '').strip()
  1588. if not name:
  1589. return jsonify({"success": True, "exists": False})
  1590. conn = get_db_connection()
  1591. try:
  1592. with conn.cursor() as cursor:
  1593. # Check for name or simplified_name match
  1594. 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))
  1595. matches = cursor.fetchall()
  1596. if matches:
  1597. # Format birthday for display
  1598. for m in matches:
  1599. if m.get('birthday'):
  1600. m['birthday_str'] = format_timestamp(m['birthday'])
  1601. else:
  1602. m['birthday_str'] = '未知'
  1603. return jsonify({"success": True, "exists": True, "matches": matches})
  1604. else:
  1605. return jsonify({"success": True, "exists": False})
  1606. except Exception as e:
  1607. return jsonify({"success": False, "error": str(e)}), 500
  1608. finally:
  1609. conn.close()
  1610. import requests
  1611. import json
  1612. import re
  1613. @app.route('/manager/api/recognize_image', methods=['POST'])
  1614. def recognize_image():
  1615. if 'user_id' not in session:
  1616. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1617. data = request.json
  1618. image_url = data.get('image_url')
  1619. if not image_url:
  1620. return jsonify({"success": False, "message": "No image URL provided"}), 400
  1621. api_key = "a1800657-9212-4afe-9b7c-b49f015c54d3"
  1622. api_url = "https://ark.cn-beijing.volces.com/api/v3/responses"
  1623. prompt = """
  1624. 请分析这张家谱图片,提取其中关于人物的信息。
  1625. 请务必将繁体字转换为简体字(original_name 字段除外)。
  1626. 特别注意:'name' 字段必须是纯简体中文,不能包含繁体字(例如:'學'应转换为'学','劉'应转换为'刘','萬'应转换为'万')。
  1627. 请提取以下字段(如果存在):
  1628. - original_name: 原始姓名(严格保持图片上的繁体字,不做任何修改或转换)
  1629. - name: 简体姓名(必须转换为简体中文,去除不需要的敬称)
  1630. - sex: 性别(男/女)
  1631. - birthday: 出生日期(尝试转换为YYYY-MM-DD格式,如果无法确定年份可只填月日)
  1632. - death_date: 逝世日期(如文本中出现“殁”、“葬”、“卒”等字眼及其对应的时间,请提取)
  1633. - father_name: 父亲姓名
  1634. - spouse_name: 配偶姓名
  1635. - generation: 第几世/代数
  1636. - name_word: 字辈(例如名字为“学勤公”,“学”为字辈;提取名字中的字辈信息)
  1637. - education: 学历/功名
  1638. - title: 官职/称号
  1639. 请严格以JSON列表格式返回,不要包含Markdown代码块标记(如 ```json ... ```),直接返回JSON数组。
  1640. 如果包含多个人物,请都提取出来。
  1641. """
  1642. ai_payload_url = get_normalized_base64_image(image_url)
  1643. payload = {
  1644. "model": "doubao-seed-1-8-251228",
  1645. "stream": True,
  1646. "input": [
  1647. {
  1648. "role": "user",
  1649. "content": [
  1650. {
  1651. "type": "input_image",
  1652. "image_url": ai_payload_url
  1653. },
  1654. {
  1655. "type": "input_text",
  1656. "text": prompt
  1657. }
  1658. ]
  1659. }
  1660. ]
  1661. }
  1662. headers = {
  1663. "Authorization": f"Bearer {api_key}",
  1664. "Content-Type": "application/json"
  1665. }
  1666. def generate():
  1667. yield "正在连接 AI 服务...\n"
  1668. try:
  1669. # 使用 stream=True, timeout=120
  1670. # 增加 verify=False 以防 SSL 问题(开发环境)
  1671. # 增加 proxies=None 以防本地代理干扰
  1672. with requests.post(
  1673. api_url,
  1674. json=payload,
  1675. headers=headers,
  1676. stream=True,
  1677. timeout=1200,
  1678. verify=False,
  1679. proxies={"http": None, "https": None}
  1680. ) as r:
  1681. if r.status_code != 200:
  1682. yield f"Error: API returned status code {r.status_code}. Response: {r.text}"
  1683. return
  1684. yield "连接成功,正在等待 AI 响应...\n"
  1685. full_reasoning = ""
  1686. json_started = False
  1687. for line in r.iter_lines():
  1688. if line:
  1689. line_str = line.decode('utf-8')
  1690. if line_str.startswith('data: '):
  1691. json_str = line_str[6:]
  1692. if json_str.strip() == '[DONE]':
  1693. break
  1694. try:
  1695. chunk = json.loads(json_str)
  1696. # 处理 standard OpenAI choices format (content)
  1697. if 'choices' in chunk and len(chunk['choices']) > 0:
  1698. delta = chunk['choices'][0].get('delta', {})
  1699. if 'content' in delta:
  1700. if not json_started:
  1701. yield "|||JSON_START|||"
  1702. json_started = True
  1703. yield delta['content']
  1704. # 处理 standard OpenAI choices format (reasoning_content) if any
  1705. if 'reasoning_content' in delta:
  1706. yield f"\n[推理]: {delta['reasoning_content']}"
  1707. # 处理 Doubao/Volcano specific formats
  1708. # Type: response.reasoning_summary_text.delta
  1709. if chunk.get('type') == 'response.reasoning_summary_text.delta':
  1710. if 'delta' in chunk:
  1711. yield chunk['delta']
  1712. # Type: response.text.delta
  1713. if chunk.get('type') == 'response.text.delta':
  1714. if 'delta' in chunk:
  1715. if not json_started:
  1716. yield "|||JSON_START|||"
  1717. json_started = True
  1718. yield chunk['delta']
  1719. # Type: response.output_item.added (May contain initial content or status)
  1720. # Type: response.reasoning_summary_part.added
  1721. except Exception as e:
  1722. print(f"Chunk parse error: {e}")
  1723. else:
  1724. # 尝试直接解析非 data: 开头的行
  1725. try:
  1726. chunk = json.loads(line_str)
  1727. if 'choices' in chunk and len(chunk['choices']) > 0:
  1728. content = chunk['choices'][0]['message']['content']
  1729. yield content
  1730. except:
  1731. pass
  1732. except Exception as e:
  1733. yield f"\n[Error: {str(e)}]"
  1734. return Response(stream_with_context(generate()), mimetype='text/plain')
  1735. @app.route('/manager/api/start_analysis/<int:record_id>', methods=['POST'])
  1736. def start_analysis(record_id):
  1737. if 'user_id' not in session:
  1738. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1739. conn = get_db_connection()
  1740. try:
  1741. with conn.cursor() as cursor:
  1742. # Check if record exists
  1743. cursor.execute("SELECT oss_url, ai_status FROM genealogy_records WHERE id = %s", (record_id,))
  1744. record = cursor.fetchone()
  1745. if not record:
  1746. return jsonify({"success": False, "message": "Record not found"}), 404
  1747. # Update status to processing (1)
  1748. cursor.execute("UPDATE genealogy_records SET ai_status = 1 WHERE id = %s", (record_id,))
  1749. conn.commit()
  1750. # Start background task
  1751. threading.Thread(target=process_ai_task, args=(record_id, record['oss_url'])).start()
  1752. return jsonify({"success": True, "message": "Analysis started"})
  1753. except Exception as e:
  1754. return jsonify({"success": False, "message": str(e)}), 500
  1755. finally:
  1756. conn.close()
  1757. def process_files_background(upload_folder, saved_files, manual_page, suggested_page, genealogy_version, genealogy_source, upload_person):
  1758. current_suggested_page = int(manual_page) if manual_page and str(manual_page).isdigit() else suggested_page
  1759. ensure_pdf_table()
  1760. for item in saved_files:
  1761. if len(item) >= 4:
  1762. filename, file_path, file_page, original_filename = item[0], item[1], item[2], item[3]
  1763. elif len(item) == 3:
  1764. filename, file_path, file_page = item
  1765. original_filename = filename
  1766. else:
  1767. filename, file_path = item[0], item[1]
  1768. file_page = None
  1769. original_filename = filename
  1770. try:
  1771. if filename.lower().endswith('.pdf'):
  1772. import uuid
  1773. display_pdf_name = (original_filename or filename).strip() or filename
  1774. oss_pdf_name = secure_filename(display_pdf_name)
  1775. if not oss_pdf_name or not oss_pdf_name.lower().endswith('.pdf'):
  1776. oss_pdf_name = f"genealogy_pdf_{uuid.uuid4().hex[:8]}.pdf"
  1777. pdf_oss_url = upload_to_oss(file_path, custom_filename=oss_pdf_name)
  1778. if pdf_oss_url:
  1779. desc_parts = []
  1780. if genealogy_version:
  1781. desc_parts.append(genealogy_version)
  1782. if genealogy_source:
  1783. desc_parts.append(genealogy_source)
  1784. pdf_description = ' · '.join(desc_parts) if desc_parts else ''
  1785. conn_pdf = get_db_connection()
  1786. try:
  1787. with conn_pdf.cursor() as cursor:
  1788. cursor.execute(
  1789. "INSERT INTO genealogy_pdfs (file_name, oss_url, description, uploader) VALUES (%s, %s, %s, %s)",
  1790. (display_pdf_name, pdf_oss_url, pdf_description, upload_person or '')
  1791. )
  1792. conn_pdf.commit()
  1793. except Exception as pdf_meta_e:
  1794. print(f"Error inserting genealogy_pdfs for {display_pdf_name}: {pdf_meta_e}")
  1795. finally:
  1796. conn_pdf.close()
  1797. else:
  1798. print(f"Warning: full PDF upload to OSS failed for {filename}, scan pages will still be processed.")
  1799. doc = fitz.open(file_path)
  1800. for page_index in range(len(doc)):
  1801. img_path = None
  1802. try:
  1803. page = doc.load_page(page_index)
  1804. max_dim = max(page.rect.width, page.rect.height)
  1805. zoom = 2000 / max_dim if max_dim > 0 else 2.0
  1806. if zoom > 2.5: zoom = 2.5
  1807. mat = fitz.Matrix(zoom, zoom)
  1808. # Use get_pixmap with matrix directly
  1809. pix = page.get_pixmap(matrix=mat)
  1810. final_page = current_suggested_page
  1811. if genealogy_version and genealogy_source:
  1812. if final_page is not None and str(final_page).strip() != '':
  1813. img_filename = f"{genealogy_version}_{genealogy_source}_{final_page}.jpg"
  1814. else:
  1815. img_filename = f"{genealogy_version}_{genealogy_source}.jpg"
  1816. else:
  1817. img_filename = f"{os.path.splitext(filename)[0]}_page_{page_index+1}.jpg"
  1818. img_path = os.path.join(upload_folder, img_filename)
  1819. # Save the pixmap to the image path
  1820. pix.save(img_path)
  1821. oss_url = upload_to_oss(img_path, custom_filename=img_filename)
  1822. if oss_url:
  1823. conn = get_db_connection()
  1824. try:
  1825. with conn.cursor() as cursor:
  1826. sql = """INSERT INTO genealogy_records
  1827. (file_name, oss_url, page_number, ai_status, genealogy_version, genealogy_source, upload_person, file_type)
  1828. VALUES (%s, %s, %s, 1, %s, %s, %s, %s)"""
  1829. cursor.execute(sql, (img_filename, oss_url, final_page, genealogy_version, genealogy_source, upload_person, 'PDF'))
  1830. record_id = cursor.lastrowid
  1831. conn.commit()
  1832. threading.Thread(target=process_ai_task, args=(record_id, oss_url)).start()
  1833. current_suggested_page += 1
  1834. finally:
  1835. conn.close()
  1836. except Exception as page_e:
  1837. print(f"Error processing page {page_index} of {filename}: {page_e}")
  1838. finally:
  1839. if img_path and os.path.exists(img_path):
  1840. try:
  1841. os.remove(img_path)
  1842. except:
  1843. pass
  1844. doc.close()
  1845. else:
  1846. img_path = compress_image_if_needed(file_path)
  1847. # Use explicitly set page number if provided, otherwise extract from filename or auto-increment
  1848. if file_page and str(file_page).isdigit():
  1849. final_page = int(file_page)
  1850. current_suggested_page = final_page + 1
  1851. page_num = final_page
  1852. else:
  1853. page_num = extract_page_number(img_path)
  1854. final_page = page_num if page_num else current_suggested_page
  1855. ext = os.path.splitext(img_path)[1]
  1856. if genealogy_version and genealogy_source:
  1857. if final_page is not None and str(final_page).strip() != '':
  1858. img_filename = f"{genealogy_version}_{genealogy_source}_{final_page}{ext}"
  1859. else:
  1860. img_filename = f"{genealogy_version}_{genealogy_source}{ext}"
  1861. else:
  1862. img_filename = os.path.basename(img_path)
  1863. oss_url = upload_to_oss(img_path, custom_filename=img_filename)
  1864. if oss_url:
  1865. conn = get_db_connection()
  1866. try:
  1867. with conn.cursor() as cursor:
  1868. sql = """INSERT INTO genealogy_records
  1869. (file_name, oss_url, page_number, ai_status, genealogy_version, genealogy_source, upload_person, file_type)
  1870. VALUES (%s, %s, %s, 1, %s, %s, %s, %s)"""
  1871. cursor.execute(sql, (img_filename, oss_url, final_page, genealogy_version, genealogy_source, upload_person, '图片'))
  1872. record_id = cursor.lastrowid
  1873. conn.commit()
  1874. threading.Thread(target=process_ai_task, args=(record_id, oss_url)).start()
  1875. if page_num:
  1876. current_suggested_page = page_num + 1
  1877. else:
  1878. current_suggested_page += 1
  1879. finally:
  1880. conn.close()
  1881. if img_path and img_path != file_path and os.path.exists(img_path):
  1882. try:
  1883. os.remove(img_path)
  1884. except:
  1885. pass
  1886. except Exception as e:
  1887. print(f"Error processing file {filename}: {e}")
  1888. finally:
  1889. if os.path.exists(file_path):
  1890. try:
  1891. os.remove(file_path)
  1892. except:
  1893. pass
  1894. @app.route('/manager/upload', methods=['GET', 'POST'])
  1895. def upload():
  1896. if 'user_id' not in session:
  1897. return redirect(url_for('login'))
  1898. # 获取建议页码 (当前最大页码 + 1)
  1899. conn = get_db_connection()
  1900. suggested_page = 1
  1901. try:
  1902. with conn.cursor() as cursor:
  1903. cursor.execute("SELECT MAX(page_number) as max_p FROM genealogy_records")
  1904. result = cursor.fetchone()
  1905. if result and result['max_p']:
  1906. suggested_page = result['max_p'] + 1
  1907. finally:
  1908. conn.close()
  1909. if request.method == 'POST':
  1910. if 'file' not in request.files:
  1911. flash('未选择文件')
  1912. return redirect(request.url)
  1913. files = request.files.getlist('file')
  1914. if not files or files[0].filename == '':
  1915. flash('未选择文件')
  1916. return redirect(request.url)
  1917. manual_page = request.form.get('manual_page')
  1918. genealogy_version = request.form.get('genealogy_version', '')
  1919. genealogy_source = request.form.get('genealogy_source', '')
  1920. upload_person = request.form.get('upload_person', '')
  1921. if not upload_person:
  1922. upload_person = session.get('username', '')
  1923. import uuid
  1924. saved_files = []
  1925. for i, file in enumerate(files):
  1926. if not file or not file.filename:
  1927. continue
  1928. original_filename = file.filename
  1929. ext = os.path.splitext(original_filename)[1].lower()
  1930. base_name = secure_filename(original_filename)
  1931. # If secure_filename removes all characters (e.g., pure Chinese name) or just leaves 'pdf'
  1932. if not base_name or base_name == ext.strip('.'):
  1933. filename = f"upload_{uuid.uuid4().hex[:8]}{ext}"
  1934. else:
  1935. # Ensure the extension is preserved
  1936. if not base_name.lower().endswith(ext):
  1937. filename = f"{base_name}{ext}"
  1938. else:
  1939. filename = base_name
  1940. file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
  1941. file.save(file_path)
  1942. # Fetch individual page number if it exists
  1943. file_page = request.form.get(f'page_number_{i}')
  1944. saved_files.append((filename, file_path, file_page, original_filename))
  1945. if saved_files:
  1946. threading.Thread(
  1947. target=process_files_background,
  1948. args=(app.config['UPLOAD_FOLDER'], saved_files, manual_page, suggested_page, genealogy_version, genealogy_source, upload_person)
  1949. ).start()
  1950. flash('上传完成,AI解析中,稍后查看')
  1951. time.sleep(1.5)
  1952. return redirect(url_for('index'))
  1953. return render_template('upload.html', suggested_page=suggested_page)
  1954. @app.route('/manager/save_upload', methods=['POST'])
  1955. def save_upload():
  1956. if 'user_id' not in session: return redirect(url_for('login'))
  1957. filename = request.form.get('filename')
  1958. oss_url = request.form.get('oss_url')
  1959. page_number = request.form.get('page_number')
  1960. genealogy_version = request.form.get('genealogy_version', '')
  1961. genealogy_source = request.form.get('genealogy_source', '')
  1962. upload_person = request.form.get('upload_person', session.get('username', ''))
  1963. file_type = request.form.get('file_type', '图片')
  1964. if not oss_url or not page_number:
  1965. flash('页码不能为空')
  1966. return redirect(url_for('upload'))
  1967. conn = get_db_connection()
  1968. try:
  1969. with conn.cursor() as cursor:
  1970. sql = """INSERT INTO genealogy_records
  1971. (file_name, oss_url, page_number, ai_status, genealogy_version, genealogy_source, upload_person, file_type)
  1972. VALUES (%s, %s, %s, 1, %s, %s, %s, %s)"""
  1973. cursor.execute(sql, (filename, oss_url, page_number, genealogy_version, genealogy_source, upload_person, file_type))
  1974. record_id = cursor.lastrowid
  1975. conn.commit()
  1976. # Start AI Task
  1977. threading.Thread(target=process_ai_task, args=(record_id, oss_url)).start()
  1978. flash('上传完成,AI解析中,稍后查看')
  1979. except Exception as e:
  1980. flash(f'保存失败: {e}')
  1981. finally:
  1982. conn.close()
  1983. return redirect(url_for('index'))
  1984. @app.route('/manager/delete_upload/<int:record_id>', methods=['POST'])
  1985. def delete_upload(record_id):
  1986. if 'user_id' not in session:
  1987. return jsonify({"success": False, "message": "Unauthorized"}), 401
  1988. conn = get_db_connection()
  1989. try:
  1990. with conn.cursor() as cursor:
  1991. # 删除记录
  1992. cursor.execute("DELETE FROM genealogy_records WHERE id = %s", (record_id,))
  1993. conn.commit()
  1994. flash('文件记录已成功删除')
  1995. return redirect(url_for('index'))
  1996. except Exception as e:
  1997. conn.rollback()
  1998. flash(f'删除失败: {e}')
  1999. return redirect(url_for('index'))
  2000. finally:
  2001. conn.close()
  2002. @app.route('/manager/upload_pdf', methods=['GET', 'POST'])
  2003. def upload_pdf():
  2004. if 'user_id' not in session:
  2005. return redirect(url_for('login'))
  2006. if request.method == 'GET':
  2007. return render_template('upload_pdf.html')
  2008. # POST请求处理
  2009. if 'file' not in request.files:
  2010. flash('请选择要上传的PDF文件')
  2011. return redirect(request.url)
  2012. file = request.files['file']
  2013. if file.filename == '':
  2014. flash('请选择要上传的PDF文件')
  2015. return redirect(request.url)
  2016. # 检查文件类型
  2017. if not file.filename.lower().endswith('.pdf'):
  2018. flash('只支持PDF文件上传')
  2019. return redirect(request.url)
  2020. # 获取表单数据
  2021. version_name = request.form.get('version_name', '').strip()
  2022. version_source = request.form.get('version_source', '').strip()
  2023. file_provider = request.form.get('file_provider', '').strip()
  2024. # 验证必填字段
  2025. if not version_name:
  2026. flash('版本名称为必填项')
  2027. return redirect(request.url)
  2028. if not version_source:
  2029. flash('版本来源为必填项')
  2030. return redirect(request.url)
  2031. # 如果未提供文件提供人,使用当前登录用户
  2032. if not file_provider:
  2033. file_provider = session.get('user_id', '未知')
  2034. import uuid
  2035. original_filename = file.filename
  2036. ext = os.path.splitext(original_filename)[1].lower()
  2037. base_name = secure_filename(original_filename)
  2038. if not base_name or base_name == ext.strip('.'):
  2039. filename = f"genealogy_pdf_{uuid.uuid4().hex[:8]}{ext}"
  2040. else:
  2041. if not base_name.lower().endswith(ext):
  2042. filename = f"{base_name}{ext}"
  2043. else:
  2044. filename = base_name
  2045. file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
  2046. file.save(file_path)
  2047. try:
  2048. # Upload to OSS
  2049. oss_url = upload_to_oss(file_path, custom_filename=filename)
  2050. if not oss_url:
  2051. flash('文件上传失败')
  2052. return redirect(request.url)
  2053. # Save to database
  2054. conn = get_db_connection()
  2055. try:
  2056. with conn.cursor() as cursor:
  2057. cursor.execute(
  2058. "INSERT INTO genealogy_pdfs (file_name, oss_url, version_name, version_source, file_provider, upload_time) VALUES (%s, %s, %s, %s, %s, CURRENT_TIMESTAMP)",
  2059. (original_filename, oss_url, version_name, version_source, file_provider)
  2060. )
  2061. conn.commit()
  2062. flash('PDF文件上传成功')
  2063. return redirect(url_for('pdf_management'))
  2064. except Exception as e:
  2065. flash(f'保存失败: {e}')
  2066. return redirect(request.url)
  2067. finally:
  2068. conn.close()
  2069. finally:
  2070. if os.path.exists(file_path):
  2071. try:
  2072. os.remove(file_path)
  2073. except:
  2074. pass
  2075. def process_pdf_pages(file_path, pdf_oss_url, uploader):
  2076. """Process PDF pages and add them to genealogy records"""
  2077. try:
  2078. import fitz
  2079. doc = fitz.open(file_path)
  2080. # Get current max page number
  2081. conn = get_db_connection()
  2082. suggested_page = 1
  2083. try:
  2084. with conn.cursor() as cursor:
  2085. cursor.execute("SELECT MAX(page_number) as max_p FROM genealogy_records")
  2086. result = cursor.fetchone()
  2087. if result and result['max_p']:
  2088. suggested_page = result['max_p'] + 1
  2089. finally:
  2090. conn.close()
  2091. for page_index in range(len(doc)):
  2092. try:
  2093. page = doc[page_index]
  2094. pix = page.get_pixmap(dpi=150)
  2095. # Save as image
  2096. img_filename = f"{os.path.splitext(os.path.basename(file_path))[0]}_page_{page_index+1}.jpg"
  2097. img_path = os.path.join(app.config['UPLOAD_FOLDER'], img_filename)
  2098. pix.save(img_path)
  2099. # Upload to OSS
  2100. img_oss_url = upload_to_oss(img_path, custom_filename=img_filename)
  2101. if img_oss_url:
  2102. # Save to genealogy_records
  2103. conn = get_db_connection()
  2104. try:
  2105. with conn.cursor() as cursor:
  2106. cursor.execute(
  2107. "INSERT INTO genealogy_records (file_name, oss_url, page_number, ai_status, upload_person, file_type) VALUES (%s, %s, %s, 1, %s, %s)",
  2108. (img_filename, img_oss_url, suggested_page + page_index, uploader, '图片')
  2109. )
  2110. record_id = cursor.lastrowid
  2111. conn.commit()
  2112. # Start AI processing
  2113. threading.Thread(target=process_ai_task, args=(record_id, img_oss_url)).start()
  2114. finally:
  2115. conn.close()
  2116. except Exception as e:
  2117. print(f"Error processing page {page_index+1}: {e}")
  2118. finally:
  2119. if 'img_path' in locals() and os.path.exists(img_path):
  2120. try:
  2121. os.remove(img_path)
  2122. except:
  2123. pass
  2124. except Exception as e:
  2125. print(f"Error processing PDF: {e}")
  2126. if __name__ == '__main__':
  2127. app.run(debug=False, port=5001)