ShayanP commited on
Commit
ce706b8
·
1 Parent(s): 50d75f1
Files changed (3) hide show
  1. app.py +565 -0
  2. dockerfile +21 -0
  3. requirements.txt +0 -0
app.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sentence_transformers import SentenceTransformer
2
+ import faiss
3
+ import json
4
+ import os
5
+ from flask import Flask, request, jsonify
6
+ from werkzeug.utils import secure_filename
7
+ from flask_cors import CORS
8
+ from anthropic import Anthropic
9
+ import re
10
+ from dotenv import load_dotenv
11
+ load_dotenv()
12
+
13
+
14
+ UPLOAD_FOLDER = "uploads"
15
+ VECTOR_FOLDER = "vectorized"
16
+ ALLOWED_EXTENSIONS = {"json","md","txt"}
17
+
18
+ if not os.path.exists(UPLOAD_FOLDER):
19
+ os.mkdir(UPLOAD_FOLDER)
20
+ if not os.path.exists(VECTOR_FOLDER):
21
+ os.mkdir(VECTOR_FOLDER)
22
+
23
+ app = Flask(__name__)
24
+ CORS(app)
25
+ app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
26
+
27
+
28
+
29
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
30
+ hf_token = hf_token = os.environ.get("HF_TOKEN")
31
+ anthropic_client = Anthropic(api_key=api_key)
32
+
33
+ embedder = SentenceTransformer("BAAI/bge-large-en-v1.5", use_auth_token=hf_token)
34
+
35
+
36
+ # Helper function to call Claude
37
+ def call_claude(prompt, model="claude-sonnet-4-20250514", max_tokens=4000, temperature=0.1):
38
+
39
+ client = anthropic_client
40
+
41
+ response = client.messages.create(
42
+ model=model,
43
+ max_tokens=max_tokens,
44
+ temperature=temperature,
45
+ messages=[
46
+ {"role": "user", "content": prompt}
47
+ ]
48
+ )
49
+
50
+ return response.content[0].text
51
+
52
+
53
+ def allowed_files(filename):
54
+ return '.' in filename and filename.rsplit('.',1)[1].lower() in ALLOWED_EXTENSIONS
55
+
56
+
57
+
58
+ def chunk_text(text, chunk_size=1000, overlap=200):
59
+ """Split text into overlapping chunks for better retrieval"""
60
+ chunks = []
61
+ start = 0
62
+ text_len = len(text)
63
+
64
+ while start < text_len:
65
+ end = min(start + chunk_size, text_len)
66
+
67
+ # Try to break at sentence end if possible
68
+ if end < text_len:
69
+ # Look for sentence endings within the last 100 characters
70
+ last_period = text.rfind('.', start + chunk_size - 100, end)
71
+ if last_period > start:
72
+ end = last_period + 1
73
+
74
+ chunk = text[start:end].strip()
75
+ if chunk:
76
+ chunks.append(chunk)
77
+
78
+ start = end - overlap if end < text_len else text_len
79
+
80
+ return chunks
81
+
82
+ def parse_markdown(file_path):
83
+ """Parse markdown file and extract sections"""
84
+ with open(file_path, "r", encoding="utf-8") as f:
85
+ content = f.read()
86
+
87
+ # Split by headers and create structured chunks
88
+ sections = []
89
+ current_section = {"title": "", "content": ""}
90
+
91
+ lines = content.split('\n')
92
+ for line in lines:
93
+ # Check if line is a header
94
+ if line.startswith('#'):
95
+ # Save previous section if it has content
96
+ if current_section["content"].strip():
97
+ sections.append(current_section)
98
+
99
+ # Start new section
100
+ header_level = len(line) - len(line.lstrip('#'))
101
+ title = line.lstrip('# ').strip()
102
+ current_section = {
103
+ "title": title,
104
+ "content": "",
105
+ "level": header_level
106
+ }
107
+ else:
108
+ # Add to current section content
109
+ current_section["content"] += line + '\n'
110
+
111
+ # Add the last section
112
+ if current_section["content"].strip():
113
+ sections.append(current_section)
114
+
115
+ # Convert sections to text chunks
116
+ texts = []
117
+ metadata = []
118
+
119
+ for section in sections:
120
+ title = section.get("title", "")
121
+ content = section.get("content", "").strip()
122
+ level = section.get("level", 1)
123
+
124
+ if not content:
125
+ continue
126
+
127
+ # For large sections, chunk them further
128
+ if len(content) > 1500:
129
+ chunks = chunk_text(content, chunk_size=1000, overlap=200)
130
+ for i, chunk in enumerate(chunks):
131
+ full_text = f"# {title}\n\n{chunk}" if title else chunk
132
+ texts.append(full_text)
133
+ metadata.append({
134
+ "title": title,
135
+ "section": f"{title}_part_{i+1}" if title else f"section_part_{i+1}",
136
+ "level": level,
137
+ "content": chunk,
138
+ "type": "markdown_section"
139
+ })
140
+ else:
141
+ full_text = f"# {title}\n\n{content}" if title else content
142
+ texts.append(full_text)
143
+ metadata.append({
144
+ "title": title,
145
+ "section": title or "content",
146
+ "level": level,
147
+ "content": content,
148
+ "type": "markdown_section"
149
+ })
150
+
151
+ return texts, metadata
152
+
153
+ def parse_text_file(file_path):
154
+ """Parse plain text file"""
155
+ with open(file_path, "r", encoding="utf-8") as f:
156
+ content = f.read()
157
+
158
+ # Split into chunks
159
+ chunks = chunk_text(content, chunk_size=1000, overlap=200)
160
+
161
+ texts = []
162
+ metadata = []
163
+
164
+ for i, chunk in enumerate(chunks):
165
+ texts.append(chunk)
166
+ metadata.append({
167
+ "chunk_id": i + 1,
168
+ "content": chunk,
169
+ "type": "text_chunk"
170
+ })
171
+
172
+ return texts, metadata
173
+
174
+ def build_index(input_file, text_key, output_prefix):
175
+ try:
176
+ print(f"Building index for file: {input_file}")
177
+
178
+ # Determine file type and parse accordingly
179
+ file_extension = input_file.lower().split('.')[-1]
180
+
181
+ if file_extension == 'json':
182
+ print(f"Processing JSON file with text key: {text_key}")
183
+
184
+ # Read and parse JSON file
185
+ with open(input_file, "r", encoding="utf-8") as f:
186
+ try:
187
+ data = json.load(f)
188
+ print(f"Successfully loaded JSON with {len(data)} items")
189
+ except json.JSONDecodeError as e:
190
+ print(f"JSON decode error: {str(e)}")
191
+ return False, f"Invalid JSON format: {str(e)}"
192
+
193
+ # Extract texts from JSON
194
+ texts = []
195
+ metadata = []
196
+
197
+ for i, item in enumerate(data):
198
+ if not isinstance(item, dict):
199
+ print(f"Item {i} is not a dictionary: {type(item)}")
200
+ continue
201
+
202
+ text_val = item.get(text_key, "")
203
+ if isinstance(text_val, str) and text_val.strip():
204
+ texts.append(text_val.strip())
205
+ metadata.append(item)
206
+ else:
207
+ print(f"Item {i} has invalid text value for key '{text_key}': {text_val}")
208
+
209
+ if not texts:
210
+ available_keys = list(data[0].keys()) if data else []
211
+ print(f"Available keys in first item: {available_keys}")
212
+ return False, f"No valid text entries found for key '{text_key}'. Available keys: {available_keys}"
213
+
214
+ elif file_extension == 'md':
215
+ print("Processing Markdown file")
216
+ texts, metadata = parse_markdown(input_file)
217
+
218
+ elif file_extension == 'txt':
219
+ print("Processing text file")
220
+ texts, metadata = parse_text_file(input_file)
221
+
222
+ else:
223
+ return False, f"Unsupported file type: {file_extension}"
224
+
225
+ print(f"Extracted {len(texts)} text entries")
226
+
227
+ if not texts:
228
+ return False, "No valid text entries found in file"
229
+
230
+ # Generate embeddings
231
+ print("Generating embeddings...")
232
+ try:
233
+ embeddings = embedder.encode(texts, convert_to_numpy=True, show_progress_bar=False)
234
+ print(f"Generated embeddings shape: {embeddings.shape}")
235
+ except Exception as e:
236
+ print(f"Error generating embeddings: {str(e)}")
237
+ return False, f"Error generating embeddings: {str(e)}"
238
+
239
+ # Create FAISS index
240
+ print("Creating FAISS index...")
241
+ try:
242
+ dim = embeddings.shape[1]
243
+ index = faiss.IndexFlatL2(dim)
244
+ index.add(embeddings)
245
+ print(f"Created index with {index.ntotal} vectors")
246
+ except Exception as e:
247
+ print(f"Error creating FAISS index: {str(e)}")
248
+ return False, f"Error creating FAISS index: {str(e)}"
249
+
250
+ # Save files
251
+ try:
252
+ faiss_path = os.path.join(VECTOR_FOLDER, f"{output_prefix}.faiss")
253
+ texts_path = os.path.join(VECTOR_FOLDER, f"{output_prefix}_texts.json")
254
+ meta_path = os.path.join(VECTOR_FOLDER, f"{output_prefix}_meta.json")
255
+
256
+ faiss.write_index(index, faiss_path)
257
+
258
+ with open(texts_path, "w", encoding="utf-8") as f:
259
+ json.dump(texts, f, indent=2, ensure_ascii=False)
260
+
261
+ with open(meta_path, "w", encoding="utf-8") as f:
262
+ json.dump(metadata, f, indent=2, ensure_ascii=False)
263
+
264
+ print(f"Saved index files: {faiss_path}, {texts_path}, {meta_path}")
265
+
266
+ except Exception as e:
267
+ print(f"Error saving index files: {str(e)}")
268
+ return False, f"Error saving index files: {str(e)}"
269
+
270
+ return True, f"Indexed {len(texts)} entries successfully"
271
+
272
+ except Exception as e:
273
+ print(f"Unexpected error in build_index: {str(e)}")
274
+ return False, f"Unexpected error: {str(e)}"
275
+
276
+
277
+
278
+ def delete_index(prefix):
279
+ files = [
280
+ f"{prefix}.faiss",
281
+ f"{prefix}_texts.json",
282
+ f"{prefix}_meta.json"
283
+ ]
284
+ for file in files:
285
+ path = os.path.join(VECTOR_FOLDER, file)
286
+ if os.path.exists(path):
287
+ os.remove(path)
288
+
289
+ def load_index(prefix):
290
+ index_path = os.path.join(VECTOR_FOLDER, f"{prefix}.faiss")
291
+ text_path = os.path.join(VECTOR_FOLDER, f"{prefix}_texts.json")
292
+ if not os.path.exists(index_path) or not os.path.exists(text_path):
293
+ return None, None
294
+ index = faiss.read_index(index_path)
295
+ with open(text_path) as f:
296
+ texts = json.load(f)
297
+ return index, texts
298
+
299
+ def retrieve(index, texts, query, top_k=3):
300
+ query_vec = embedder.encode([query], convert_to_numpy=True)
301
+ D, I = index.search(query_vec, top_k)
302
+ return [texts[i] for i in I[0]]
303
+
304
+ def run_search(query, index_name=None, top_k=3):
305
+ if not query:
306
+ return {"status":"error", "message":"Query is required"}
307
+ if index_name:
308
+ index,texts = load_index(index_name)
309
+ if not index:
310
+ return {"status":"error","message":f"Index '{index_name}' not found"}
311
+ results = retrieve(index,texts,query,top_k)
312
+ return {"status":"success", "results":results}
313
+ results = {}
314
+ for file in os.listdir(VECTOR_FOLDER):
315
+ if file.endswith('.faiss'):
316
+ prefix = file.replace(".faiss","")
317
+ index,texts = load_index(prefix)
318
+ if index:
319
+ results[prefix] = retrieve(index,texts,query,top_k)
320
+ return {"status":"success","results":results}
321
+
322
+
323
+
324
+ # Updated upload route that doesn't require text_key for non-JSON files
325
+ @app.route("/upload", methods=["POST"])
326
+ def upload_file():
327
+ try:
328
+ print("Upload request received")
329
+
330
+ if "file" not in request.files:
331
+ print("No file in request")
332
+ return jsonify({"status": "error", "message": "No file uploaded"}), 400
333
+
334
+ file = request.files["file"]
335
+ text_key = request.form.get("text_key", "text") # Default for JSON files
336
+
337
+ print(f"File received: {file.filename}")
338
+ print(f"Text key: {text_key}")
339
+
340
+ if file.filename == "":
341
+ print("Empty filename")
342
+ return jsonify({"status": "error", "message": "No selected file"}), 400
343
+
344
+ if not file or not allowed_files(file.filename):
345
+ print("Invalid file type or no file")
346
+ return jsonify({"status": "error", "message": "Invalid file type"}), 400
347
+
348
+ # Save file
349
+ filename = secure_filename(file.filename)
350
+ file_path = os.path.join(UPLOAD_FOLDER, filename)
351
+
352
+ try:
353
+ file.save(file_path)
354
+ print(f"File saved to: {file_path}")
355
+ except Exception as e:
356
+ print(f"Error saving file: {str(e)}")
357
+ return jsonify({"status": "error", "message": f"Error saving file: {str(e)}"}), 500
358
+
359
+ # Build index
360
+ prefix = filename.split(".", 1)[0]
361
+ print(f"Building index with prefix: {prefix}")
362
+
363
+ try:
364
+ success, msg = build_index(file_path, text_key, prefix)
365
+ print(f"Index build result: {success}, message: {msg}")
366
+ except Exception as e:
367
+ print(f"Error building index: {str(e)}")
368
+ if os.path.exists(file_path):
369
+ os.remove(file_path)
370
+ return jsonify({"status": "error", "message": f"Error processing file: {str(e)}"}), 500
371
+
372
+ if not success:
373
+ print(f"Index building failed: {msg}")
374
+ if os.path.exists(file_path):
375
+ os.remove(file_path)
376
+ return jsonify({"status": "error", "message": msg}), 400
377
+
378
+ print(f"Upload successful: {msg}")
379
+ return jsonify({"status": "success", "message": msg, "file": filename}), 200
380
+
381
+ except Exception as e:
382
+ print(f"Unexpected error in upload: {str(e)}")
383
+ return jsonify({"status": "error", "message": f"Unexpected error: {str(e)}"}), 500
384
+
385
+ @app.route("/files",methods=["GET"])
386
+ def list_files():
387
+ files = os.listdir(UPLOAD_FOLDER)
388
+ return jsonify({"status":"success","files":files})
389
+
390
+ @app.route("/delete/<filename>", methods=["DELETE"])
391
+ def delete_file(filename):
392
+ file_path = os.path.join(UPLOAD_FOLDER,filename)
393
+ prefix = filename.rsplit(".",1)[0]
394
+ if os.path.exists(file_path):
395
+ os.remove(file_path)
396
+ delete_index(prefix)
397
+ return jsonify({"status":"success","message":f"{filename} and index deleted"})
398
+ else:
399
+ return jsonify({"status":"error","message":"File not found"}),400
400
+
401
+ @app.route("/search", methods=["POST"])
402
+ def search():
403
+ data = request.get_json()
404
+ query = data.get("query")
405
+ index_name = data.get("index_name")
406
+ top_k = int(data.get("top_k", 3))
407
+
408
+ result = run_search(query, index_name=index_name, top_k=top_k)
409
+
410
+ if result.get("status") == "error":
411
+ return jsonify(result), 400
412
+
413
+ prompt = f"""
414
+ You are a policy compliance adviser.
415
+ Reframe these policies into simple, clear sentences.
416
+
417
+ ⚠️ STRICT INSTRUCTION: Output ONLY valid JSON in this format:
418
+ {{
419
+ "results": [
420
+ "policy 1 reformulated",
421
+ "policy 2 reformulated",
422
+ ...
423
+ ],
424
+ "status": "success"
425
+ }}
426
+
427
+ Policies for reference:
428
+ {result}
429
+ """
430
+
431
+ raw_response = call_claude(prompt)
432
+
433
+ # --- Extract only JSON ---
434
+ try:
435
+ match = re.search(r"\{.*\}", raw_response, re.DOTALL)
436
+ if match:
437
+ policy_result = json.loads(match.group(0))
438
+ else:
439
+ policy_result = {"results": [], "status": "error", "message": "No JSON found"}
440
+ except Exception as e:
441
+ policy_result = {"results": [], "status": "error", "message": str(e)}
442
+
443
+ return jsonify(policy_result)
444
+
445
+
446
+
447
+ @app.route("/validate_instruction", methods=["POST"])
448
+ def validate_instruction():
449
+ data = request.get_json()
450
+ instruction = data.get("instruction")
451
+ index_name = data.get("index_name")
452
+ top_k = int(data.get("top_k", 3))
453
+
454
+ if not instruction:
455
+ return jsonify({"error": "Missing 'instruction' in request"}), 400
456
+
457
+ search_result = run_search(instruction, index_name=index_name, top_k=top_k)
458
+ if search_result.get("status") != "success":
459
+ return jsonify({"error":"Search Failed", "details":search_result}),500
460
+ context_results = search_result["results"]
461
+
462
+
463
+
464
+ prompt = f"""
465
+ You are a policy compliance checker and an instruction validator.
466
+
467
+ Evaluation Criteria
468
+ 1. USER-FACING
469
+ a. The instruction must be directed at an end user in natural, human-centered language.
470
+ b. It must not read like a direct command to a system, developer, or internal process.
471
+ c. Prefer “you” or “you want to…” phrasing.
472
+ d. Avoid technical commands like “delete invoice 42,” “POST to API endpoint,” or “run SQL query.”
473
+
474
+ 2. OUTPUT/GOAL ORIENTED (not procedural)
475
+ a. The instruction must specify the exact outcome or solution the task is designed to achieve, not how to do it step-by-step.
476
+ b. Avoid “spoon-feeding” the system with exact process steps (looping, filtering, database operations, etc.).
477
+
478
+ 3. SINGLE, UNAMBIGUOUS OUTCOME
479
+ a. One overarching outcome – It expresses a single desired result instead of multiple separate actions.
480
+ b. User-centered – Written in second person (“you want to…”) so it’s directed at the end user.
481
+ c. Context-preserving – All relevant details (time, people, conditions, constraints) are included, but only as supporting context to achieve that one outcome.
482
+ d. Clarity & measurability – The goal is specific enough that you can verify when it has been achieved.
483
+ e. No competing intents – Even if there are multiple steps, they are framed as sub-parts of one larger objective, not as separate goals.
484
+ Example:
485
+ Not a single goal (ambiguous): “Fix the bulb, create an alert, and schedule automation.”
486
+ Single unambiguous goal: “You want to ensure reliable bulb management by fixing the malfunction, logging the alert acknowledged by David Navarro, and setting up a daily shutdown routine.”
487
+
488
+
489
+ 4. POLICY COMPLIANT
490
+ a. The instruction must follow the given policy and not introduce extra constraints that could conflict.
491
+ b. If it violates policy or imposes unrelated restrictions, it fails.
492
+
493
+ Pass/Fail Decision Tree
494
+ Is it user-facing? → No = FAIL.
495
+ Is it goal-oriented (not process)? → No = FAIL.
496
+ Does it have one clear outcome? → No = FAIL.
497
+ Is it policy compliant? → No = FAIL.
498
+ If all 4 pass → OVERALL: PASS.
499
+
500
+ improved_instruction:
501
+ a. The improved instruction should tell how to frame sentence so that single outcome is achieved.
502
+ b. Do not omit any detils that is given in the instruction.
503
+ c. Your job is to modify the instruction in such a way that all the checks passes, and the details in instruction are also not lost also keep in mind that the instruction should be compact.
504
+ d. Also keep in mind all the compliances while modifying the instruction like user_facing,output_oriented, single_outcome, policy_compliant, overall.
505
+
506
+ Policy rules:
507
+ {context_results}
508
+
509
+ Good Examples:
510
+ You are James Shawn ([email protected]). On 2025-08-07, you want to add a 100,000 EUR subscription to the 'Emerging Markets Equity Fund' for investor Lawson-Edwards, assign it to yourself, and send them a subscription update email. You also want to create an invoice for half the subscription amount with due date 2025-08-31 and send an alert email for it.
511
+
512
+ Bad Examples:
513
+ You are Natasha Hickman (email: [email protected]), an administrator who needs to handle a comprehensive commitment management scenario for multiple investors. First, you need to verify your identity and then check if investor ID 15 has any existing commitments for fund ID 25. If no commitment exists, you need to create a new commitment for 500,000 GBP with a commitment date of September 10, 2025. Then, retrieve all commitments for this investor to verify the creation. Next, you need to update the commitment amount to 750,000 GBP due to increased investor interest. After the update, check the commitment fulfillment status and calculate the fulfillment percentage. Additionally, create another commitment for investor ID 30 to fund ID 25 for 300,000 GBP with a commitment date of September 15, 2025. Retrieve all commitments for fund ID 25 to see both commitments. However, investor ID 30 has decided to withdraw, so you need to delete their commitment. Finally, generate a holding report for fund ID 25 for investor ID 15 with a report date and export period end date of September 25, 2025, and send an email notification of type alert to investor ID 15 about their updated commitment status.
514
+
515
+ Instruction:
516
+ {instruction}
517
+
518
+ Decide if the instruction is VALID or INVALID according to the rules.
519
+ Respond ONLY in format given below:
520
+ {{
521
+ "user_facing": {{
522
+ "result": "PASS/FAIL",
523
+ "explanation": "..."
524
+ }},
525
+ "output_oriented": {{
526
+ "result": "PASS/FAIL",
527
+ "explanation": "..."
528
+ }},
529
+ "single_outcome": {{
530
+ "result": "PASS/FAIL",
531
+ "explanation": "..."
532
+ }},
533
+ "policy_compliant": {{
534
+ "result": "PASS/FAIL",
535
+ "explanation": "..."
536
+ }},
537
+ "overall": {{
538
+ "result": "PASS/FAIL",
539
+ "summary": "...",
540
+ "improved_instruction": ["...", "...", "..."]
541
+ }}
542
+ }}
543
+ """
544
+
545
+ result_text = call_claude(prompt)
546
+
547
+
548
+ if result_text.startswith("```"):
549
+ result_text = result_text.strip("`").lstrip("json").strip()
550
+
551
+ try:
552
+ validation_data = json.loads(result_text)
553
+ except json.JSONDecodeError as e:
554
+ return jsonify({
555
+ "error": "Invalid JSON from model",
556
+ "raw_output": result_text,
557
+ "details": str(e)
558
+ }), 500
559
+
560
+ return jsonify({"Validation": validation_data})
561
+
562
+ if __name__ == "__main__":
563
+ import os
564
+ port = int(os.environ.get("PORT", 7860))
565
+ app.run(host="0.0.0.0", port=port, debug=False)
dockerfile ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Base image with Python
2
+ FROM python:3.10-slim
3
+
4
+ # Set working directory
5
+ WORKDIR /app
6
+
7
+ # Copy requirements and install
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ # Copy app code
12
+ COPY . .
13
+
14
+ # Hugging Face Spaces expect app to listen on 0.0.0.0:7860
15
+ ENV PORT 7860
16
+
17
+ # Expose port
18
+ EXPOSE 7860
19
+
20
+ # Run Flask app
21
+ CMD ["python", "app.py"]
requirements.txt ADDED
Binary file (160 Bytes). View file