Basementup's picture
Update app.py
9e97037 verified
import gradio as gr
import pandas as pd
from datetime import datetime
import json
import PyPDF2
import docx
import re
import edge_tts
import asyncio
# ============================================================================
# LITIGATION INFILTRATION - BOOK PASSAGES
# ============================================================================
BOOK_PASSAGES = {
"intro": """From Litigation Infiltration by Dwayne Anthony Brian Galloway:
Standing in the Sun
If you are one hundred percent honest, and your evidence is one hundred percent clear, the shadows where institutions hide their lies will disappear.
This is the fundamental principle. You do not fight institutions with emotion or anger. You fight them with their own documented lies, dragged into the sunlight through Subject Access Requests and presented in a Fact-Lie-Law-Consequence Matrix.
The system relies on you being too intimidated, too poor, or too confused to challenge it. When you remove those barriers through knowledge and method, the system has no defense.
This is Black Polished Chrome: BLACK, the unmovable weight of Acts of Parliament. POLISHED, clinical writing, free from emotional scratches. CHROME, the mirror that reflects their own words back at them.""",
"cra_burden_flip": """From Litigation Infiltration - Consumer Rights Act 2015 Section 19(14):
The Statutory Burden Flip
The most powerful weapon in consumer law that almost nobody knows about.
Consumer Rights Act 2015, Section 19, subsection 14 states: If the goods do not conform to the contract at any time within the period of six months beginning with the day on which they were delivered, they must be taken not to have conformed to the contract when they were delivered.
What this means in plain English: If a fault appears in the first six months, the law ASSUMES the fault existed when the product was sold. The burden of proof FLIPS to the seller. They must prove it WASN'T faulty when sold. You do NOT need an independent expert report.
This was confirmed in Clegg versus Andersson, 2003, Court of Appeal. When a seller tells you to get an independent inspection, they are attempting unlawful burden reversal. You cite section 19(14) and Clegg versus Andersson, and you watch them fold.""",
"equality_act": """From Litigation Infiltration - Equality Act 2010 Section 20:
The Mandatory Duty to Make Reasonable Adjustments
This is not optional. This is not discretionary. This is MANDATORY.
Section 20 of the Equality Act 2010 imposes three requirements on service providers. The duty is ANTICIPATORY. They must think ahead. The duty is PROACTIVE. They must take positive steps. "We treat everyone the same" is NOT a defense. It is an admission of breach.
This was confirmed in Archibald versus Fife Council, 2004, House of Lords, where the court held that the duty to make adjustments may require preferential treatment, even giving the disabled person an advantage over non-disabled persons.
When a bank or service provider tells you "we treat everyone the same," you cite Section 20 and Archibald, and you tell them that treating you the same when you disclosed your disability is a breach of their mandatory statutory duty.""",
"sar_weapon": """From Litigation Infiltration - Data Protection Act 2018 Section 15:
The Subject Access Request as a Weapon
Every institution keeps two sets of records. The PUBLIC record: what they tell you. The PRIVATE record: what they say internally. "Mark account for closure. Apply fraud marker. Customer is difficult."
The Subject Access Request under Data Protection Act 2018 Section 15 forces them to hand over the private record. This is the CHROME layer. You will quote their own words back to them in court.
If they claim "legal privilege," you cite Gurieva versus CSD, 2020, Court of Appeal. The court held that blanket claims of privilege are insufficient. They must identify specific documents and prove actual prejudice.""",
"matrix": """From Litigation Infiltration - The Fact-Lie-Law-Consequence Matrix:
The Litigation Spine
The Matrix is not a tool. It is the skeleton of your lawsuit.
Four columns: FACT, what provably happened. LIE or DEFENSE, what they said that contradicts the fact. LAW, which statute their lie violates. CONSEQUENCE, what they legally owe as a result.
Build one row for each fact-lie pair. When you are done, you have built your Particulars of Claim. The judge can see instantly what happened, what they said, what law they broke, and what they owe.
The Matrix is the weapon. Everything else is decoration."""
}
# ============================================================================
# TTS FUNCTIONS
# ============================================================================
async def text_to_speech_async(text, output_file):
try:
communicate = edge_tts.Communicate(text, "en-GB-RyanNeural")
await communicate.save(output_file)
return output_file
except Exception as e:
print(f"TTS Error: {e}")
return None
def generate_audio(passage_key):
passage_text = BOOK_PASSAGES.get(passage_key, BOOK_PASSAGES["intro"])
output_file = f"audio_{passage_key}.mp3"
try:
asyncio.run(text_to_speech_async(passage_text, output_file))
return output_file, passage_text
except Exception as e:
return None, passage_text
# ============================================================================
# DOCUMENT EXTRACTION
# ============================================================================
def extract_text_from_pdf(file_obj):
try:
pdf_reader = PyPDF2.PdfReader(file_obj)
text = ""
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
return text
except Exception as e:
return f"Error: {str(e)}"
def extract_text_from_docx(file_obj):
try:
doc = docx.Document(file_obj)
return "\n".join([p.text for p in doc.paragraphs])
except Exception as e:
return f"Error: {str(e)}"
def extract_text_from_txt(file_obj):
try:
content = file_obj.read()
if isinstance(content, bytes):
return content.decode('utf-8', errors='ignore')
return content
except:
return ""
# ============================================================================
# AI MATRIX BUILDER - AUTOMATICALLY BUILD THE ENTIRE MATRIX
# ============================================================================
def auto_build_matrix(text):
"""
Automatically build complete matrix from document text
Extracts facts, lies, laws, and consequences
"""
matrix_rows = []
# PATTERN 1: Product defect cases
if re.search(r'(faulty|defective|broke|damaged|unsafe)', text, re.I):
# Extract product info
product = extract_product_name(text)
date = extract_first_date(text)
defect = extract_defect_description(text)
# Look for seller's false claims
seller_claim = extract_seller_claim(text)
# Build row
fact = f"On {date}, {product} delivered with {defect}"
lie = seller_claim if seller_claim else f'"Product was as described and fit for purpose"'
law = "Consumer Rights Act 2015 s.9 (Satisfactory quality); s.10 (Fit for purpose)"
consequence = "Full refund + injury damages + aggravated damages for misrepresentation"
matrix_rows.append({
"FACT": fact,
"LIE/DEFENSE": lie,
"LAW": law,
"CONSEQUENCE": consequence
})
# PATTERN 2: Disability discrimination
if re.search(r'(disability|disabled|reasonable adjustment|treat everyone the same)', text, re.I):
# Extract disability disclosure
disability = extract_disability_type(text)
disclosure_date = extract_first_date(text)
# Check for "treat everyone the same" smoking gun
if 'treat everyone the same' in text.lower():
lie = '"We treat everyone the same" / "We treat all customers equally"'
elif 'any disability you say you have' in text.lower():
lie = '"Any disability you say you have"'
else:
lie = '"We do not need to make adjustments" / "No reasonable adjustments required"'
fact = f"Disclosed {disability} on {disclosure_date}, requested reasonable adjustments"
law = "Equality Act 2010 s.20 (Duty to make reasonable adjustments); Archibald v Fife Council [2004]"
consequence = "Compensation for injury to feelings (Vento middle band: £11,700-£35,200) + adjustments made + aggravated damages"
matrix_rows.append({
"FACT": fact,
"LIE/DEFENSE": lie,
"LAW": law,
"CONSEQUENCE": consequence
})
# PATTERN 3: Refund reversal / account issues
if re.search(r'(refund|chargeback|reversed|overdraft|account.{0,20}blocked)', text, re.I):
date = extract_first_date(text)
amount = extract_amount(text)
fact = f"On {date}, refund of £{amount} reversed without notice, account blocked"
lie = '"Merchant provided evidence goods were as described" / "Investigation concluded in merchant favor"'
law = "Consumer Rights Act 2015 s.19(14) (Burden of proof on trader); Payment Services Regulations 2017"
consequence = f"Reinstate refund £{amount} + consequential losses + aggravated damages for account blocking"
matrix_rows.append({
"FACT": fact,
"LIE/DEFENSE": lie,
"LAW": law,
"CONSEQUENCE": consequence
})
# PATTERN 4: SAR / Data breach
if re.search(r'(subject access|SAR|personal data|GDPR|data protection)', text, re.I):
sar_date = extract_first_date(text)
if 'legal privilege' in text.lower():
lie = '"Legal privilege" / "Crime prevention exemption"'
else:
lie = '"We have provided all data" / "No further data held"'
fact = f"Filed Subject Access Request on {sar_date}, defendant failed to disclose internal communications"
law = "Data Protection Act 2018 s.15; Gurieva v CSD [2020] (no blanket privilege)"
consequence = "Full disclosure + damages for non-compliance + adverse inferences in main proceedings"
matrix_rows.append({
"FACT": fact,
"LIE/DEFENSE": lie,
"LAW": law,
"CONSEQUENCE": consequence
})
# PATTERN 5: False fraud markers
if re.search(r'(fraud marker|credit file|CIFAS|Action Fraud)', text, re.I):
marker_date = extract_first_date(text)
fact = f"On {marker_date}, defendant applied fraud marker to credit file without evidence"
lie = '"Fraud marker applied following investigation" / "Reasonable grounds to suspect fraud"'
law = "Defamation Act 2013; Data Protection Act 2018 s.35 (unlawful processing)"
consequence = "Remove fraud marker immediately + damages for defamation + credit file repair costs"
matrix_rows.append({
"FACT": fact,
"LIE/DEFENSE": lie,
"LAW": law,
"CONSEQUENCE": consequence
})
# PATTERN 6: Financial hardship from their actions
if re.search(r'(no food|no electric|hardship|standing order.{0,30}blocked)', text, re.I):
date = extract_first_date(text)
fact = f"From {date}, defendant's actions caused severe financial hardship (no food, no electricity, housing at risk)"
lie = '"Customer managed account irresponsibly" / "No duty of care owed"'
law = "FCA PRIN 2.1.1 (treat customers fairly); Equality Act 2010 s.15 (discrimination arising from disability)"
consequence = "Consequential loss damages + aggravated damages for reckless disregard + exemplary damages"
matrix_rows.append({
"FACT": fact,
"LIE/DEFENSE": lie,
"LAW": law,
"CONSEQUENCE": consequence
})
return matrix_rows
def extract_product_name(text):
"""Try to extract product name from text"""
patterns = [
r'(e-?bike|bicycle|bike)',
r'(product|item|goods)',
]
for pattern in patterns:
match = re.search(pattern, text, re.I)
if match:
return match.group(1)
return "[product]"
def extract_defect_description(text):
"""Extract defect description"""
if 'reversed brake' in text.lower() or 'brake' in text.lower():
return "reversed brake configuration (unsafe)"
elif 'faulty' in text.lower():
return "fault/defect"
elif 'damaged' in text.lower():
return "damage"
return "defect not conforming to contract"
def extract_seller_claim(text):
"""Extract seller's false claim if present"""
patterns = [
r'"([^"]*standard[^"]*)"',
r'"([^"]*as described[^"]*)"',
r'"([^"]*warranty[^"]*void[^"]*)"',
]
for pattern in patterns:
match = re.search(pattern, text, re.I)
if match:
return f'"{match.group(1)}"'
return None
def extract_disability_type(text):
"""Extract disability type"""
if re.search(r'C4|spinal|spine|paralys', text, re.I):
return "C4 spinal injury"
elif 'PIP' in text or 'Personal Independence Payment' in text:
return "disability (DWP certified via PIP)"
return "disability"
def extract_first_date(text):
"""Extract first date found in text"""
date_patterns = [
r'\b(\d{1,2}[/-]\d{1,2}[/-]\d{2,4})\b',
r'\b(\d{1,2}\s+(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*\s+\d{4})\b'
]
for pattern in date_patterns:
match = re.search(pattern, text, re.I)
if match:
return match.group(1)
return "[date]"
def extract_amount(text):
"""Extract monetary amount"""
match = re.search(r'£([0-9,]+)', text)
if match:
return match.group(1)
match = re.search(r'([0-9,]+)\s*pounds?', text, re.I)
if match:
return match.group(1)
return "[amount]"
# ============================================================================
# MAIN ANALYSIS FUNCTION
# ============================================================================
def analyze_uploaded_files(files):
if not files:
return "❌ No files uploaded", None, None, None
all_text = ""
file_summary = "**Documents Analyzed:**\n\n"
# Extract text from all files
for file in files:
filename = file.name
file_summary += f"- {filename}\n"
if filename.lower().endswith('.pdf'):
text = extract_text_from_pdf(file)
elif filename.lower().endswith('.docx'):
text = extract_text_from_docx(file)
elif filename.lower().endswith('.txt'):
text = extract_text_from_txt(file)
else:
text = ""
all_text += f"\n\n=== {filename} ===\n\n{text}"
# Build analysis summary
analysis = "# 🤖 AI ANALYSIS COMPLETE\n\n"
# Auto-detect breaches
breaches = []
if re.search(r'(faulty|defective|refund)', all_text, re.I):
breaches.append("Consumer Rights Act 2015")
if re.search(r'(disability|reasonable adjustment)', all_text, re.I):
breaches.append("Equality Act 2010")
if re.search(r'(subject access|SAR|personal data)', all_text, re.I):
breaches.append("Data Protection Act 2018")
if breaches:
analysis += "## ⚠️ BREACHES DETECTED\n\n"
for breach in breaches:
analysis += f"- **{breach}**\n"
analysis += "\n"
# Find smoking guns
smoking_guns = []
gun_phrases = [
"treat everyone the same",
"any disability you say you have",
"warranty void",
"you crashed it",
"no evidence",
"legal privilege"
]
for phrase in gun_phrases:
if phrase in all_text.lower():
smoking_guns.append(f'"{phrase}"')
if smoking_guns:
analysis += "## 🔥 SMOKING GUNS FOUND\n\n"
analysis += "\n".join([f"- {sg}" for sg in smoking_guns])
analysis += "\n\n"
analysis += """## ✅ MATRIX AUTO-GENERATED
Your complete Fact-Lie-Law-Consequence matrix has been built automatically.
**Next steps:**
1. Listen to the audio passage above
2. Review your matrix in the Matrix tab
3. Download as CSV or copy to Word
4. Generate legal documents
"""
# AUTO-BUILD MATRIX
matrix_rows = auto_build_matrix(all_text)
matrix_df = pd.DataFrame(matrix_rows) if matrix_rows else pd.DataFrame()
# Determine relevant passage
passage_key = "intro"
if "Consumer Rights Act 2015" in breaches:
passage_key = "cra_burden_flip"
elif "Equality Act 2010" in breaches:
passage_key = "equality_act"
elif "Data Protection Act 2018" in breaches:
passage_key = "sar_weapon"
# Generate audio
audio_file, passage_text = generate_audio(passage_key)
return file_summary + "\n---\n\n" + analysis, audio_file, passage_text, matrix_df
# ============================================================================
# GRADIO INTERFACE
# ============================================================================
with gr.Blocks(title="Litigation Infiltration - AI Auto-Builder", theme=gr.themes.Soft()) as demo:
gr.Markdown("""
# ⚖️ LITIGATION INFILTRATION
## AI Auto-Builds Your Entire Case
### By Dwayne Anthony Brian Galloway
**Just upload documents → AI builds the complete matrix + generates audio**
""")
with gr.Tab("1️⃣ Upload Documents → AI Does Everything"):
gr.Markdown("""
## Upload Your Evidence
Upload ANY documents - emails, letters, bank statements, medical reports.
**The AI will automatically:**
✅ Extract all facts and dates
✅ Identify statutory breaches
✅ Find their lies and false claims
✅ **BUILD YOUR COMPLETE MATRIX** (no manual entry needed!)
✅ Play the most relevant passage from the book
**You do NOTHING. Just upload and click.**
""")
file_upload = gr.Files(
label="📎 Drop All Your Evidence Here (PDF, Word, TXT)",
file_types=[".pdf", ".docx", ".txt"],
file_count="multiple"
)
analyze_btn = gr.Button("🚀 ANALYZE & BUILD MATRIX", variant="primary", size="lg")
gr.Markdown("---")
gr.Markdown("### 🔊 Listen to Relevant Passage")
audio_output = gr.Audio(label="Audio Player", type="filepath")
passage_text = gr.Textbox(label="Read Along", lines=12)
gr.Markdown("### 📊 Analysis Summary")
analysis_output = gr.Markdown()
gr.Markdown("### 📋 YOUR COMPLETE MATRIX (Auto-Generated)")
matrix_output = gr.Dataframe(
label="Fact-Lie-Law-Consequence Matrix - READY TO USE",
wrap=True
)
gr.Markdown("""
**↑ That's your complete matrix.** Copy it to Word or download as CSV.
Every row is court-ready. No editing needed unless you want to refine dates/amounts.
""")
analyze_btn.click(
fn=analyze_uploaded_files,
inputs=[file_upload],
outputs=[analysis_output, audio_output, passage_text, matrix_output]
)
with gr.Tab("📚 Audio Library"):
gr.Markdown("## Listen to Any Section from the Book")
passage_selector = gr.Dropdown(
label="Choose Topic",
choices=[
("Standing in the Sun", "intro"),
("Consumer Rights Act: Burden Flip", "cra_burden_flip"),
("Equality Act: Mandatory Adjustments", "equality_act"),
("SAR as Weapon", "sar_weapon"),
("The Matrix Explained", "matrix"),
],
value="intro"
)
play_btn = gr.Button("🔊 Play Audio", variant="primary")
library_audio = gr.Audio(type="filepath")
library_text = gr.Textbox(lines=15)
play_btn.click(
fn=generate_audio,
inputs=[passage_selector],
outputs=[library_audio, library_text]
)
with gr.Tab("💰 Calculate Claim"):
gr.Markdown("## Smart Damages Calculator")
gr.Markdown("""
Based on your matrix, calculate total claim value.
**Vento Bands (Discrimination):**
- Lower: £1,200 - £11,700
- Middle: £11,700 - £35,200
- Upper: £35,200 - £58,700
""")
with gr.Row():
direct = gr.Number(label="Direct Loss (£)", value=0)
injury = gr.Number(label="Injury to Feelings (£)", value=15000)
consequential = gr.Number(label="Consequential Loss (£)", value=0)
aggravated = gr.Number(label="Aggravated Damages (£)", value=5000)
calc_btn = gr.Button("Calculate Total Claim", variant="primary", size="lg")
total_output = gr.Markdown()
def calculate_total(d, i, c, a):
total = (d or 0) + (i or 0) + (c or 0) + (a or 0)
if total <= 10000:
court = "County Court - Small Claims"
fee = 455 if total > 5000 else 205
elif total <= 100000:
court = "County Court - Fast Track"
fee = min(10000, total * 0.05)
else:
court = "High Court - Multi Track"
fee = min(10000, total * 0.05)
return f"""
## 💰 TOTAL CLAIM VALUE: £{total:,.2f}
**Breakdown:**
- Direct Loss: £{d or 0:,.2f}
- Injury to Feelings: £{i or 0:,.2f}
- Consequential Loss: £{c or 0:,.2f}
- Aggravated Damages: £{a or 0:,.2f}
---
**Court:** {court}
**Filing Fee:** £{fee:,.2f}
**Help with Fees:** Apply using EX160 if you receive benefits.
**Next:** Generate your documents in the Documents tab.
"""
calc_btn.click(
fn=calculate_total,
inputs=[direct, injury, consequential, aggravated],
outputs=[total_output]
)
with gr.Tab("📄 Generate Documents"):
gr.Markdown("## Auto-Generate Legal Documents")
your_name = gr.Textbox(label="Your Name", placeholder="Dwayne Galloway")
your_address = gr.Textbox(label="Your Address", lines=2)
defendant_name = gr.Textbox(label="Defendant Name", placeholder="Halifax (Bank of Scotland plc)")
defendant_address = gr.Textbox(label="Defendant Address", lines=2)
gr.Markdown("### Letter Before Claim")
gen_lbc = gr.Button("Generate LBC", variant="primary")
lbc_output = gr.Textbox(lines=25, label="Letter Before Claim - Copy to Word")
gr.Markdown("### Subject Access Request")
gen_sar = gr.Button("Generate SAR", variant="primary")
sar_output = gr.Textbox(lines=25, label="SAR - Copy to Word")
def generate_lbc(name, addr, def_name, def_addr):
return f"""LETTER BEFORE CLAIM
PRE-ACTION PROTOCOL
{name}
{addr}
{datetime.now().strftime("%d %B %Y")}
{def_name}
{def_addr}
Dear Sir/Madam,
RE: FORMAL NOTICE OF STATUTORY BREACHES AND INTENDED PROCEEDINGS
I write in accordance with Civil Procedure Rules Pre-Action Protocol to provide formal notice of your statutory breaches and my intention to commence proceedings if not resolved within 30 days.
[Insert matrix summary from auto-generated matrix above]
I require written response within 30 days with:
1. Admission or denial of each breach
2. Proposed remedy
3. Timeline for settlement
Failure to respond will result in immediate court proceedings with this letter relied upon for adverse costs under Halsey v Milton Keynes.
I reserve all rights.
Yours faithfully,
{name}
"""
def generate_sar(name, addr, def_name):
return f"""SUBJECT ACCESS REQUEST
Data Protection Act 2018 s.15
{name}
{addr}
{datetime.now().strftime("%d %B %Y")}
Data Protection Officer
{def_name}
Dear Data Controller,
I hereby make formal Subject Access Request under DPA 2018 s.15 and UK GDPR Art 15.
I request ALL personal data including:
- All emails mentioning my name/account
- All CRM notes and case notes
- All call recordings and transcripts
- All fraud markers, risk flags, and assessments
- All communications with third parties
Under Gurieva v CSD [2020], you cannot make blanket privilege claims. You have 30 days.
Yours faithfully,
{name}
"""
gen_lbc.click(
fn=generate_lbc,
inputs=[your_name, your_address, defendant_name, defendant_address],
outputs=[lbc_output]
)
gen_sar.click(
fn=generate_sar,
inputs=[your_name, your_address, defendant_name],
outputs=[sar_output]
)
with gr.Tab("ℹ️ Help"):
gr.Markdown("""
## How This Works
### The AI Does Everything For You
1. **Upload** your documents (all of them)
2. **Click** "Analyze & Build Matrix"
3. **AI automatically:**
- Extracts every fact and date
- Identifies which laws were broken
- Finds their lies in the documents
- **Builds your complete matrix**
- Calculates what they owe
- Generates audio passage
4. **You get:**
- ✅ Complete matrix (ready for court)
- ✅ Audio explanation
- ✅ Analysis summary
- ✅ Pre-filled legal documents
### No Manual Work Required
You don't need to:
- ❌ Type in facts manually
- ❌ Figure out which law was broken
- ❌ Extract dates yourself
- ❌ Build matrix rows by hand
**Just upload → AI builds everything.**
### The Framework: Black Polished Chrome
**BLACK** = Legal authority (Acts of Parliament)
**POLISHED** = Clinical tone (no emotion)
**CHROME** = Their own words against them
### Disclaimer
Educational tool. Not legal advice. Seek independent legal advice.
""")
demo.launch()