File size: 3,305 Bytes
370f105
 
 
 
 
 
 
 
 
 
 
 
ee5e4e0
03bce1c
370f105
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import gradio as gr
import pandas as pd
import os

from langchain_community.document_loaders import PyPDFLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_community.vectorstores import Chroma
from langchain.chains import RetrievalQA

from transformers import pipeline
from langchain_community.llms import HuggingFacePipeline
print("Hi")
print('try')
# =========================
# LOAD PDF GUIDELINES
# =========================

PDF_PATH = "Lemonade_Guidlines.pdf"

loader = PyPDFLoader(PDF_PATH)
docs = loader.load()

# =========================
# CHUNKING
# =========================

text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=100
)

chunks = text_splitter.split_documents(docs)

# =========================
# EMBEDDINGS
# =========================

embedding_model = HuggingFaceEmbeddings(
    model_name="sentence-transformers/all-MiniLM-L6-v2"
)

# =========================
# VECTOR DB (FASTER INIT)
# =========================

vectorstore = Chroma.from_documents(
    documents=chunks,
    embedding=embedding_model
)

retriever = vectorstore.as_retriever(search_kwargs={"k": 2})

# =========================
# LIGHTWEIGHT LLM (IMPORTANT FIX)
# =========================

pipe = pipeline(
    "text-generation",
    model="TinyLlama/TinyLlama-1.1B-Chat-v1.0",  # 🔥 small + fast
    max_new_tokens=120,
    temperature=0.2
)

llm = HuggingFacePipeline(pipeline=pipe)

# =========================
# QA CHAIN
# =========================

qa_chain = RetrievalQA.from_chain_type(
    llm=llm,
    retriever=retriever
)

# =========================
# VIOLATION CHECK
# =========================

def check_violation(row):

    prompt = f"""
You are a strict legal billing auditor.

Check if the below entry violates guidelines.

Narrative: {row['Narrative (Full Text)']}
Task Code: {row['Task Code']}
Timekeeper: {row['Timekeeper Name']}
Hours: {row['Units (Hrs / Qty)']}

Respond strictly:

Violation: Yes or No
Reason: <one line>
"""

    try:
        result = qa_chain.invoke({"query": prompt})
        return result["result"]
    except Exception as e:
        return f"Error: {str(e)}"

# =========================
# FILE PROCESSING
# =========================

def process_file(file):

    df = pd.read_excel(file, engine="openpyxl")

    # Duplicate detection
    df["Duplicate Count"] = df.duplicated(
        subset=["Narrative (Full Text)", "Units (Hrs / Qty)", "Rate ($/Unit)"],
        keep=False
    ).astype(int)

    results = []

    for i, row in df.iterrows():

        # 🔥 LIMIT rows to avoid timeout (VERY IMPORTANT)
        if i > 30:
            results.append("Skipped (limit reached)")
            continue

        res = check_violation(row)
        results.append(res)

    df["Violation Analysis"] = results

    output_path = "audited_output.xlsx"
    df.to_excel(output_path, index=False)

    return output_path

# =========================
# UI
# =========================

interface = gr.Interface(
    fn=process_file,
    inputs=gr.File(label="Upload Billing Excel"),
    outputs=gr.File(label="Download Result"),
    title="Legal Billing Auditor",
    description="AI-powered billing audit using RAG"
)

interface.launch()