Rajan Sharma commited on
Commit
1a93711
·
verified ·
1 Parent(s): 386287a

Create upload_ingest.py

Browse files
Files changed (1) hide show
  1. upload_ingest.py +56 -15
upload_ingest.py CHANGED
@@ -1,18 +1,52 @@
1
- \
2
- import os
3
  from typing import List, Tuple
4
  import pdfplumber
5
  from docx import Document as DocxDocument
6
  from PIL import Image
7
  import pytesseract
8
 
9
- TEXT_EXT = {".txt", ".md", ".csv"}
10
- DOCX_EXT = {".docx"}
11
- PDF_EXT = {".pdf"}
12
- IMG_EXT = {".png", ".jpg", ".jpeg", ".webp"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
  def _read_text_file(path: str) -> str:
15
- return open(path, "r", encoding="utf-8", errors="ignore").read()
 
16
 
17
  def _read_docx(path: str) -> str:
18
  doc = DocxDocument(path)
@@ -30,22 +64,29 @@ def _read_image_ocr(path: str) -> str:
30
  return pytesseract.image_to_string(img)
31
 
32
  def extract_text_from_files(filepaths: List[str]) -> List[Tuple[str, str]]:
33
- results = []
34
- for fp in filepaths:
35
- _, ext = os.path.splitext(fp.lower())
 
 
 
 
 
 
 
36
  try:
37
- if ext in TEXT_EXT:
38
  txt = _read_text_file(fp)
39
- elif ext in DOCX_EXT:
40
  txt = _read_docx(fp)
41
- elif ext in PDF_EXT:
42
  txt = _read_pdf(fp)
43
- elif ext in IMG_EXT:
44
  txt = _read_image_ocr(fp)
45
  else:
46
  txt = ""
47
  if txt and txt.strip():
48
- results.append((os.path.basename(fp), txt))
49
  except Exception:
50
  continue
51
  return results
 
1
+ import os, mimetypes
 
2
  from typing import List, Tuple
3
  import pdfplumber
4
  from docx import Document as DocxDocument
5
  from PIL import Image
6
  import pytesseract
7
 
8
+ from settings import ALLOWED_EXT, ALLOWED_MIME, MAX_UPLOAD_MB, ENABLE_AV_SCAN, CLAMD_UNIX_SOCKET, CLAMD_NETWORK
9
+ from privacy import redact_text
10
+
11
+ # --- Optional AV scan (clamd) ---
12
+ def _clamd_scan(path: str) -> bool:
13
+ if not ENABLE_AV_SCAN:
14
+ return True
15
+ try:
16
+ import clamd
17
+ cd = None
18
+ if CLAMD_UNIX_SOCKET:
19
+ cd = clamd.ClamdUnixSocket(CLAMD_UNIX_SOCKET)
20
+ elif CLAMD_NETWORK:
21
+ host, port = CLAMD_NETWORK
22
+ cd = clamd.ClamdNetworkSocket(host, port)
23
+ if not cd:
24
+ return True
25
+ res = cd.scan(path)
26
+ # Expected: {'/path/file': ('OK', 'OK')} or ('FOUND','Eicar-Test-Signature')
27
+ verdict = next(iter(res.values()))[0] if isinstance(res, dict) else "OK"
28
+ return verdict == "OK"
29
+ except Exception:
30
+ # If AV unavailable, fail open by default (configurable)
31
+ return True
32
+
33
+ def _check_allowed(path: str) -> tuple[bool, str]:
34
+ ext = os.path.splitext(path.lower())[1]
35
+ if ext not in ALLOWED_EXT:
36
+ return False, f"Extension {ext} not allowed."
37
+ mime, _ = mimetypes.guess_type(path)
38
+ if mime not in ALLOWED_MIME:
39
+ return False, f"MIME {mime} not allowed."
40
+ size_mb = os.path.getsize(path) / (1024 * 1024)
41
+ if size_mb > MAX_UPLOAD_MB:
42
+ return False, f"File too large ({size_mb:.1f}MB > {MAX_UPLOAD_MB}MB)."
43
+ if not _clamd_scan(path):
44
+ return False, "Antivirus scan failed."
45
+ return True, "ok"
46
 
47
  def _read_text_file(path: str) -> str:
48
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
49
+ return f.read()
50
 
51
  def _read_docx(path: str) -> str:
52
  doc = DocxDocument(path)
 
64
  return pytesseract.image_to_string(img)
65
 
66
  def extract_text_from_files(filepaths: List[str]) -> List[Tuple[str, str]]:
67
+ """
68
+ Returns a list of (safe_name, redacted_text) for approved files.
69
+ """
70
+ results: List[Tuple[str, str]] = []
71
+ for fp in filepaths or []:
72
+ ok, reason = _check_allowed(fp)
73
+ if not ok:
74
+ # skip silently or raise/log upstream
75
+ continue
76
+ ext = os.path.splitext(fp.lower())[1]
77
  try:
78
+ if ext in {".txt", ".md", ".csv"}:
79
  txt = _read_text_file(fp)
80
+ elif ext == ".docx":
81
  txt = _read_docx(fp)
82
+ elif ext == ".pdf":
83
  txt = _read_pdf(fp)
84
+ elif ext in {".png", ".jpg", ".jpeg", ".webp"}:
85
  txt = _read_image_ocr(fp)
86
  else:
87
  txt = ""
88
  if txt and txt.strip():
89
+ results.append((os.path.basename(fp), redact_text(txt)))
90
  except Exception:
91
  continue
92
  return results