kjbytes commited on
Commit
41c9648
·
1 Parent(s): cd27a30

Add application file

Browse files
Files changed (1) hide show
  1. main.py +22 -3
main.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import logging
2
  import os
3
  import tempfile
@@ -9,6 +10,20 @@ from fastapi.responses import FileResponse
9
  from model import extract_contact
10
  from vcf import generate_vcf, VCF_DIR
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  logging.basicConfig(
13
  level=logging.INFO,
14
  format="%(asctime)s %(levelname)s: %(message)s",
@@ -47,13 +62,16 @@ async def extract(file: UploadFile = File(...)):
47
 
48
  vcf_path = generate_vcf(data)
49
  filename = os.path.basename(vcf_path)
50
- log.info("wrote vcf: %s", filename)
 
51
 
52
  return {
53
  "success": True,
54
  "contact": data,
55
  "vcf": filename,
 
56
  "download": f"/download/{filename}",
 
57
  }
58
  except Exception as e:
59
  # ponytail: exc_info dumps the full traceback to the container logs
@@ -69,5 +87,6 @@ def download(filename: str):
69
  # ponytail: basename strips any ../ path traversal from the URL
70
  path = os.path.join(VCF_DIR, os.path.basename(filename))
71
  if not os.path.exists(path):
72
- raise HTTPException(404, "VCF not found")
73
- return FileResponse(path, filename=filename, media_type="text/vcard")
 
 
1
+ import csv
2
  import logging
3
  import os
4
  import tempfile
 
10
  from model import extract_contact
11
  from vcf import generate_vcf, VCF_DIR
12
 
13
+ CSV_FIELDS = ["name", "company", "designation", "phone", "email", "website", "address"]
14
+ CSV_PATH = os.path.join(VCF_DIR, "contacts.csv")
15
+
16
+
17
+ def append_csv(data):
18
+ # ponytail: append-only log of every extraction; write header once on first row
19
+ new_file = not os.path.exists(CSV_PATH)
20
+ with open(CSV_PATH, "a", newline="") as f:
21
+ w = csv.DictWriter(f, fieldnames=CSV_FIELDS, extrasaction="ignore")
22
+ if new_file:
23
+ w.writeheader()
24
+ w.writerow({k: data.get(k, "") for k in CSV_FIELDS})
25
+ return os.path.basename(CSV_PATH)
26
+
27
  logging.basicConfig(
28
  level=logging.INFO,
29
  format="%(asctime)s %(levelname)s: %(message)s",
 
62
 
63
  vcf_path = generate_vcf(data)
64
  filename = os.path.basename(vcf_path)
65
+ csv_name = append_csv(data)
66
+ log.info("wrote vcf: %s, appended csv: %s", filename, csv_name)
67
 
68
  return {
69
  "success": True,
70
  "contact": data,
71
  "vcf": filename,
72
+ "csv": csv_name,
73
  "download": f"/download/{filename}",
74
+ "csv_download": f"/download/{csv_name}",
75
  }
76
  except Exception as e:
77
  # ponytail: exc_info dumps the full traceback to the container logs
 
87
  # ponytail: basename strips any ../ path traversal from the URL
88
  path = os.path.join(VCF_DIR, os.path.basename(filename))
89
  if not os.path.exists(path):
90
+ raise HTTPException(404, "file not found")
91
+ media = "text/csv" if path.endswith(".csv") else "text/vcard"
92
+ return FileResponse(path, filename=filename, media_type=media)