clinical-analysis-api / decrypt_response.py
MakPr016
Analysis includes NPL summary
6c66675
"""
Decrypt and analyze API response from Postman
"""
import base64
import gzip
import json
import sys
import os
from nacl.secret import SecretBox
# Your hex key from .env
SECRET_KEY_HEX = "7633eeaf69156124e49025ce8f6a3adbdbf6be87f1e58529397a67168a65bd66"
# Convert hex to bytes (32 bytes)
SECRET_KEY = bytes.fromhex(SECRET_KEY_HEX)
print(f"βœ“ Key length: {len(SECRET_KEY)} bytes")
def decrypt_response(ciphertext, nonce):
"""Decrypt the encrypted response"""
try:
box = SecretBox(SECRET_KEY) # Use bytes directly, not .encode()
ciphertext_bytes = base64.b64decode(ciphertext)
nonce_bytes = base64.b64decode(nonce)
decrypted = box.decrypt(ciphertext_bytes, nonce_bytes)
decompressed = gzip.decompress(base64.b64decode(decrypted))
return json.loads(decompressed.decode('utf-8'))
except Exception as e:
print(f"❌ Decryption error: {e}")
import traceback
traceback.print_exc()
return None
def print_summary(result):
"""Print a nice summary of the results"""
print("\n" + "="*70)
print("LAB REPORT ANALYSIS SUMMARY")
print("="*70)
# Basic info
print(f"\nπŸ“‹ Report Information:")
print(f" Report ID: {result.get('report_id', 'N/A')}")
print(f" Report Type: {result.get('report_type', 'N/A')}")
print(f" Processing Time: {result.get('processing_time', 'N/A')}s")
print(f" OCR Used: {result.get('ocr_used', 'N/A')}")
print(f" OCR Engine: {result.get('ocr_engine', 'N/A')}")
# Test results
test_results = result.get('test_results', [])
print(f"\nπŸ§ͺ Test Results: {len(test_results)} tests")
if test_results:
for i, test in enumerate(test_results, 1):
status_icon = "βœ“" if test['status'] == 'normal' else "⚠️"
print(f"\n{status_icon} {i}. {test['test_name']}")
print(f" Value: {test['value']} {test['unit']}")
print(f" Status: {test['status'].upper()}")
if test['status'] != 'normal':
print(f" β†’ {test['clinical_significance']}")
# Abnormal results
abnormal = result.get('abnormal_results', [])
if abnormal:
print(f"\n⚠️ ABNORMAL RESULTS ({len(abnormal)}):")
for abn in abnormal:
print(f" β€’ {abn['test_name']} ({abn['severity']})")
# Clinical Insights
clinical_insights = result.get('clinical_insights', {})
if clinical_insights:
print(f"\n🧬 CLINICAL INSIGHTS:")
print(f" Relevance Score: {clinical_insights.get('clinical_relevance_score', 0)}/100")
if clinical_insights.get('abnormality_patterns'):
for pattern in clinical_insights['abnormality_patterns']:
print(f" β€’ {pattern}")
print("\n" + "="*70)
def main():
print("="*70)
print("LAB REPORT API RESPONSE DECRYPTOR")
print("="*70)
response_file = sys.argv[1] if len(sys.argv) > 1 else "tests/samples/response.json"
if not os.path.exists(response_file):
print(f"❌ File not found: {response_file}")
return
print(f"\nπŸ“‚ Reading: {response_file}")
with open(response_file, 'r') as f:
encrypted_response = json.load(f)
if 'ciphertext' not in encrypted_response or 'nonce' not in encrypted_response:
print("❌ Invalid response format")
return
print("πŸ”“ Decrypting...")
decrypted = decrypt_response(
encrypted_response['ciphertext'],
encrypted_response['nonce']
)
if not decrypted:
return
print("βœ… Successfully decrypted!")
# Save
output_file = response_file.replace('.json', '_decrypted.json')
with open(output_file, 'w') as f:
json.dump(decrypted, f, indent=2)
print(f"πŸ’Ύ Saved to: {output_file}")
# Print summary
print_summary(decrypted)
print("\nβœ… Done!")
if __name__ == "__main__":
main()