tejash300 commited on
Commit
2d967e5
·
verified ·
1 Parent(s): ae819dc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +728 -0
app.py ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import torch
4
+ import uvicorn
5
+ import spacy
6
+ import pdfplumber
7
+ import moviepy.editor as mp
8
+ import librosa
9
+ import soundfile as sf
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ import json
13
+ import tempfile
14
+ from fastapi import FastAPI, UploadFile, File, HTTPException, Form
15
+ from fastapi.responses import FileResponse, JSONResponse
16
+ from fastapi.middleware.cors import CORSMiddleware
17
+ from transformers import pipeline, AutoModelForQuestionAnswering, AutoTokenizer
18
+ from sentence_transformers import SentenceTransformer
19
+ from pyngrok import ngrok
20
+ from threading import Thread
21
+ import time
22
+ import uuid
23
+
24
+ # Ensure compatibility with Google Colab (if applicable)
25
+ try:
26
+ from google.colab import drive
27
+ drive.mount('/content/drive')
28
+ except:
29
+ pass # Skip drive mount if not in Google Colab
30
+
31
+ # Ensure required directories exist
32
+ os.makedirs("static", exist_ok=True)
33
+ os.makedirs("temp", exist_ok=True)
34
+
35
+ # Ensure GPU usage
36
+ device = "cuda" if torch.cuda.is_available() else "cpu"
37
+
38
+ # Initialize FastAPI
39
+ app = FastAPI(title="Legal Document and Video Analyzer")
40
+
41
+ # Add CORS middleware
42
+ app.add_middleware(
43
+ CORSMiddleware,
44
+ allow_origins=["*"],
45
+ allow_credentials=True,
46
+ allow_methods=["*"],
47
+ allow_headers=["*"],
48
+ )
49
+
50
+ # Initialize document storage
51
+ document_storage = {}
52
+ chat_history = [] # Global chat history
53
+
54
+ # Function to store document context by task ID
55
+ def store_document_context(task_id, text):
56
+ """Store document text for retrieval by chatbot."""
57
+ document_storage[task_id] = text
58
+ return True
59
+
60
+ # Function to load document context by task ID
61
+ def load_document_context(task_id):
62
+ """Retrieve document text for chatbot context."""
63
+ return document_storage.get(task_id, "")
64
+
65
+ #############################
66
+ # Fine-tuning on CUAD QA #
67
+ #############################
68
+
69
+ def fine_tune_cuad_model():
70
+ """
71
+ Fine tunes a question-answering model on the CUAD (Contract Understanding Atticus Dataset)
72
+ for detailed clause extraction. This demo function uses one epoch for demonstration;
73
+ adjust training parameters as needed.
74
+ """
75
+ from datasets import load_dataset
76
+ import numpy as np
77
+ from transformers import Trainer, TrainingArguments
78
+ from transformers import AutoModelForQuestionAnswering
79
+
80
+ print("✅ Loading CUAD dataset for fine tuning...")
81
+ dataset = load_dataset("theatticusproject/cuad-qa", trust_remote_code=True)
82
+
83
+ if "train" in dataset:
84
+ train_dataset = dataset["train"].select(range(1000))
85
+ if "validation" in dataset:
86
+ val_dataset = dataset["validation"].select(range(200))
87
+ else:
88
+ split = train_dataset.train_test_split(test_size=0.2)
89
+ train_dataset = split["train"]
90
+ val_dataset = split["test"]
91
+ else:
92
+ raise ValueError("CUAD dataset does not have a train split")
93
+
94
+ print("✅ Preparing training features...")
95
+
96
+ tokenizer = AutoTokenizer.from_pretrained("deepset/roberta-base-squad2")
97
+ model = AutoModelForQuestionAnswering.from_pretrained("deepset/roberta-base-squad2")
98
+
99
+ def prepare_train_features(examples):
100
+ tokenized_examples = tokenizer(
101
+ examples["question"],
102
+ examples["context"],
103
+ truncation="only_second",
104
+ max_length=384,
105
+ stride=128,
106
+ return_overflowing_tokens=True,
107
+ return_offsets_mapping=True,
108
+ padding="max_length",
109
+ )
110
+ sample_mapping = tokenized_examples.pop("overflow_to_sample_mapping")
111
+ offset_mapping = tokenized_examples.pop("offset_mapping")
112
+ tokenized_examples["start_positions"] = []
113
+ tokenized_examples["end_positions"] = []
114
+ for i, offsets in enumerate(offset_mapping):
115
+ input_ids = tokenized_examples["input_ids"][i]
116
+ cls_index = input_ids.index(tokenizer.cls_token_id)
117
+ sequence_ids = tokenized_examples.sequence_ids(i)
118
+ sample_index = sample_mapping[i]
119
+ answers = examples["answers"][sample_index]
120
+ if len(answers["answer_start"]) == 0:
121
+ tokenized_examples["start_positions"].append(cls_index)
122
+ tokenized_examples["end_positions"].append(cls_index)
123
+ else:
124
+ start_char = answers["answer_start"][0]
125
+ end_char = start_char + len(answers["text"][0])
126
+ tokenized_start_index = 0
127
+ while sequence_ids[tokenized_start_index] != 1:
128
+ tokenized_start_index += 1
129
+ tokenized_end_index = len(input_ids) - 1
130
+ while sequence_ids[tokenized_end_index] != 1:
131
+ tokenized_end_index -= 1
132
+ if not (offsets[tokenized_start_index][0] <= start_char and offsets[tokenized_end_index][1] >= end_char):
133
+ tokenized_examples["start_positions"].append(cls_index)
134
+ tokenized_examples["end_positions"].append(cls_index)
135
+ else:
136
+ while tokenized_start_index < len(offsets) and offsets[tokenized_start_index][0] <= start_char:
137
+ tokenized_start_index += 1
138
+ tokenized_examples["start_positions"].append(tokenized_start_index - 1)
139
+ while offsets[tokenized_end_index][1] >= end_char:
140
+ tokenized_end_index -= 1
141
+ tokenized_examples["end_positions"].append(tokenized_end_index + 1)
142
+ return tokenized_examples
143
+
144
+ print("✅ Tokenizing dataset...")
145
+ train_dataset = train_dataset.map(prepare_train_features, batched=True, remove_columns=train_dataset.column_names)
146
+ val_dataset = val_dataset.map(prepare_train_features, batched=True, remove_columns=val_dataset.column_names)
147
+
148
+ train_dataset.set_format(type="torch", columns=["input_ids", "attention_mask", "start_positions", "end_positions"])
149
+ val_dataset.set_format(type="torch", columns=["input_ids", "attention_mask", "start_positions", "end_positions"])
150
+
151
+ training_args = TrainingArguments(
152
+ output_dir="./fine_tuned_legal_qa",
153
+ evaluation_strategy="steps",
154
+ eval_steps=100,
155
+ learning_rate=2e-5,
156
+ per_device_train_batch_size=16,
157
+ per_device_eval_batch_size=16,
158
+ num_train_epochs=1,
159
+ weight_decay=0.01,
160
+ logging_steps=50,
161
+ save_steps=100,
162
+ load_best_model_at_end=True,
163
+ report_to=[]
164
+ )
165
+
166
+ print("✅ Starting fine tuning on CUAD QA dataset...")
167
+ trainer = Trainer(
168
+ model=model,
169
+ args=training_args,
170
+ train_dataset=train_dataset,
171
+ eval_dataset=val_dataset,
172
+ tokenizer=tokenizer,
173
+ )
174
+
175
+ trainer.train()
176
+ print("✅ Fine tuning completed. Saving model...")
177
+
178
+ model.save_pretrained("./fine_tuned_legal_qa")
179
+ tokenizer.save_pretrained("./fine_tuned_legal_qa")
180
+
181
+ return tokenizer, model
182
+
183
+ #############################
184
+ # Load NLP Models #
185
+ #############################
186
+
187
+ try:
188
+ try:
189
+ nlp = spacy.load("en_core_web_sm")
190
+ except:
191
+ spacy.cli.download("en_core_web_sm")
192
+ nlp = spacy.load("en_core_web_sm")
193
+ print("✅ Loading NLP models...")
194
+
195
+ summarizer = pipeline("summarization", model="nsi319/legal-pegasus",
196
+ device=0 if torch.cuda.is_available() else -1)
197
+ embedding_model = SentenceTransformer("all-mpnet-base-v2", device=device)
198
+ ner_model = pipeline("ner", model="dslim/bert-base-NER",
199
+ device=0 if torch.cuda.is_available() else -1)
200
+ speech_to_text = pipeline("automatic-speech-recognition",
201
+ model="openai/whisper-medium",
202
+ chunk_length_s=30,
203
+ device_map="auto" if torch.cuda.is_available() else "cpu")
204
+
205
+ # Load or Fine Tune CUAD QA Model
206
+ if os.path.exists("fine_tuned_legal_qa"):
207
+ print("✅ Loading fine-tuned CUAD QA model from fine_tuned_legal_qa...")
208
+ cuad_tokenizer = AutoTokenizer.from_pretrained("fine_tuned_legal_qa")
209
+ from transformers import AutoModelForQuestionAnswering
210
+ cuad_model = AutoModelForQuestionAnswering.from_pretrained("fine_tuned_legal_qa")
211
+ cuad_model.to(device)
212
+ else:
213
+ print("⚠️ Fine-tuned QA model not found. Starting fine tuning on CUAD QA dataset. This may take a while...")
214
+ cuad_tokenizer, cuad_model = fine_tune_cuad_model()
215
+ cuad_model.to(device)
216
+
217
+ print("✅ All models loaded successfully")
218
+
219
+ except Exception as e:
220
+ print(f"⚠️ Error loading models: {str(e)}")
221
+ raise RuntimeError(f"Error loading models: {str(e)}")
222
+
223
+ qa_model = pipeline("question-answering", model="deepset/roberta-base-squad2")
224
+
225
+ def legal_chatbot(user_input, context):
226
+ """Uses a real NLP model for legal Q&A."""
227
+ global chat_history
228
+ chat_history.append({"role": "user", "content": user_input})
229
+ response = qa_model(question=user_input, context=context)["answer"]
230
+ chat_history.append({"role": "assistant", "content": response})
231
+ return response
232
+
233
+ def extract_text_from_pdf(pdf_file):
234
+ """Extracts text from a PDF file using pdfplumber."""
235
+ try:
236
+ with pdfplumber.open(pdf_file) as pdf:
237
+ text = "\n".join([page.extract_text() or "" for page in pdf.pages])
238
+ return text.strip() if text else None
239
+ except Exception as e:
240
+ raise HTTPException(status_code=400, detail=f"PDF extraction failed: {str(e)}")
241
+
242
+ def process_video_to_text(video_file_path):
243
+ """Extract audio from video and convert to text."""
244
+ try:
245
+ print(f"Processing video file at {video_file_path}")
246
+ temp_audio_path = os.path.join("temp", "extracted_audio.wav")
247
+ video = mp.VideoFileClip(video_file_path)
248
+ video.audio.write_audiofile(temp_audio_path, codec='pcm_s16le')
249
+ print(f"Audio extracted to {temp_audio_path}")
250
+ result = speech_to_text(temp_audio_path)
251
+ transcript = result["text"]
252
+ print(f"Transcription completed: {len(transcript)} characters")
253
+ if os.path.exists(temp_audio_path):
254
+ os.remove(temp_audio_path)
255
+ return transcript
256
+ except Exception as e:
257
+ print(f"Error in video processing: {str(e)}")
258
+ raise HTTPException(status_code=400, detail=f"Video processing failed: {str(e)}")
259
+
260
+ def process_audio_to_text(audio_file_path):
261
+ """Process audio file and convert to text."""
262
+ try:
263
+ print(f"Processing audio file at {audio_file_path}")
264
+ result = speech_to_text(audio_file_path)
265
+ transcript = result["text"]
266
+ print(f"Transcription completed: {len(transcript)} characters")
267
+ return transcript
268
+ except Exception as e:
269
+ print(f"Error in audio processing: {str(e)}")
270
+ raise HTTPException(status_code=400, detail=f"Audio processing failed: {str(e)}")
271
+
272
+ def extract_named_entities(text):
273
+ """Extracts named entities from legal text."""
274
+ max_length = 10000
275
+ entities = []
276
+ for i in range(0, len(text), max_length):
277
+ chunk = text[i:i+max_length]
278
+ doc = nlp(chunk)
279
+ entities.extend([{"entity": ent.text, "label": ent.label_} for ent in doc.ents])
280
+ return entities
281
+
282
+ def analyze_risk(text):
283
+ """Analyzes legal risk in the document using keyword-based analysis."""
284
+ risk_keywords = {
285
+ "Liability": ["liability", "responsible", "responsibility", "legal obligation"],
286
+ "Termination": ["termination", "breach", "contract end", "default"],
287
+ "Indemnification": ["indemnification", "indemnify", "hold harmless", "compensate", "compensation"],
288
+ "Payment Risk": ["payment", "terms", "reimbursement", "fee", "schedule", "invoice", "money"],
289
+ "Insurance": ["insurance", "coverage", "policy", "claims"],
290
+ }
291
+ risk_scores = {category: 0 for category in risk_keywords}
292
+ lower_text = text.lower()
293
+ for category, keywords in risk_keywords.items():
294
+ for keyword in keywords:
295
+ risk_scores[category] += lower_text.count(keyword.lower())
296
+ return risk_scores
297
+
298
+ def extract_context_for_risk_terms(text, risk_keywords, window=1):
299
+ """
300
+ Extracts and summarizes the context around risk terms.
301
+ """
302
+ doc = nlp(text)
303
+ sentences = list(doc.sents)
304
+ risk_contexts = {category: [] for category in risk_keywords}
305
+ for i, sent in enumerate(sentences):
306
+ sent_text_lower = sent.text.lower()
307
+ for category, details in risk_keywords.items():
308
+ for keyword in details["keywords"]:
309
+ if keyword.lower() in sent_text_lower:
310
+ start_idx = max(0, i - window)
311
+ end_idx = min(len(sentences), i + window + 1)
312
+ context_chunk = " ".join([s.text for s in sentences[start_idx:end_idx]])
313
+ risk_contexts[category].append(context_chunk)
314
+ summarized_contexts = {}
315
+ for category, contexts in risk_contexts.items():
316
+ if contexts:
317
+ combined_context = " ".join(contexts)
318
+ try:
319
+ summary_result = summarizer(combined_context, max_length=100, min_length=30, do_sample=False)
320
+ summary = summary_result[0]['summary_text']
321
+ except Exception as e:
322
+ summary = "Context summarization failed."
323
+ summarized_contexts[category] = summary
324
+ else:
325
+ summarized_contexts[category] = "No contextual details found."
326
+ return summarized_contexts
327
+
328
+ def get_detailed_risk_info(text):
329
+ """
330
+ Returns detailed risk information by merging risk scores with descriptive details
331
+ and contextual summaries from the document.
332
+ """
333
+ risk_details = {
334
+ "Liability": {
335
+ "description": "Liability refers to the legal responsibility for losses or damages.",
336
+ "common_concerns": "Broad liability clauses may expose parties to unforeseen risks.",
337
+ "recommendations": "Review and negotiate clear limits on liability.",
338
+ "example": "E.g., 'The party shall be liable for direct damages due to negligence.'"
339
+ },
340
+ "Termination": {
341
+ "description": "Termination involves conditions under which a contract can be ended.",
342
+ "common_concerns": "Unilateral termination rights or ambiguous conditions can be risky.",
343
+ "recommendations": "Ensure termination clauses are balanced and include notice periods.",
344
+ "example": "E.g., 'Either party may terminate the agreement with 30 days notice.'"
345
+ },
346
+ "Indemnification": {
347
+ "description": "Indemnification requires one party to compensate for losses incurred by the other.",
348
+ "common_concerns": "Overly broad indemnification can shift significant risk.",
349
+ "recommendations": "Negotiate clear limits and carve-outs where necessary.",
350
+ "example": "E.g., 'The seller shall indemnify the buyer against claims from product defects.'"
351
+ },
352
+ "Payment Risk": {
353
+ "description": "Payment risk pertains to terms regarding fees, schedules, and reimbursements.",
354
+ "common_concerns": "Vague payment terms or hidden charges increase risk.",
355
+ "recommendations": "Clarify payment conditions and include penalties for delays.",
356
+ "example": "E.g., 'Payments must be made within 30 days, with a 2% late fee thereafter.'"
357
+ },
358
+ "Insurance": {
359
+ "description": "Insurance risk covers the adequacy and scope of required coverage.",
360
+ "common_concerns": "Insufficient insurance can leave parties exposed in unexpected events.",
361
+ "recommendations": "Review insurance requirements to ensure they meet the risk profile.",
362
+ "example": "E.g., 'The contractor must maintain liability insurance with at least $1M coverage.'"
363
+ }
364
+ }
365
+ risk_scores = analyze_risk(text)
366
+ risk_keywords_context = {
367
+ "Liability": {"keywords": ["liability", "responsible", "responsibility", "legal obligation"]},
368
+ "Termination": {"keywords": ["termination", "breach", "contract end", "default"]},
369
+ "Indemnification": {"keywords": ["indemnification", "indemnify", "hold harmless", "compensate", "compensation"]},
370
+ "Payment Risk": {"keywords": ["payment", "terms", "reimbursement", "fee", "schedule", "invoice", "money"]},
371
+ "Insurance": {"keywords": ["insurance", "coverage", "policy", "claims"]}
372
+ }
373
+ risk_contexts = extract_context_for_risk_terms(text, risk_keywords_context, window=1)
374
+ detailed_info = {}
375
+ for risk_term, score in risk_scores.items():
376
+ if score > 0:
377
+ info = risk_details.get(risk_term, {"description": "No details available."})
378
+ detailed_info[risk_term] = {
379
+ "score": score,
380
+ "description": info.get("description", ""),
381
+ "common_concerns": info.get("common_concerns", ""),
382
+ "recommendations": info.get("recommendations", ""),
383
+ "example": info.get("example", ""),
384
+ "context_summary": risk_contexts.get(risk_term, "No context available.")
385
+ }
386
+ return detailed_info
387
+
388
+ def analyze_contract_clauses(text):
389
+ """Analyzes contract clauses using the fine-tuned CUAD QA model."""
390
+ max_length = 512
391
+ step = 256
392
+ clauses_detected = []
393
+ try:
394
+ clause_types = list(cuad_model.config.id2label.values())
395
+ except Exception as e:
396
+ clause_types = [
397
+ "Obligations of Seller", "Governing Law", "Termination", "Indemnification",
398
+ "Confidentiality", "Insurance", "Non-Compete", "Change of Control",
399
+ "Assignment", "Warranty", "Limitation of Liability", "Arbitration",
400
+ "IP Rights", "Force Majeure", "Revenue/Profit Sharing", "Audit Rights"
401
+ ]
402
+ chunks = [text[i:i+max_length] for i in range(0, len(text), step) if i+step < len(text)]
403
+ for chunk in chunks:
404
+ inputs = cuad_tokenizer(chunk, return_tensors="pt", truncation=True, max_length=512).to(device)
405
+ with torch.no_grad():
406
+ outputs = cuad_model(**inputs)
407
+ predictions = torch.sigmoid(outputs.start_logits).cpu().numpy()[0]
408
+ for idx, confidence in enumerate(predictions):
409
+ if confidence > 0.5 and idx < len(clause_types):
410
+ clauses_detected.append({"type": clause_types[idx], "confidence": float(confidence)})
411
+ aggregated_clauses = {}
412
+ for clause in clauses_detected:
413
+ clause_type = clause["type"]
414
+ if clause_type not in aggregated_clauses or clause["confidence"] > aggregated_clauses[clause_type]["confidence"]:
415
+ aggregated_clauses[clause_type] = clause
416
+ return list(aggregated_clauses.values())
417
+
418
+ @app.post("/analyze_legal_document")
419
+ async def analyze_legal_document(file: UploadFile = File(...)):
420
+ """Analyzes a legal document for clause detection and compliance risks."""
421
+ try:
422
+ print(f"Processing file: {file.filename}")
423
+ content = await file.read()
424
+ text = extract_text_from_pdf(io.BytesIO(content))
425
+ if not text:
426
+ return {"status": "error", "message": "No valid text found in the document."}
427
+ summary_text = text[:4096] if len(text) > 4096 else text
428
+ summary = summarizer(summary_text, max_length=200, min_length=50, do_sample=False)[0]['summary_text'] if len(text) > 100 else "Document too short for meaningful summarization."
429
+ print("Extracting named entities...")
430
+ entities = extract_named_entities(text)
431
+ print("Analyzing risk...")
432
+ risk_scores = analyze_risk(text)
433
+ detailed_risk = get_detailed_risk_info(text)
434
+ print("Analyzing contract clauses...")
435
+ clauses = analyze_contract_clauses(text)
436
+ generated_task_id = str(uuid.uuid4())
437
+ store_document_context(generated_task_id, text)
438
+ return {
439
+ "status": "success",
440
+ "task_id": generated_task_id,
441
+ "summary": summary,
442
+ "named_entities": entities,
443
+ "risk_scores": risk_scores,
444
+ "detailed_risk": detailed_risk,
445
+ "clauses_detected": clauses
446
+ }
447
+ except Exception as e:
448
+ print(f"Error processing document: {str(e)}")
449
+ return {"status": "error", "message": str(e)}
450
+
451
+ @app.post("/analyze_legal_video")
452
+ async def analyze_legal_video(file: UploadFile = File(...)):
453
+ """Analyzes a legal video by transcribing audio and analyzing the transcript."""
454
+ try:
455
+ print(f"Processing video file: {file.filename}")
456
+ content = await file.read()
457
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as temp_file:
458
+ temp_file.write(content)
459
+ temp_file_path = temp_file.name
460
+ print(f"Temporary file saved at: {temp_file_path}")
461
+ text = process_video_to_text(temp_file_path)
462
+ if os.path.exists(temp_file_path):
463
+ os.remove(temp_file_path)
464
+ if not text:
465
+ return {"status": "error", "message": "No speech could be transcribed from the video."}
466
+ transcript_path = os.path.join("static", f"transcript_{int(time.time())}.txt")
467
+ with open(transcript_path, "w") as f:
468
+ f.write(text)
469
+ summary_text = text[:4096] if len(text) > 4096 else text
470
+ summary = summarizer(summary_text, max_length=200, min_length=50, do_sample=False)[0]['summary_text'] if len(text) > 100 else "Transcript too short for meaningful summarization."
471
+ print("Extracting named entities from transcript...")
472
+ entities = extract_named_entities(text)
473
+ print("Analyzing risk from transcript...")
474
+ risk_scores = analyze_risk(text)
475
+ detailed_risk = get_detailed_risk_info(text)
476
+ print("Analyzing legal clauses from transcript...")
477
+ clauses = analyze_contract_clauses(text)
478
+ generated_task_id = str(uuid.uuid4())
479
+ store_document_context(generated_task_id, text)
480
+ return {
481
+ "status": "success",
482
+ "task_id": generated_task_id,
483
+ "transcript": text,
484
+ "transcript_path": transcript_path,
485
+ "summary": summary,
486
+ "named_entities": entities,
487
+ "risk_scores": risk_scores,
488
+ "detailed_risk": detailed_risk,
489
+ "clauses_detected": clauses
490
+ }
491
+ except Exception as e:
492
+ print(f"Error processing video: {str(e)}")
493
+ return {"status": "error", "message": str(e)}
494
+
495
+ @app.post("/analyze_legal_audio")
496
+ async def analyze_legal_audio(file: UploadFile = File(...)):
497
+ """Analyzes legal audio by transcribing and analyzing the transcript."""
498
+ try:
499
+ print(f"Processing audio file: {file.filename}")
500
+ content = await file.read()
501
+ with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(file.filename)[1]) as temp_file:
502
+ temp_file.write(content)
503
+ temp_file_path = temp_file.name
504
+ print(f"Temporary file saved at: {temp_file_path}")
505
+ text = process_audio_to_text(temp_file_path)
506
+ if os.path.exists(temp_file_path):
507
+ os.remove(temp_file_path)
508
+ if not text:
509
+ return {"status": "error", "message": "No speech could be transcribed from the audio."}
510
+ transcript_path = os.path.join("static", f"transcript_{int(time.time())}.txt")
511
+ with open(transcript_path, "w") as f:
512
+ f.write(text)
513
+ summary_text = text[:4096] if len(text) > 4096 else text
514
+ summary = summarizer(summary_text, max_length=200, min_length=50, do_sample=False)[0]['summary_text'] if len(text) > 100 else "Transcript too short for meaningful summarization."
515
+ print("Extracting named entities from transcript...")
516
+ entities = extract_named_entities(text)
517
+ print("Analyzing risk from transcript...")
518
+ risk_scores = analyze_risk(text)
519
+ detailed_risk = get_detailed_risk_info(text)
520
+ print("Analyzing legal clauses from transcript...")
521
+ clauses = analyze_contract_clauses(text)
522
+ generated_task_id = str(uuid.uuid4())
523
+ store_document_context(generated_task_id, text)
524
+ return {
525
+ "status": "success",
526
+ "task_id": generated_task_id,
527
+ "transcript": text,
528
+ "transcript_path": transcript_path,
529
+ "summary": summary,
530
+ "named_entities": entities,
531
+ "risk_scores": risk_scores,
532
+ "detailed_risk": detailed_risk,
533
+ "clauses_detected": clauses
534
+ }
535
+ except Exception as e:
536
+ print(f"Error processing audio: {str(e)}")
537
+ return {"status": "error", "message": str(e)}
538
+
539
+ @app.get("/transcript/{transcript_id}")
540
+ async def get_transcript(transcript_id: str):
541
+ """Retrieves a previously generated transcript."""
542
+ transcript_path = os.path.join("static", f"transcript_{transcript_id}.txt")
543
+ if os.path.exists(transcript_path):
544
+ return FileResponse(transcript_path)
545
+ else:
546
+ raise HTTPException(status_code=404, detail="Transcript not found")
547
+
548
+ @app.post("/legal_chatbot")
549
+ async def legal_chatbot_api(query: str = Form(...), task_id: str = Form(...)):
550
+ """Handles legal Q&A using chat history and document context."""
551
+ document_context = load_document_context(task_id)
552
+ if not document_context:
553
+ return {"response": "⚠️ No relevant document found for this task ID."}
554
+ response = legal_chatbot(query, document_context)
555
+ return {"response": response, "chat_history": chat_history[-5:]}
556
+
557
+ @app.get("/health")
558
+ async def health_check():
559
+ return {
560
+ "status": "ok",
561
+ "models_loaded": True,
562
+ "device": device,
563
+ "gpu_available": torch.cuda.is_available(),
564
+ "timestamp": time.time()
565
+ }
566
+
567
+ def setup_ngrok():
568
+ """Sets up ngrok tunnel for Google Colab."""
569
+ try:
570
+ auth_token = os.environ.get("NGROK_AUTH_TOKEN")
571
+ if auth_token:
572
+ ngrok.set_auth_token(auth_token)
573
+ ngrok.kill()
574
+ time.sleep(1)
575
+ ngrok_tunnel = ngrok.connect(8500, "http")
576
+ public_url = ngrok_tunnel.public_url
577
+ print(f"✅ Ngrok Public URL: {public_url}")
578
+ def keep_alive():
579
+ while True:
580
+ time.sleep(60)
581
+ try:
582
+ tunnels = ngrok.get_tunnels()
583
+ if not tunnels:
584
+ print("⚠️ Ngrok tunnel closed. Reconnecting...")
585
+ ngrok_tunnel = ngrok.connect(8500, "http")
586
+ print(f"✅ Reconnected. New URL: {ngrok_tunnel.public_url}")
587
+ except Exception as e:
588
+ print(f"⚠️ Ngrok error: {e}")
589
+ Thread(target=keep_alive, daemon=True).start()
590
+ return public_url
591
+ except Exception as e:
592
+ print(f"⚠️ Ngrok setup error: {e}")
593
+ return None
594
+
595
+ @app.get("/download_risk_chart")
596
+ async def download_risk_chart():
597
+ """Generate and return a risk assessment chart as an image file."""
598
+ try:
599
+ os.makedirs("static", exist_ok=True)
600
+ risk_scores = {
601
+ "Liability": 11,
602
+ "Termination": 12,
603
+ "Indemnification": 10,
604
+ "Payment Risk": 41,
605
+ "Insurance": 71
606
+ }
607
+ plt.figure(figsize=(8, 5))
608
+ plt.bar(risk_scores.keys(), risk_scores.values(), color='red')
609
+ plt.xlabel("Risk Categories")
610
+ plt.ylabel("Risk Score")
611
+ plt.title("Legal Risk Assessment")
612
+ plt.xticks(rotation=30)
613
+ risk_chart_path = "static/risk_chart.png"
614
+ plt.savefig(risk_chart_path)
615
+ plt.close()
616
+ return FileResponse(risk_chart_path, media_type="image/png", filename="risk_chart.png")
617
+ except Exception as e:
618
+ raise HTTPException(status_code=500, detail=f"Error generating risk chart: {str(e)}")
619
+
620
+ @app.get("/download_risk_pie_chart")
621
+ async def download_risk_pie_chart():
622
+ try:
623
+ risk_scores = {
624
+ "Liability": 11,
625
+ "Termination": 12,
626
+ "Indemnification": 10,
627
+ "Payment Risk": 41,
628
+ "Insurance": 71
629
+ }
630
+ plt.figure(figsize=(6, 6))
631
+ plt.pie(risk_scores.values(), labels=risk_scores.keys(), autopct='%1.1f%%', startangle=90)
632
+ plt.title("Legal Risk Distribution")
633
+ pie_chart_path = "static/risk_pie_chart.png"
634
+ plt.savefig(pie_chart_path)
635
+ plt.close()
636
+ return FileResponse(pie_chart_path, media_type="image/png", filename="risk_pie_chart.png")
637
+ except Exception as e:
638
+ raise HTTPException(status_code=500, detail=f"Error generating pie chart: {str(e)}")
639
+
640
+ @app.get("/download_risk_radar_chart")
641
+ async def download_risk_radar_chart():
642
+ try:
643
+ risk_scores = {
644
+ "Liability": 11,
645
+ "Termination": 12,
646
+ "Indemnification": 10,
647
+ "Payment Risk": 41,
648
+ "Insurance": 71
649
+ }
650
+ categories = list(risk_scores.keys())
651
+ values = list(risk_scores.values())
652
+ categories += categories[:1]
653
+ values += values[:1]
654
+ angles = np.linspace(0, 2 * np.pi, len(categories), endpoint=False).tolist()
655
+ angles += angles[:1]
656
+ fig, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
657
+ ax.plot(angles, values, 'o-', linewidth=2)
658
+ ax.fill(angles, values, alpha=0.25)
659
+ ax.set_thetagrids(np.degrees(angles[:-1]), categories)
660
+ ax.set_title("Legal Risk Radar Chart", y=1.1)
661
+ radar_chart_path = "static/risk_radar_chart.png"
662
+ plt.savefig(radar_chart_path)
663
+ plt.close()
664
+ return FileResponse(radar_chart_path, media_type="image/png", filename="risk_radar_chart.png")
665
+ except Exception as e:
666
+ raise HTTPException(status_code=500, detail=f"Error generating radar chart: {str(e)}")
667
+
668
+ @app.get("/download_risk_trend_chart")
669
+ async def download_risk_trend_chart():
670
+ try:
671
+ dates = ["2025-01-01", "2025-02-01", "2025-03-01", "2025-04-01"]
672
+ risk_history = {
673
+ "Liability": [10, 12, 11, 13],
674
+ "Termination": [12, 15, 14, 13],
675
+ "Indemnification": [9, 10, 11, 10],
676
+ "Payment Risk": [40, 42, 41, 43],
677
+ "Insurance": [70, 69, 71, 72]
678
+ }
679
+ plt.figure(figsize=(10, 6))
680
+ for category, scores in risk_history.items():
681
+ plt.plot(dates, scores, marker='o', label=category)
682
+ plt.xlabel("Date")
683
+ plt.ylabel("Risk Score")
684
+ plt.title("Historical Legal Risk Trends")
685
+ plt.xticks(rotation=45)
686
+ plt.legend()
687
+ trend_chart_path = "static/risk_trend_chart.png"
688
+ plt.savefig(trend_chart_path, bbox_inches="tight")
689
+ plt.close()
690
+ return FileResponse(trend_chart_path, media_type="image/png", filename="risk_trend_chart.png")
691
+ except Exception as e:
692
+ raise HTTPException(status_code=500, detail=f"Error generating trend chart: {str(e)}")
693
+
694
+ import pandas as pd
695
+ import plotly.express as px
696
+ from fastapi.responses import HTMLResponse
697
+
698
+ @app.get("/interactive_risk_chart", response_class=HTMLResponse)
699
+ async def interactive_risk_chart():
700
+ try:
701
+ risk_scores = {
702
+ "Liability": 11,
703
+ "Termination": 12,
704
+ "Indemnification": 10,
705
+ "Payment Risk": 41,
706
+ "Insurance": 71
707
+ }
708
+ df = pd.DataFrame({
709
+ "Risk Category": list(risk_scores.keys()),
710
+ "Risk Score": list(risk_scores.values())
711
+ })
712
+ fig = px.bar(df, x="Risk Category", y="Risk Score", title="Interactive Legal Risk Assessment")
713
+ return fig.to_html()
714
+ except Exception as e:
715
+ raise HTTPException(status_code=500, detail=f"Error generating interactive chart: {str(e)}")
716
+
717
+ def run():
718
+ """Starts the FastAPI server."""
719
+ print("Starting FastAPI server...")
720
+ uvicorn.run(app, host="0.0.0.0", port=8500, timeout_keep_alive=600)
721
+
722
+ if __name__ == "__main__":
723
+ public_url = setup_ngrok()
724
+ if public_url:
725
+ print(f"\n✅ Your API is publicly available at: {public_url}/docs\n")
726
+ else:
727
+ print("\n⚠️ Ngrok setup failed. API will only be available locally.\n")
728
+ run()