-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.py
More file actions
7099 lines (6595 loc) · 360 KB
/
Copy pathserver.py
File metadata and controls
7099 lines (6595 loc) · 360 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""知产管家 · IP Keeper — 本地服务器"""
import os, json, sqlite3, mimetypes, math, zipfile, re, shutil, uuid, threading, calendar, unicodedata, subprocess, tempfile
import hashlib
from difflib import SequenceMatcher
from rules.dates import (_to_date, _add_years, _add_months, _month_end)
from rules.common import (_as_bool, norm_patent_type)
from rules.versions import (RULESET_VERSION, CNIPA_PATENT_LAW_URL, CNIPA_OA_URL, CNIPA_FEE_REDUCTION_URL, CNIPA_TM_2026_URL, PATENT_FEE_RULE_VERSION, LEGAL_RULE_VERSIONS)
from rules.cn_patent_term import (DESIGN_TERM_CHANGE_DATE, patent_term_years)
from rules.cn_patent_fee import (FEE_TABLE, FEE_REDUCTION_YEARS, FEE_SINGLE_OWNER_RATIO, FEE_MULTIPLE_OWNER_RATIO, annual_fee_late_rate, patent_owner_count, normalize_fee_reduction_status, resolve_fee_reduction_ratio, patent_grant_fee_year, calculate_cn_annual_fee)
from rules.cn_deadline import (calculate_legal_deadline)
from contextlib import nullcontext
from ipkeeper_alert_center import SCHEMA as ALERT_CENTER_SCHEMA, register as register_alert_center
from datetime import datetime, date, timedelta
from pathlib import Path
from io import BytesIO
from flask import Flask, request, jsonify, send_file, send_from_directory
from ipkeeper_attachment_utils import build_duplicate_groups, file_sha256
from ipkeeper_backup_utils import (
BackupValidationError,
create_backup_archive,
database_is_valid as backup_database_is_valid,
directory_summary,
extract_and_validate_backup,
)
CODE_DIR = Path(__file__).parent.resolve()
BASE_DIR = CODE_DIR
DB_PATH = BASE_DIR / "ipkeeper.db"
UPLOAD_DIR = BASE_DIR / "uploads"
STATIC_DIR = CODE_DIR / "static"
DEFAULT_WATCH_DIR = BASE_DIR / "待关联"
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
DEFAULT_WATCH_DIR.mkdir(parents=True, exist_ok=True)
# ── 启动诊断 ────────────────────────────────────────────────
print(f"ℹ️ BASE_DIR = {BASE_DIR}")
print(f"ℹ️ STATIC_DIR = {STATIC_DIR}")
print(f"ℹ️ index.html 存在: {(STATIC_DIR/'index.html').exists()}")
if not (STATIC_DIR/'index.html').exists():
print(f"❌ 错误:static/index.html 不存在!")
print(f" 请确保解压后的所有文件在同一个目录")
app = Flask(__name__, static_folder=str(STATIC_DIR))
app.config['MAX_CONTENT_LENGTH'] = int(
os.environ.get('IPKEEPER_MAX_UPLOAD_BYTES', str(2 * 1024 * 1024 * 1024))
)
WEB_PORT = int(os.environ.get('IPKEEPER_PORT', '5678'))
APP_VERSION = 'web'
BACKUP_OPERATION_LOCK = threading.Lock()
BACKUP_STATUS_LOCK = threading.Lock()
BACKUP_STATUS = {
'active': False,
'kind': '',
'phase': 'idle',
'sequence': 0,
'error': '',
}
AUTO_BACKUP_STARTED = False
MAINTENANCE_MODE = False
# File analysis is relatively expensive (especially OCR). Cache watch-folder
# analysis by absolute path + mtime + size so refreshing the watch view does not
# repeatedly re-read unchanged files. The cache is intentionally process-local;
# changing or replacing a file invalidates its key automatically.
WATCH_ANALYSIS_CACHE = {}
WATCH_ANALYSIS_CACHE_LIMIT = 512
ALLOWED_EXT = {'.pdf','.png','.jpg','.jpeg','.docx','.doc','.xlsx','.xls',
'.zip','.rar','.txt','.ofd','.msg','.eml'}
USPTO_MAINTENANCE_URL = 'https://www.uspto.gov/patents/maintain'
EPO_UNITARY_RENEWAL_URL = 'https://www.epo.org/en/legal/guidelines-up/2026/section_3_7'
def _clean_filename(name):
base = Path(name or "attachment").name
cleaned = "".join(c for c in base if c.isalnum() or c in "._-")
return cleaned or "attachment"
def _doc_mime(name):
return mimetypes.guess_type(name or "")[0] or "application/octet-stream"
def _safe_document_filename(item_type, item_id, original_name):
ext = Path(original_name or "").suffix.lower()
ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f")
stem = Path(_clean_filename(original_name)).stem[:80] or "attachment"
return f"{item_type}_{item_id}_{ts}_{uuid.uuid4().hex[:8]}_{stem}{ext}"
def _find_reusable_document_file(db, digest, size):
if not digest or not size:
return None
rows = db.execute("""
SELECT filename, mime_type
FROM documents
WHERE file_hash=? AND file_size=?
ORDER BY id DESC
""", (digest, size)).fetchall()
for row in rows:
filename = row["filename"]
if filename and (UPLOAD_DIR / filename).exists():
return dict(row)
return None
def _store_document_source(db, source_path, original_name, item_type, item_id, move=False):
"""Store one physical file, reusing identical content when possible."""
source_path = Path(source_path)
size = source_path.stat().st_size
digest = file_sha256(source_path)
mime = _doc_mime(original_name)
existing = _find_reusable_document_file(db, digest, size)
if existing:
if move:
try:
source_path.unlink(missing_ok=True)
except Exception:
pass
return {
"filename": existing["filename"],
"file_size": size,
"mime_type": existing.get("mime_type") or mime,
"file_hash": digest,
"reused": True,
"path": UPLOAD_DIR / existing["filename"],
}
safe = _safe_document_filename(item_type, item_id, original_name)
dest = UPLOAD_DIR / safe
if move:
shutil.move(str(source_path), str(dest))
else:
shutil.copy2(source_path, dest)
return {
"filename": safe,
"file_size": dest.stat().st_size,
"mime_type": mime,
"file_hash": digest,
"reused": False,
"path": dest,
}
def _ensure_document_hashes(db, limit=0):
sql = """
SELECT id, filename, file_size
FROM documents
WHERE COALESCE(file_hash, '')=''
ORDER BY id
"""
if limit:
sql += f" LIMIT {int(limit)}"
changed = 0
for row in db.execute(sql).fetchall():
path = UPLOAD_DIR / row["filename"]
if not path.exists() or not path.is_file():
continue
try:
size = path.stat().st_size
db.execute(
"UPDATE documents SET file_hash=?, file_size=COALESCE(file_size, ?) WHERE id=?",
(file_sha256(path), size, row["id"]),
)
changed += 1
except Exception:
continue
return changed
def _unlink_if_unreferenced(db, filename):
if not filename:
return False
row = db.execute("SELECT COUNT(*) AS c FROM documents WHERE filename=?", (filename,)).fetchone()
if row and row["c"]:
return False
try:
(UPLOAD_DIR / filename).unlink(missing_ok=True)
return True
except Exception:
return False
TRASH_TYPE_LABELS = {
'patent': '专利',
'trademark': '商标',
'copyright': '软著',
'document': '附件',
'fee_payment': '年费记录',
'status_history': '状态记录',
'trademark_logo': '商标图',
'fee_receipt': '缴费凭证',
}
def _trash_add(db, item_type, item_id, name, payload):
"""Store a complete recoverable snapshot. Recycle-bin rows are never auto-purged."""
cur = db.execute(
"""INSERT INTO recycle_bin(item_type,item_id,name,payload,deleted_at)
VALUES(?,?,?,?,?)""",
(item_type, item_id, name or TRASH_TYPE_LABELS.get(item_type, '已删除数据'),
json.dumps(payload, ensure_ascii=False), now_str()),
)
return cur.lastrowid
def _rows_as_dicts(db, sql, params=()):
return [dict(row) for row in db.execute(sql, params).fetchall()]
def _insert_snapshot_row(db, table, row, replace_id=None, preserve_id=True):
allowed = {
'patents', 'trademarks', 'copyrights', 'documents',
'status_history', 'fee_payments', 'data_health_marks',
'legal_events',
}
if table not in allowed or not isinstance(row, dict) or not row:
raise ValueError('无效的恢复数据')
restored = dict(row)
if replace_id is not None and 'id' in restored:
restored['id'] = replace_id
if not preserve_id:
restored.pop('id', None)
columns = list(restored)
placeholders = ','.join('?' for _ in columns)
cur = db.execute(
f"INSERT INTO {table} ({','.join(columns)}) VALUES ({placeholders})",
[restored[column] for column in columns],
)
return restored.get('id') if preserve_id else cur.lastrowid
def _trash_payload_filenames(payload):
names = set()
if not isinstance(payload, dict):
return names
for doc in payload.get('documents', []):
if isinstance(doc, dict) and doc.get('filename'):
names.add(doc['filename'])
record = payload.get('record') or {}
if isinstance(record, dict):
for key in ('filename', 'receipt_filename', 'logo_filename'):
if record.get(key):
names.add(record[key])
for payment in payload.get('fee_payments', []):
if isinstance(payment, dict) and payment.get('receipt_filename'):
names.add(payment['receipt_filename'])
if payload.get('logo_filename'):
names.add(payload['logo_filename'])
if payload.get('receipt_filename'):
names.add(payload['receipt_filename'])
return names
def _file_is_referenced(db, filename, excluding_trash_id=None):
if not filename:
return False
if db.execute("SELECT 1 FROM documents WHERE filename=? LIMIT 1", (filename,)).fetchone():
return True
if db.execute("SELECT 1 FROM fee_payments WHERE receipt_filename=? LIMIT 1", (filename,)).fetchone():
return True
if db.execute("SELECT 1 FROM trademarks WHERE logo_filename=? LIMIT 1", (filename,)).fetchone():
return True
sql = "SELECT id,payload FROM recycle_bin"
params = []
if excluding_trash_id is not None:
sql += " WHERE id<>?"
params.append(excluding_trash_id)
for row in db.execute(sql, params).fetchall():
try:
if filename in _trash_payload_filenames(json.loads(row['payload'])):
return True
except Exception:
continue
return False
def _delete_document_rows(db, ids):
"""Move attachment rows to the recycle bin without removing physical files."""
ids = [int(x) for x in ids if str(x).strip()]
if not ids:
return {"deleted": 0, "files_removed": 0}
placeholders = ",".join("?" * len(ids))
rows = db.execute(f"SELECT * FROM documents WHERE id IN ({placeholders})", ids).fetchall()
if not rows:
return {"deleted": 0, "files_removed": 0}
trashed = 0
for row in rows:
record = dict(row)
marks = _rows_as_dicts(
db,
"SELECT * FROM data_health_marks WHERE item_type='document' AND item_id=?",
(str(row['id']),),
)
_trash_add(db, 'document', row['id'], record.get('original_name') or record.get('filename'), {
'version': 1,
'record': record,
'health_marks': marks,
})
db.execute("DELETE FROM data_health_marks WHERE item_type='document' AND item_id=?", (str(row['id']),))
db.execute("DELETE FROM documents WHERE id=?", (row['id'],))
trashed += 1
return {"deleted": trashed, "trashed": trashed, "files_removed": 0}
def _delete_item_documents(db, item_type, item_id):
rows = db.execute(
"SELECT id FROM documents WHERE item_type=? AND item_id=?",
(item_type, item_id),
).fetchall()
return _delete_document_rows(db, [row["id"] for row in rows])
RECORD_TABLE_BY_ITEM_TYPE = {
'patent': 'patents',
'trademark': 'trademarks',
'trademark_evidence': 'trademarks',
'copyright': 'copyrights',
}
def _record_exists(db, item_type, item_id):
table = RECORD_TABLE_BY_ITEM_TYPE.get(item_type)
if not table:
return False
try:
numeric_id = int(item_id)
except (TypeError, ValueError):
return False
return db.execute(f"SELECT 1 FROM {table} WHERE id=?", (numeric_id,)).fetchone() is not None
def _delete_health_marks_for_item(db, item_type, item_id):
db.execute(
"DELETE FROM data_health_marks WHERE item_type=? AND item_id=?",
(item_type, str(item_id)),
)
def _move_case_to_trash(db, item_type, item_id):
meta = {
'patent': ('patents', 'title', ('patent',)),
'trademark': ('trademarks', 'name', ('trademark', 'trademark_evidence')),
'copyright': ('copyrights', 'name', ('copyright',)),
}.get(item_type)
if not meta:
raise ValueError('不支持的数据类型')
table, name_key, document_types = meta
row = db.execute(f"SELECT * FROM {table} WHERE id=?", (item_id,)).fetchone()
if not row:
return None
record = dict(row)
doc_placeholders = ','.join('?' for _ in document_types)
documents = _rows_as_dicts(
db,
f"SELECT * FROM documents WHERE item_type IN ({doc_placeholders}) AND item_id=? ORDER BY id",
tuple(document_types) + (item_id,),
)
history = _rows_as_dicts(
db, "SELECT * FROM status_history WHERE item_type=? AND item_id=? ORDER BY id",
(item_type, item_id),
)
legal_events = _rows_as_dicts(
db, "SELECT * FROM legal_events WHERE item_type=? AND item_id=? ORDER BY id",
(item_type, item_id),
)
payments = _rows_as_dicts(
db, "SELECT * FROM fee_payments WHERE patent_id=? ORDER BY id", (item_id,),
) if item_type == 'patent' else []
mark_conditions = ["(item_type=? AND item_id=?)"]
mark_params = [item_type, str(item_id)]
for document in documents:
mark_conditions.append("(item_type='document' AND item_id=?)")
mark_params.append(str(document['id']))
health_marks = _rows_as_dicts(
db, "SELECT * FROM data_health_marks WHERE " + ' OR '.join(mark_conditions), mark_params,
)
trash_id = _trash_add(db, item_type, item_id, record.get(name_key), {
'version': 1,
'record': record,
'documents': documents,
'status_history': history,
'legal_events': legal_events,
'fee_payments': payments,
'health_marks': health_marks,
})
if documents:
document_ids = [document['id'] for document in documents]
placeholders = ','.join('?' for _ in document_ids)
db.execute(f"DELETE FROM documents WHERE id IN ({placeholders})", document_ids)
if health_marks:
db.executemany("DELETE FROM data_health_marks WHERE issue_id=?", [(mark['issue_id'],) for mark in health_marks])
db.execute("DELETE FROM status_history WHERE item_type=? AND item_id=?", (item_type, item_id))
db.execute("DELETE FROM legal_events WHERE item_type=? AND item_id=?", (item_type, item_id))
if item_type == 'patent':
db.execute("DELETE FROM fee_payments WHERE patent_id=?", (item_id,))
db.execute(f"DELETE FROM {table} WHERE id=?", (item_id,))
return trash_id
def _restore_health_marks(db, marks):
for mark in marks or []:
try:
_insert_snapshot_row(db, 'data_health_marks', mark)
except sqlite3.IntegrityError:
continue
def _restore_trash_entry(db, trash_row):
item_type = trash_row['item_type']
payload = json.loads(trash_row['payload'])
record = payload.get('record') or {}
root_meta = {
'patent': ('patents', 'patent'),
'trademark': ('trademarks', 'trademark'),
'copyright': ('copyrights', 'copyright'),
}.get(item_type)
if root_meta:
table, _ = root_meta
old_id = int(record.get('id'))
if db.execute(f"SELECT 1 FROM {table} WHERE id=?", (old_id,)).fetchone():
raise ValueError('原位置已有同编号数据,暂时无法恢复')
_insert_snapshot_row(db, table, record)
for history in payload.get('status_history', []):
_insert_snapshot_row(db, 'status_history', history)
for event in payload.get('legal_events', []):
_insert_snapshot_row(db, 'legal_events', event)
for payment in payload.get('fee_payments', []):
_insert_snapshot_row(db, 'fee_payments', payment)
for document in payload.get('documents', []):
_insert_snapshot_row(db, 'documents', document)
_restore_health_marks(db, payload.get('health_marks'))
return {'item_type': item_type, 'item_id': old_id}
if item_type == 'document':
if not _record_exists(db, record.get('item_type'), record.get('item_id')):
raise ValueError('关联案件不存在,请先恢复对应案件')
if db.execute("SELECT 1 FROM documents WHERE id=?", (record.get('id'),)).fetchone():
raise ValueError('原位置已有同编号附件,暂时无法恢复')
_insert_snapshot_row(db, 'documents', record)
_restore_health_marks(db, payload.get('health_marks'))
return {'item_type': item_type, 'item_id': record.get('id')}
if item_type == 'fee_payment':
if not db.execute("SELECT 1 FROM patents WHERE id=?", (record.get('patent_id'),)).fetchone():
raise ValueError('关联专利不存在,请先恢复对应专利')
_insert_snapshot_row(db, 'fee_payments', record)
return {'item_type': item_type, 'item_id': record.get('id')}
if item_type == 'status_history':
if not _record_exists(db, record.get('item_type'), record.get('item_id')):
raise ValueError('关联案件不存在,请先恢复对应案件')
_insert_snapshot_row(db, 'status_history', record)
return {'item_type': item_type, 'item_id': record.get('id')}
if item_type == 'trademark_logo':
trademark_id = payload.get('trademark_id')
current = db.execute("SELECT name,logo_filename FROM trademarks WHERE id=?", (trademark_id,)).fetchone()
if not current:
raise ValueError('关联商标不存在,请先恢复对应商标')
if current['logo_filename'] and current['logo_filename'] != payload.get('logo_filename'):
_trash_add(db, 'trademark_logo', trademark_id, f"{current['name']} · 商标图", {
'version': 1,
'trademark_id': trademark_id,
'logo_filename': current['logo_filename'],
})
db.execute(
"UPDATE trademarks SET logo_filename=?,updated_at=? WHERE id=?",
(payload.get('logo_filename') or '', now_str(), trademark_id),
)
return {'item_type': item_type, 'item_id': trademark_id}
if item_type == 'fee_receipt':
payment_id = payload.get('payment_id')
current = db.execute("SELECT * FROM fee_payments WHERE id=?", (payment_id,)).fetchone()
if not current:
raise ValueError('关联缴费记录不存在,请先恢复对应缴费记录')
if current['receipt_filename'] and current['receipt_filename'] != payload.get('receipt_filename'):
_trash_add(db, 'fee_receipt', payment_id, current['receipt_original_name'] or '缴费凭证', {
'version': 1,
'payment_id': payment_id,
'receipt_filename': current['receipt_filename'],
'receipt_original_name': current['receipt_original_name'],
'receipt_size': current['receipt_size'],
})
db.execute(
"""UPDATE fee_payments
SET receipt_filename=?,receipt_original_name=?,receipt_size=? WHERE id=?""",
(payload.get('receipt_filename') or '', payload.get('receipt_original_name') or '',
payload.get('receipt_size') or 0, payment_id),
)
return {'item_type': item_type, 'item_id': payment_id}
raise ValueError('该回收站数据暂不支持恢复')
def _purge_trash_entry(db, trash_row):
try:
payload = json.loads(trash_row['payload'])
except Exception:
payload = {}
filenames = _trash_payload_filenames(payload)
db.execute("DELETE FROM recycle_bin WHERE id=?", (trash_row['id'],))
removed = 0
for filename in filenames:
if not _file_is_referenced(db, filename):
try:
(UPLOAD_DIR / filename).unlink(missing_ok=True)
removed += 1
except Exception:
continue
return removed
def _json_payload():
payload = request.get_json(silent=True)
return payload if isinstance(payload, dict) else {}
# ── PDF 文书识别规则 ──────────────────────────────────────────────────────────
# 每条规则:(关键词列表, 文书名称, 建议专利状态, 建议商标状态)
# 关键词全部命中(AND)才触发,按优先级排列
# 规则设计原则:
# 1. 商标规则含"商标"关键词,专利规则含"专利"关键词,避免交叉误匹配
# 2. 通用规则(如"受理")放在最后,仅作为兜底
# 3. 驳回类规则需区分专利驳回和商标驳回
DOC_RULES = [
# ── 商标(优先匹配,因为商标文书常含"申请号""受理"等通用词)──
(['商标注册申请受理'], '商标申请受理通知书', None, '已受理'),
(['注册商标变更证明'], '注册商标变更证明', None, '已注册'),
(['商标', '变更证明'], '注册商标变更证明', None, '已注册'),
(['商标注册证'], '商标注册证', None, '已注册'),
(['商标注册公告'], '商标注册公告', None, '已注册'),
(['注册公告', '商标'], '商标注册公告', None, '已注册'),
(['商标注册申请初步审定公告'], '商标初审公告', None, '初审公告'),
(['初步审定', '商标'], '商标初审公告', None, '初审公告'),
(['驳回复审', '商标'], '商标驳回复审材料', None, '复审中'),
(['商标驳回'], '商标驳回通知书', None, '已驳回'),
(['驳回通知书', '商标'], '商标驳回通知书', None, '已驳回'),
(['驳回', '商标', '注册'], '商标驳回通知书', None, '已驳回'),
(['不予注册', '商标'], '商标驳回通知书', None, '已驳回'),
(['异议申请', '商标'], '其他', None, '异议中'),
(['异议决定', '商标'], '其他', None, None),
(['撤销申请', '连续三年'], '其他', None, '撤三中'),
(['无效宣告', '商标'], '其他', None, '无效中'),
(['商标', '续展'], '其他', None, None),
(['商标', '转让'], '其他', None, None),
# ── 专利 ──
(['专利证书', '授权'], '专利证书', '已授权', None),
(['授权通知书', '专利'], '授权通知书', '待登记', None),
(['授予发明专利权'], '授权通知书', '待登记', None),
(['办理登记手续'], '办理登记通知', '待登记', None),
(['专利申请受理'], '专利受理通知书', '已受理', None),
(['受理通知书', '专利'], '专利受理通知书', '已受理', None),
(['驳回决定', '专利'], '驳回决定书', '已驳回', None),
(['驳回决定'], '驳回决定书', '已驳回', None),
(['复审决定', '专利'], '复审决定书', None, None),
(['复审决定书'], '复审决定书', None, None),
(['复审请求', '专利'], '复审请求书', '复审中', None),
(['宣告专利权全部无效'], '无效宣告决定书', '失效', None),
(['无效宣告', '专利'], '无效宣告请求书', None, None),
(['视为撤回'], '视撤通知书', '视为撤回', None),
(['放弃专利权'], '放弃通知书', '失效', None),
(['进入实质审查'], '进入实审通知', '实审中', None),
(['实质审查请求'], '实审请求书', '实审中', None),
(['审查意见通知书'], '审查意见通知书', '实审中', None),
(['专利申请公布'], '申请公布通知', '已公开', None),
(['检索报告'], '检索报告', '实审中', None),
# ── 通用兜底(最后匹配)──
(['商标', '受理'], '商标申请受理通知书', None, '已受理'),
(['申请号', '受理'], '受理通知书', '已受理', None),
]
# 文件名是上传人可见且可直接核对的证据。命中这些明确词组时,优先级高于
# OCR/正文推断;只有文件名没有足够信息,才回退到正文规则。
FILENAME_DOC_RULES = {
'trademark': [
(('驳回', '复审'), '商标驳回复审材料'),
(('驳回',), '商标驳回通知书'),
(('不予注册',), '商标驳回通知书'),
(('初步审定',), '商标初审公告'),
(('初审公告',), '商标初审公告'),
(('注册公告',), '商标注册公告'),
(('注册证',), '商标注册证'),
(('变更证明',), '注册商标变更证明'),
(('受理',), '商标申请受理通知书'),
],
'patent': [
(('驳回', '复审'), '复审请求书'),
(('驳回',), '驳回决定书'),
(('审查意见',), '审查意见通知书'),
(('办理登记',), '办理登记通知书'),
(('授权通知',), '授权通知书'),
(('专利证书',), '专利证书'),
(('受理',), '受理通知书'),
(('补正',), '补正通知书'),
(('视撤',), '视撤通知书'),
(('年费', '收据'), '年费缴费收据'),
(('年费',), '年费缴费通知'),
],
'copyright': [
(('驳回',), '驳回通知书'),
(('补正',), '补正通知书'),
(('受理',), '登记受理通知书'),
(('登记证',), '著作权登记证书'),
],
}
def _filename_doc_type(fname, item_type=''):
"""Return a document type only when the filename has an unambiguous cue."""
text = Path(fname or '').stem.lower()
scopes = [item_type] if item_type in FILENAME_DOC_RULES else []
if not scopes:
if '商标' in text:
scopes = ['trademark']
elif '专利' in text or re.search(r'cn\s*\d{6,}', text, re.I):
scopes = ['patent']
elif '软著' in text or '著作权' in text:
scopes = ['copyright']
for scope in scopes:
for words, doc_type in FILENAME_DOC_RULES[scope]:
if all(word in text for word in words):
return doc_type
return ''
def extract_pdf_text(path: Path, max_chars=8000) -> str:
"""提取 PDF 文本,失败返回空字符串"""
try:
from pdfminer.high_level import extract_text
text = extract_text(str(path))
return (text or '')[:max_chars]
except Exception:
pass
try:
import pypdf
reader = pypdf.PdfReader(str(path))
parts = []
for page in reader.pages[:8]:
parts.append(page.extract_text() or '')
return '\n'.join(parts)[:max_chars]
except Exception:
return ''
def extract_ocr_text(path: Path, max_chars=8000) -> str:
"""Best-effort local OCR for scanned PDFs/images; silently falls back when unavailable."""
tesseract = shutil.which('tesseract')
if not tesseract:
return ''
lang = os.environ.get('IPKEEPER_OCR_LANG', 'chi_sim+eng')
def run_tesseract(image_path):
try:
proc = subprocess.run(
[tesseract, str(image_path), 'stdout', '-l', lang, '--psm', '6'],
capture_output=True, text=True, timeout=30,
)
return proc.stdout or ''
except Exception:
return ''
suffix = path.suffix.lower()
if suffix in {'.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff', '.webp'}:
return run_tesseract(path)[:max_chars]
if suffix != '.pdf':
return ''
pdftoppm = shutil.which('pdftoppm')
if not pdftoppm:
return ''
with tempfile.TemporaryDirectory(prefix='ipkeeper_ocr_') as td:
prefix = Path(td) / 'page'
try:
subprocess.run(
[pdftoppm, '-f', '1', '-l', '3', '-jpeg', '-r', '180', str(path), str(prefix)],
capture_output=True, timeout=40, check=False,
)
except Exception:
return ''
parts = []
for image_path in sorted(Path(td).glob('page-*.jpg')):
text = run_tesseract(image_path)
if text:
parts.append(text)
if sum(len(x) for x in parts) >= max_chars:
break
return '\n'.join(parts)[:max_chars]
def extract_document_text(path: Path, max_chars=8000) -> str:
"""Extract text from common attachment formats for case prefill."""
suffix = path.suffix.lower()
if suffix == '.pdf':
text = extract_pdf_text(path, max_chars)
if len(re.sub(r'\s+', '', text)) >= 40:
return text
return (text + '\n' + extract_ocr_text(path, max_chars)).strip()[:max_chars]
if suffix in {'.png', '.jpg', '.jpeg', '.bmp', '.tif', '.tiff', '.webp'}:
return extract_ocr_text(path, max_chars)
if suffix == '.txt':
try:
return path.read_text(encoding='utf-8', errors='ignore')[:max_chars]
except Exception:
return ''
if suffix == '.docx':
try:
import docx
doc = docx.Document(str(path))
return '\n'.join(p.text for p in doc.paragraphs if p.text)[:max_chars]
except Exception:
return ''
return ''
def _normalize_ocr_spacing(text):
"""Collapse OCR-added spaces between CJK characters while keeping word spacing."""
return re.sub(r'(?<=[\u3400-\u9fff])\s+(?=[\u3400-\u9fff])', '', text or '')
def analyze_doc_text(text: str, item_type: str):
"""
对提取的文本运行规则匹配。
返回 {'doc_type': str, 'suggested_status': str|None, 'confidence': float, 'snippet': str}
"""
if not text.strip():
return None
# 归一化
t = _normalize_ocr_spacing(text.replace('\n', ' ').replace('\r', ' '))
# 按 item_type 优先匹配对应类型的规则,避免专利规则误匹配商标文书
def _match(rules_subset):
for keywords, doc_name, patent_status, tm_status in rules_subset:
if all(kw in t for kw in keywords):
suggested = patent_status if item_type == 'patent' else tm_status
snippet = re.sub(r'\s+', ' ', t[:200]).strip()
return {
'doc_type': doc_name,
'suggested_status': suggested,
# This is deterministic keyword coverage, not a calibrated
# machine-learning probability.
'confidence': min(.85, .55 + .10 * len(keywords)),
'confidence_type': 'rule_match_strength',
'matched_keywords': keywords,
'snippet': snippet,
}
return None
# 按关键词特征分类规则
trademark_indicators = {'商标', '注册', '异议', '撤三', '无效', '初步审定'}
patent_indicators = {'专利', '发明', '实用新型', '外观', '实审', '复审', '公开', 'PCT'}
tm_rules, patent_rules, general_rules = [], [], []
for rule in DOC_RULES:
keywords = rule[0]
if any(kw in trademark_indicators for kw in keywords):
tm_rules.append(rule)
elif any(kw in patent_indicators for kw in keywords):
patent_rules.append(rule)
else:
general_rules.append(rule)
# 先匹配对应类型,再匹配通用规则
if item_type == 'trademark':
result = _match(tm_rules) or _match(general_rules)
elif item_type == 'patent':
result = _match(patent_rules) or _match(general_rules)
else:
result = _match(DOC_RULES)
if result:
return result
return {
'doc_type': '其他文书',
'suggested_status': None,
'confidence': 0.0,
'confidence_type': 'rule_match_strength',
'matched_keywords': [],
'snippet': re.sub(r'\s+', ' ', t[:200]).strip(),
}
def extract_doc_fields(text: str, item_type: str, filename: str = '') -> dict:
"""从 PDF 文本中提取可用字段,返回 dict 用于自动填充新记录。
只提取确信度高的字段,不瞎猜。"""
fields = {}
# 保留原始换行用于行首提取,同时生成平文本用于正则
lines = [l.strip() for l in text.split('\n') if l.strip()]
t = text.replace('\n', ' ').replace('\r', ' ').replace('\xa0', ' ').replace(' ', ' ')
# 归一化连续空格
t = _normalize_ocr_spacing(re.sub(r'\s+', ' ', t))
if item_type == 'trademark':
# 申请号:优先从文件名提取
m = re.search(r'(\d{7,9})', filename)
if not m:
m = re.search(r'申请号[::]?\s*(\d{7,9})', t)
if m:
fields['app_no'] = m.group(1)
# 注册号
m = re.search(r'注册号[::]?\s*(\d+)', t)
if m:
fields['reg_no'] = m.group(1)
# 类别("类别:第10类" 或 "第10类")
m = re.search(r'类\s*别[::]?\s*第?\s*(\d+)\s*类', t)
if not m:
m = re.search(r'第\s*(\d+)\s*类', t)
if m:
fields['classes'] = m.group(1)
# 申请人/注册人:接受通知书中无"申请人:"标签,公司名通常在文档开头前几行
owner = ''
# 先尝试有标签的情况
for pat in [r'注册人[::]\s*(.+?)(?:\s+地址)', r'权利人[::]\s*(.+?)(?:\s+地址)',
r'申请人[::]\s*(.+?)(?:\s+地址)', r'受让人[::]\s*(.+?)(?:\s+地址)']:
m = re.search(pat, t)
if m:
owner = m.group(1).strip()
break
# 无标签时:从文档前几行找公司名(包含"公司"/"集团"/"大学"等关键词的行)
if not owner:
for line in lines[:6]:
if any(kw in line for kw in ['公司', '集团', '大学', '研究院', '研究所', '医院', '有限', '股份']) and len(line) <= 40:
owner = line
break
if owner:
# 清理:去掉尾部的地址/邮编等
owner = re.sub(r'(北京市|上海市|广东省|地址|邮编|电话|Tel).*$', '', owner).strip()
if 2 <= len(owner) <= 80:
fields['owner'] = owner
# 申请日期(标签后可能有其他内容,所以也尝试直接找"YYYY年MM月DD日")
m = re.search(r'申请日期[::]?\s*(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日', t)
if not m:
# 有些格式:申请日期: XXXXXX申请号:2026年05月08日 → 取申请号后的日期
m2 = re.search(r'申请号[::]?\s*\d{7,}\s*申请号[::]?\s*(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日', t)
if m2:
m = m2
if not m:
# 兜底:找所有日期,取"申请号:"附近最近的日期
dates = list(re.finditer(r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日', t))
if dates:
# 如果有"申请号",取其后的最近日期;否则取最晚的
app_no_pos = t.find('申请号')
if app_no_pos >= 0:
after = [d for d in dates if d.start() > app_no_pos]
best = after[0] if after else dates[-1]
else:
best = max(dates, key=lambda d: (int(d.group(1)), int(d.group(2)), int(d.group(3))))
m = best
if m:
fields['app_date'] = f'{m.group(1)}-{int(m.group(2)):02d}-{int(m.group(3)):02d}'
m = re.search(r'商标名[称]?[::]\s*[\""\"]?\s*(.+?)\s*[\""\"]?(?:\s+注册|类|申请|商标)', t)
if m and 1 <= len(m.group(1).strip()) <= 20:
fields['name'] = m.group(1).strip()
elif item_type == 'patent':
codes = re.sub(r'\s+', '', t)
# 申请号
for pat in [r'申请号[::]?(?:CN|ZL)?(\d{10,16}(?:\.\d)?)',
r'专利申请号[::]?(?:CN|ZL)?(\d{10,16}(?:\.\d)?)',
r'(?:CN|ZL)(\d{10,16}(?:\.\d)?)']:
m = re.search(pat, codes, re.I)
if m:
fields['app_no'] = m.group(1).upper()
break
# 公开号
m = re.search(r'(?:公开|授权公告)号[::]?(CN\d+[A-Z]?)', codes, re.I)
if m:
fields['pub_no'] = m.group(1).upper()
# 授权号/专利号
m = re.search(r'(?:授权|专利).{0,4}号[::]?(ZL\d{10,16}(?:\.\d)?)', codes, re.I)
if not m:
m = re.search(r'(ZL\d{10,16}(?:\.\d)?)', codes, re.I)
if m:
fields['grant_no'] = m.group(1).upper()
# 发明名称(有标签的情况)
for pat in [r'发明名称\s*[::]\s*(.+?)(?:专.{0,6}权人|申请号|发明人|专利号)',
r'专利名称\s*[::]\s*(.+?)(?:申请号|专利号)',
r'名\s*称\s*[::]\s*(.+?)(?:申请号|专利号)']:
m = re.search(pat, t)
if m:
fields['title'] = m.group(1).strip()[:120]
break
# 发明人
m = re.search(r'发明人\s*[::]\s*(.+?)(?:申请号|申请人|地址|专利号)', t)
if m:
fields['inventors'] = m.group(1).strip()[:100]
# 申请人(有标签的情况)
for pat in [r'申请人\s*[::]\s*(.+?)(?:地址|邮编)',
r'专.{0,5}权人\s*[::]\s*(.+?)(?:地址|邮编|发明)']:
m = re.search(pat, t)
if m:
fields['owner'] = m.group(1).strip()[:80]
break
# IPC 分类号
m = re.search(r'(?:IPC|分类号)[::]?\s*([A-H]\d{2}[A-Z]\s*\d+/\d+)', t, re.I)
if m:
fields['ipc'] = m.group(1).replace(' ', '')
# 申请日期
m = re.search(r'(?:专利)?申请(?:日期|日)\s*[::]?\s*(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日', t)
if m:
fields['app_date'] = f'{m.group(1)}-{int(m.group(2)):02d}-{int(m.group(3)):02d}'
m = re.search(r'授权公告日\s*[::]?\s*(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日', t)
if m:
fields['grant_date'] = f'{m.group(1)}-{int(m.group(2)):02d}-{int(m.group(3)):02d}'
elif item_type == 'copyright':
# 登记号
m = re.search(r'(\d{4}SR\d+)', t, re.I)
if not m:
m = re.search(r'(\d{4}SR\d+)', filename, re.I)
if m:
fields['reg_no'] = m.group(1).upper()
# 软件名称(有标签)
for pat in [r'软件名称[::]\s*(.+?)(?:\s+登记号|版本)', r'作品名称[::]\s*(.+?)(?:\s+登记)']:
m = re.search(pat, t)
if m:
fields['name'] = m.group(1).strip()[:100]
break
# 版本号
m = re.search(r'版本[号]?[::]\s*V?\s*([\d.]+)', t)
if m:
fields['version'] = 'V' + m.group(1)
# 著作权人(有标签)
for pat in [r'著作权人[::]\s*(.+?)(?:\s+地址)', r'权利人[::]\s*(.+?)(?:\s+地址)']:
m = re.search(pat, t)
if m:
fields['owner'] = m.group(1).strip()[:80]
break
# 登记日期
m = re.search(r'登记日期[::]?\s*(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日', t)
if m:
fields['reg_date'] = f'{m.group(1)}-{int(m.group(2)):02d}-{int(m.group(3)):02d}'
return fields
# 费减按案件备案资格和权利人数量执行。
def get_fee(patent_type, year, entity, app_date=None, grant_date=None,
due_date=None, as_of=None, owner=None, fee_reduction_approved=False):
quote = calculate_cn_annual_fee(
patent_type, year, entity, app_date, grant_date, due_date, as_of, owner,
fee_reduction_approved
)
return quote['base'], quote['total_due']
def get_db():
conn = sqlite3.connect(str(DB_PATH), timeout=30)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA busy_timeout=10000")
conn.execute("PRAGMA foreign_keys=ON")
conn.execute("PRAGMA synchronous=FULL")
return conn
def checkpoint_database():
"""Flush committed WAL data so web-service restarts never lose saved changes."""
if not DB_PATH.exists():
return
conn = sqlite3.connect(str(DB_PATH), timeout=10)
try:
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
conn.commit()
finally:
conn.close()
# ── 自动关联辅助 ────────────────────────────────────────────
TEXT_MATCH_THRESHOLD = 0.85
_TEXT_MATCH_NOISE_WORDS = [
'发明专利证书', '实用新型证书', '外观设计证书', '专利证书', '授权证书',
'商标注册证', '注册证书', '登记证书', '受理通知书', '授权通知书',
'驳回通知书', '驳回决定书', '复审决定书', '审查意见通知书', '检索报告',
'办理登记通知书', '公开公告', '证书', '通知书', '受理', '授权', '注册',
'专利', '商标', '软著', '著作权', '发明', '实用新型', '外观设计',
'北京至真健康科技股份有限公司', '北京至真互联网技术有限公司',
'吉林至真明熠医疗器械有限公司', '至真健康', '至真互联网', '至真明熠',
'江苏', '北京', '美国', '日本', '韩国', '欧盟', '南非', '荷兰',
]
def _normalize_text_match(value):
"""Normalize filename/title text for conservative fuzzy matching."""
text = unicodedata.normalize('NFKC', str(value or '').lower())
text = Path(text).stem
text = re.sub(r'(cn|zl)?\d{7,18}(?:\.\d)?', ' ', text, flags=re.I)
text = re.sub(r'pct[/a-z]{2}\d{4}/\d{6}', ' ', text, flags=re.I)
text = re.sub(r'\d{4}sr\d+', ' ', text, flags=re.I)
text = re.sub(r'^\s*\d+[\s_.-]*', ' ', text)
for word in _TEXT_MATCH_NOISE_WORDS:
text = text.replace(word.lower(), ' ')
text = re.sub(r'[\s_.,,。;;::()()\[\]【】{}《》<>、/\\|+\-&]+', '', text)
return text.strip()
def _text_match_score(filename_text, record_text):