gopallikehack commited on
Commit
2748c3f
Β·
verified Β·
1 Parent(s): bb77d0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -102
app.py CHANGED
@@ -1,144 +1,101 @@
1
  import os
2
  import json
3
  import subprocess
4
- from fastapi import FastAPI, Query
5
- from fastapi.responses import JSONResponse
6
  import tempfile
 
7
 
8
- app = FastAPI(title="Hitek Search Engine", developer="Gopal Parmar")
9
 
10
  MOUNT_PATH = "/data/"
11
- PART_PREFIX = "hitek.7z."
12
- PARTS = [f"{PART_PREFIX}{i:03d}" for i in range(1, 58)]
13
- EXTRACTED_JSON = "/data/users_data.json"
14
- MERGED_FILE = "/data/merged.7z"
15
-
16
- # ========== MERGE ALL PARTS ==========
17
- def merge_parts():
18
- """Merge all 57 parts into a single 7z file"""
19
- if os.path.exists(MERGED_FILE):
20
- return True
21
-
22
- try:
23
- with open(MERGED_FILE, 'wb') as out:
24
- for part in PARTS:
25
- part_path = os.path.join(MOUNT_PATH, part)
26
- if os.path.exists(part_path):
27
- with open(part_path, 'rb') as f:
28
- out.write(f.read())
29
- print(f"βž• Merged: {part}")
30
- else:
31
- print(f"❌ Missing: {part}")
32
- return False
33
- print(f"βœ… Merged: {MERGED_FILE} ({os.path.getsize(MERGED_FILE)/(1024**3):.2f} GB)")
34
- return True
35
- except Exception as e:
36
- print(f"❌ Merge error: {e}")
37
- return False
38
 
39
- # ========== EXTRACT JSON ==========
40
- def extract_json():
41
- """Extract users_data.json from merged 7z"""
42
- if os.path.exists(EXTRACTED_JSON):
43
- return True
44
-
45
- if not os.path.exists(MERGED_FILE):
46
- return False
47
 
48
  try:
49
- # Use 7z command to extract
50
  result = subprocess.run(
51
- ["7z", "x", "-so", MERGED_FILE, "users_data.json"],
52
  capture_output=True,
53
  timeout=600 # 10 minutes
54
  )
55
- if result.returncode == 0:
56
- with open(EXTRACTED_JSON, 'wb') as f:
 
57
  f.write(result.stdout)
58
- print(f"βœ… Extracted: {EXTRACTED_JSON} ({os.path.getsize(EXTRACTED_JSON)/(1024**2):.2f} MB)")
59
- return True
60
  else:
61
- print(f"❌ Extract error: {result.stderr.decode()}")
62
- return False
 
63
  except Exception as e:
64
- print(f"❌ Extract error: {e}")
65
- return False
66
 
67
- # ========== SEARCH IN JSON ==========
68
- def search_json(query: str, limit: int = 10):
69
- """Search query in JSON file"""
70
- if not os.path.exists(EXTRACTED_JSON):
71
- return []
72
-
73
- results = []
74
- try:
75
- with open(EXTRACTED_JSON, 'r', encoding='utf-8', errors='ignore') as f:
76
- for line in f:
77
- if query in line:
78
- try:
79
- results.append(json.loads(line))
80
- except:
81
- results.append({"raw": line.strip()})
82
- if len(results) >= limit:
83
- break
84
- except Exception as e:
85
- return [{"error": str(e)}]
86
-
87
- return results
88
-
89
- # ========== API ENDPOINTS ==========
90
  @app.on_event("startup")
91
  async def startup():
92
- """Run merge and extract on startup"""
93
- print("πŸ” Checking files...")
94
- if merge_parts():
95
- extract_json()
 
 
 
 
 
 
 
 
96
  else:
97
- print("❌ Merge failed. Check if all parts are mounted.")
98
 
99
  @app.get("/")
100
  async def root():
101
- file_exists = os.path.exists(EXTRACTED_JSON)
102
  return {
103
- "message": "πŸ” Hitek Search Engine",
104
  "developer": "Gopal Parmar",
105
- "status": "ready" if file_exists else "processing",
106
- "file_size_gb": round(os.path.getsize(EXTRACTED_JSON)/(1024**3), 2) if file_exists else 0,
107
- "endpoints": {
108
- "/search?q=9999999998": "Search by phone number",
109
- "/status": "Check merge/extract status"
110
- }
111
  }
112
 
113
  @app.get("/status")
114
  async def status():
115
- parts_available = []
116
- for part in PARTS:
 
117
  if os.path.exists(os.path.join(MOUNT_PATH, part)):
118
- parts_available.append(part)
119
 
120
  return {
121
  "developer": "Gopal Parmar",
122
- "total_parts": 57,
123
- "available_parts": len(parts_available),
124
- "merged_file_exists": os.path.exists(MERGED_FILE),
125
- "json_exists": os.path.exists(EXTRACTED_JSON),
126
- "json_size_gb": round(os.path.getsize(EXTRACTED_JSON)/(1024**3), 2) if os.path.exists(EXTRACTED_JSON) else 0,
127
- "status": "ready" if os.path.exists(EXTRACTED_JSON) else "processing"
128
  }
129
 
130
  @app.get("/search")
131
  async def search(q: str = Query(..., min_length=4), limit: int = 10):
132
- """Search by phone number or any field"""
133
- results = search_json(q, limit)
134
 
135
- if not results:
136
- return {
137
- "developer": "Gopal Parmar",
138
- "query": q,
139
- "count": 0,
140
- "results": []
141
- }
 
 
 
 
 
 
142
 
143
  return {
144
  "developer": "Gopal Parmar",
 
1
  import os
2
  import json
3
  import subprocess
 
 
4
  import tempfile
5
+ from fastapi import FastAPI, Query
6
 
7
+ app = FastAPI(title="Hitek Direct Extract API", developer="Gopal Parmar")
8
 
9
  MOUNT_PATH = "/data/"
10
+ FIRST_PART = "hitek.7z.001"
11
+ OUTPUT_JSON = "/data/users_data.json"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
+ def extract_json_direct():
14
+ """Extract users_data.json directly from multi-part archive"""
15
+ part_path = os.path.join(MOUNT_PATH, FIRST_PART)
16
+ if not os.path.exists(part_path):
17
+ return False, "First part not found"
 
 
 
18
 
19
  try:
20
+ # 7z will automatically find all parts in the same directory
21
  result = subprocess.run(
22
+ ["7z", "x", "-so", part_path, "users_data.json"],
23
  capture_output=True,
24
  timeout=600 # 10 minutes
25
  )
26
+
27
+ if result.returncode == 0 and result.stdout:
28
+ with open(OUTPUT_JSON, 'wb') as f:
29
  f.write(result.stdout)
30
+ return True, "Extracted successfully"
 
31
  else:
32
+ return False, result.stderr.decode()
33
+ except subprocess.TimeoutExpired:
34
+ return False, "Extraction timed out"
35
  except Exception as e:
36
+ return False, str(e)
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  @app.on_event("startup")
39
  async def startup():
40
+ print("πŸ” Checking for parts...")
41
+ # Check if first part exists
42
+ part_path = os.path.join(MOUNT_PATH, FIRST_PART)
43
+ if os.path.exists(part_path):
44
+ print(f"βœ… Found: {FIRST_PART}")
45
+ print("⏳ Extracting users_data.json (this may take time)...")
46
+ success, msg = extract_json_direct()
47
+ if success:
48
+ size = os.path.getsize(OUTPUT_JSON) / (1024**2)
49
+ print(f"βœ… Extracted: users_data.json ({size:.2f} MB)")
50
+ else:
51
+ print(f"❌ Extraction failed: {msg}")
52
  else:
53
+ print(f"❌ {FIRST_PART} not found in {MOUNT_PATH}")
54
 
55
  @app.get("/")
56
  async def root():
57
+ exists = os.path.exists(OUTPUT_JSON)
58
  return {
59
+ "message": "πŸ” Hitek Direct Extract API",
60
  "developer": "Gopal Parmar",
61
+ "status": "ready" if exists else "processing",
62
+ "file_size_mb": round(os.path.getsize(OUTPUT_JSON) / (1024**2), 2) if exists else 0
 
 
 
 
63
  }
64
 
65
  @app.get("/status")
66
  async def status():
67
+ parts_found = []
68
+ for i in range(1, 58):
69
+ part = f"hitek.7z.{i:03d}"
70
  if os.path.exists(os.path.join(MOUNT_PATH, part)):
71
+ parts_found.append(part)
72
 
73
  return {
74
  "developer": "Gopal Parmar",
75
+ "parts_found": len(parts_found),
76
+ "total_expected": 57,
77
+ "json_exists": os.path.exists(OUTPUT_JSON),
78
+ "json_size_mb": round(os.path.getsize(OUTPUT_JSON) / (1024**2), 2) if os.path.exists(OUTPUT_JSON) else 0
 
 
79
  }
80
 
81
  @app.get("/search")
82
  async def search(q: str = Query(..., min_length=4), limit: int = 10):
83
+ if not os.path.exists(OUTPUT_JSON):
84
+ return {"error": "JSON not extracted yet. Check /status"}
85
 
86
+ results = []
87
+ try:
88
+ with open(OUTPUT_JSON, 'r', encoding='utf-8', errors='ignore') as f:
89
+ for line in f:
90
+ if q in line:
91
+ try:
92
+ results.append(json.loads(line))
93
+ except:
94
+ results.append({"raw": line.strip()})
95
+ if len(results) >= limit:
96
+ break
97
+ except Exception as e:
98
+ return {"error": str(e)}
99
 
100
  return {
101
  "developer": "Gopal Parmar",