karthickg12 commited on
Commit
35872c0
Β·
verified Β·
1 Parent(s): c0d20ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -54
app.py CHANGED
@@ -1,36 +1,50 @@
1
-
2
  import pdfplumber
3
  import gradio as gr
4
  import torch
5
 
6
- from transformers import pipeline
 
 
 
7
 
8
  MODEL_NAME = "Qwen/Qwen2.5-3B-Instruct"
9
 
10
  print("Loading model...")
11
 
12
- pipe = pipeline(
13
- "text-generation",
14
- model=MODEL_NAME,
15
- torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
16
- device_map="auto"
17
  )
18
 
19
- print("Model loaded.")
 
 
 
 
 
20
 
 
21
 
22
 
23
  def extract_text(pdf_file):
24
  text = ""
25
 
26
- with pdfplumber.open(pdf_file.name) as pdf:
27
- for page in pdf.pages:
28
- page_text = page.extract_text()
29
- if page_text:
30
- text += page_text + "\n"
 
 
 
 
 
 
 
 
31
 
32
- return text[:12000]
33
- print(text)
34
 
35
 
36
  def build_prompt(policy_text):
@@ -38,13 +52,25 @@ def build_prompt(policy_text):
38
  return f"""
39
  You are a senior insurance consultant.
40
 
41
- Analyze the insurance policy and produce a customer-friendly report.
42
 
43
- Return your answer in markdown.
44
 
45
  # Executive Summary
46
 
47
- Summarize the policy in simple English.
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
  # What Is Covered
50
 
@@ -58,40 +84,29 @@ Provide bullet points.
58
 
59
  Provide bullet points.
60
 
61
- # Claim Process
62
-
63
- Step-by-step instructions.
64
-
65
  # Coverage Gaps
66
 
67
- Identify situations where customers may incorrectly assume coverage.
68
 
69
- # Red Flags
70
 
71
- Anything customers commonly overlook.
72
 
73
- # Questions To Ask Your Insurer
74
 
75
  Provide 5 questions.
76
 
77
  # Explain Like I'm 15
78
 
79
- Explain the policy in simple language.
80
 
81
- Policy Text:
82
 
83
  {policy_text}
84
  """
85
 
86
 
87
- def analyze_policy(pdf_file):
88
-
89
- if pdf_file is None:
90
- return "Please upload a policy PDF."
91
-
92
- policy_text = extract_text(pdf_file)
93
-
94
- prompt = build_prompt(policy_text)
95
 
96
  messages = [
97
  {
@@ -104,19 +119,83 @@ def analyze_policy(pdf_file):
104
  }
105
  ]
106
 
107
- result = pipe(
108
  messages,
109
- max_new_tokens=1200,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  temperature=0.2,
111
- do_sample=True
 
 
 
 
 
 
 
 
112
  )
113
 
114
- return result[0]["generated_text"][-1]["content"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
 
116
 
117
  with gr.Blocks(
118
  title="Insurance Policy Decoder",
119
- theme=gr.themes.Soft()
 
120
  ) as demo:
121
 
122
  gr.Markdown(
@@ -125,42 +204,45 @@ with gr.Blocks(
125
 
126
  Understand your insurance policy in less than a minute.
127
 
128
- Upload a policy PDF to get:
129
 
130
- βœ… Simple Summary
131
 
132
  βœ… Coverage Details
133
 
134
- βœ… Major Exclusions
135
 
136
  βœ… Waiting Periods
137
 
138
- βœ… Claim Checklist
139
-
140
  βœ… Coverage Gaps
141
 
 
 
 
 
142
  βœ… Questions To Ask Your Insurer
143
  """
144
  )
145
 
146
- with gr.Row():
147
-
148
- pdf_input = gr.File(
149
- label="Upload Insurance Policy",
150
- file_types=[".pdf"]
151
- )
152
 
153
  analyze_btn = gr.Button(
154
  "Decode Policy",
155
  variant="primary"
156
  )
157
 
158
- output = gr.Markdown()
 
 
159
 
160
  analyze_btn.click(
161
  fn=analyze_policy,
162
  inputs=pdf_input,
163
- outputs=output
 
164
  )
165
 
166
  demo.launch()
 
 
1
  import pdfplumber
2
  import gradio as gr
3
  import torch
4
 
5
+ from transformers import (
6
+ AutoTokenizer,
7
+ AutoModelForCausalLM
8
+ )
9
 
10
  MODEL_NAME = "Qwen/Qwen2.5-3B-Instruct"
11
 
12
  print("Loading model...")
13
 
14
+ tokenizer = AutoTokenizer.from_pretrained(
15
+ MODEL_NAME,
16
+ trust_remote_code=True
 
 
17
  )
18
 
19
+ model = AutoModelForCausalLM.from_pretrained(
20
+ MODEL_NAME,
21
+ torch_dtype="auto",
22
+ device_map="auto",
23
+ trust_remote_code=True
24
+ )
25
 
26
+ print("Model loaded successfully.")
27
 
28
 
29
  def extract_text(pdf_file):
30
  text = ""
31
 
32
+ try:
33
+ with pdfplumber.open(pdf_file.name) as pdf:
34
+
35
+ for page in pdf.pages:
36
+ page_text = page.extract_text()
37
+
38
+ if page_text:
39
+ text += page_text + "\n"
40
+
41
+ except Exception as e:
42
+ return f"PDF Extraction Error: {str(e)}"
43
+
44
+ print(f"Extracted {len(text)} characters")
45
 
46
+ # Keep small for free-tier inference
47
+ return text[:3000]
48
 
49
 
50
  def build_prompt(policy_text):
 
52
  return f"""
53
  You are a senior insurance consultant.
54
 
55
+ Analyze the insurance policy and create a customer-friendly report.
56
 
57
+ Return markdown.
58
 
59
  # Executive Summary
60
 
61
+ Summarize the policy in plain English.
62
+
63
+ # Customer Risk Score
64
+
65
+ Rate 1-10 and explain why.
66
+
67
+ # Policy Complexity Score
68
+
69
+ Rate 1-10 and explain why.
70
+
71
+ # Claim Difficulty Score
72
+
73
+ Rate 1-10 and explain why.
74
 
75
  # What Is Covered
76
 
 
84
 
85
  Provide bullet points.
86
 
 
 
 
 
87
  # Coverage Gaps
88
 
89
+ Identify situations where customers may wrongly assume they are covered.
90
 
91
+ # Claim Checklist
92
 
93
+ Provide step-by-step instructions.
94
 
95
+ # Questions To Ask The Insurer
96
 
97
  Provide 5 questions.
98
 
99
  # Explain Like I'm 15
100
 
101
+ Explain the policy simply.
102
 
103
+ POLICY DOCUMENT:
104
 
105
  {policy_text}
106
  """
107
 
108
 
109
+ def generate_response(prompt):
 
 
 
 
 
 
 
110
 
111
  messages = [
112
  {
 
119
  }
120
  ]
121
 
122
+ text = tokenizer.apply_chat_template(
123
  messages,
124
+ tokenize=False,
125
+ add_generation_prompt=True
126
+ )
127
+
128
+ inputs = tokenizer(
129
+ text,
130
+ return_tensors="pt",
131
+ truncation=True,
132
+ max_length=4096
133
+ )
134
+
135
+ inputs = {k: v.to(model.device) for k, v in inputs.items()}
136
+
137
+ outputs = model.generate(
138
+ **inputs,
139
+ max_new_tokens=800,
140
  temperature=0.2,
141
+ do_sample=True,
142
+ pad_token_id=tokenizer.eos_token_id
143
+ )
144
+
145
+ generated_tokens = outputs[0][inputs["input_ids"].shape[1]:]
146
+
147
+ response = tokenizer.decode(
148
+ generated_tokens,
149
+ skip_special_tokens=True
150
  )
151
 
152
+ return response
153
+
154
+
155
+ def analyze_policy(pdf_file):
156
+
157
+ try:
158
+
159
+ if pdf_file is None:
160
+ return "Please upload a policy PDF."
161
+
162
+ policy_text = extract_text(pdf_file)
163
+
164
+ if len(policy_text.strip()) == 0:
165
+ return "No text could be extracted from this PDF."
166
+
167
+ prompt = build_prompt(policy_text)
168
+
169
+ response = generate_response(prompt)
170
+
171
+ return response
172
+
173
+ except Exception as e:
174
+
175
+ print("ERROR:", e)
176
+
177
+ return f"""
178
+ # Error
179
+
180
+ {str(e)}
181
+ """
182
+
183
+
184
+ CUSTOM_CSS = """
185
+ footer {
186
+ display:none;
187
+ }
188
+
189
+ .gradio-container {
190
+ max-width: 1200px !important;
191
+ }
192
+ """
193
 
194
 
195
  with gr.Blocks(
196
  title="Insurance Policy Decoder",
197
+ theme=gr.themes.Soft(),
198
+ css=CUSTOM_CSS
199
  ) as demo:
200
 
201
  gr.Markdown(
 
204
 
205
  Understand your insurance policy in less than a minute.
206
 
207
+ Upload a policy PDF and receive:
208
 
209
+ βœ… Executive Summary
210
 
211
  βœ… Coverage Details
212
 
213
+ βœ… Exclusions
214
 
215
  βœ… Waiting Periods
216
 
 
 
217
  βœ… Coverage Gaps
218
 
219
+ βœ… Risk Scores
220
+
221
+ βœ… Claim Checklist
222
+
223
  βœ… Questions To Ask Your Insurer
224
  """
225
  )
226
 
227
+ pdf_input = gr.File(
228
+ label="Upload Insurance Policy PDF",
229
+ file_types=[".pdf"]
230
+ )
 
 
231
 
232
  analyze_btn = gr.Button(
233
  "Decode Policy",
234
  variant="primary"
235
  )
236
 
237
+ output = gr.Markdown(
238
+ value="Upload a policy document and click **Decode Policy**."
239
+ )
240
 
241
  analyze_btn.click(
242
  fn=analyze_policy,
243
  inputs=pdf_input,
244
+ outputs=output,
245
+ show_progress="full"
246
  )
247
 
248
  demo.launch()