Daemontatox commited on
Commit
43bee1c
·
verified ·
1 Parent(s): f9b55bc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -36
app.py CHANGED
@@ -20,7 +20,7 @@ class DocumentState:
20
  def __init__(self):
21
  self.current_doc_images = []
22
  self.current_doc_text = ""
23
- self.doc_type = None # 'pdf' or 'image'
24
 
25
  def clear(self):
26
  self.current_doc_images = []
@@ -35,17 +35,18 @@ def process_pdf_file(file_path):
35
  images = []
36
  text = ""
37
 
38
- for page_num, page in enumerate(doc):
39
- # Extract text
40
- text += f"\n=== Page {page_num + 1} ===\n"
41
- text += page.get_text() + "\n"
42
-
43
- # Convert page to image
44
- pix = page.get_pixmap(matrix=fitz.Matrix(300/72, 300/72)) # 300 DPI
45
  img_data = pix.tobytes("png")
46
  img = Image.open(io.BytesIO(img_data))
47
  images.append(img.convert("RGB"))
48
 
 
 
 
49
  doc.close()
50
  return images, text
51
 
@@ -61,7 +62,7 @@ def process_file(file):
61
  if file_path.lower().endswith('.pdf'):
62
  doc_state.doc_type = 'pdf'
63
  doc_state.current_doc_images, doc_state.current_doc_text = process_pdf_file(file_path)
64
- return f"PDF processed successfully. {len(doc_state.current_doc_images)} pages loaded. You can now ask questions about the content."
65
  else:
66
  doc_state.doc_type = 'image'
67
  doc_state.current_doc_images = [Image.open(file_path).convert("RGB")]
@@ -71,48 +72,35 @@ def process_file(file):
71
  def bot_streaming(message, history, max_new_tokens=2048):
72
  txt = message["text"]
73
  messages = []
74
- images = []
75
 
76
  # Process new file if provided
77
  if message.get("files") and len(message["files"]) > 0:
78
  process_file(message["files"][0])
79
 
80
- # Process history and maintain context
81
  for i, msg in enumerate(history):
82
  if isinstance(msg[0], tuple):
83
- messages.append({"role": "user", "content": [{"type": "text", "text": history[i+1][0]}, {"type": "image"}]})
84
- messages.append({"role": "assistant", "content": [{"type": "text", "text": history[i+1][1]}]})
85
- elif isinstance(history[i-1], tuple) and isinstance(msg[0], str):
86
- pass
87
- elif isinstance(history[i-1][0], str) and isinstance(msg[0], str):
88
  messages.append({"role": "user", "content": [{"type": "text", "text": msg[0]}]})
89
  messages.append({"role": "assistant", "content": [{"type": "text", "text": msg[1]}]})
90
 
91
  # Include document context in the current message
92
  if doc_state.current_doc_images:
93
- images.extend(doc_state.current_doc_images)
94
- context = ""
95
- if doc_state.doc_type == 'pdf':
96
- context = f"\nContext from PDF:\n{doc_state.current_doc_text}"
97
  current_msg = f"{txt}{context}"
98
  messages.append({"role": "user", "content": [{"type": "text", "text": current_msg}, {"type": "image"}]})
 
 
 
 
 
 
 
99
  else:
100
  messages.append({"role": "user", "content": [{"type": "text", "text": txt}]})
101
-
102
- texts = processor.apply_chat_template(messages, add_generation_prompt=True)
103
-
104
- if not images:
105
  inputs = processor(text=texts, return_tensors="pt").to("cuda")
106
- else:
107
- # Process images in batches if needed
108
- max_images = 12 # Increased maximum number of images/pages
109
- if len(images) > max_images:
110
- # Take evenly spaced samples if we have too many pages
111
- indices = np.linspace(0, len(images) - 1, max_images, dtype=int)
112
- images = [images[i] for i in indices]
113
- txt += f"\n(Note: Analyzing {max_images} evenly distributed pages from the document)"
114
-
115
- inputs = processor(text=texts, images=images, return_tensors="pt").to("cuda")
116
 
117
  streamer = TextIteratorStreamer(processor, skip_special_tokens=True, skip_prompt=True)
118
  generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=max_new_tokens)
@@ -131,10 +119,10 @@ def clear_context():
131
  doc_state.clear()
132
  return "Document context cleared. You can upload a new document."
133
 
134
- # Create the Gradio interface with enhanced features
135
  with gr.Blocks() as demo:
136
  gr.Markdown("# Document Analyzer with Chat Support")
137
- gr.Markdown("Upload a PDF or image and chat about its contents. The context is maintained throughout the conversation.")
138
 
139
  chatbot = gr.ChatInterface(
140
  fn=bot_streaming,
 
20
  def __init__(self):
21
  self.current_doc_images = []
22
  self.current_doc_text = ""
23
+ self.doc_type = None
24
 
25
  def clear(self):
26
  self.current_doc_images = []
 
35
  images = []
36
  text = ""
37
 
38
+ # Take first page only for initial processing
39
+ if doc.page_count > 0:
40
+ page = doc[0]
41
+ text = f"First page content:\n{page.get_text()}\n"
42
+ pix = page.get_pixmap(matrix=fitz.Matrix(300/72, 300/72))
 
 
43
  img_data = pix.tobytes("png")
44
  img = Image.open(io.BytesIO(img_data))
45
  images.append(img.convert("RGB"))
46
 
47
+ if doc.page_count > 1:
48
+ text += f"\nTotal pages in document: {doc.page_count}\n"
49
+
50
  doc.close()
51
  return images, text
52
 
 
62
  if file_path.lower().endswith('.pdf'):
63
  doc_state.doc_type = 'pdf'
64
  doc_state.current_doc_images, doc_state.current_doc_text = process_pdf_file(file_path)
65
+ return f"PDF first page processed. You can now ask questions about the content."
66
  else:
67
  doc_state.doc_type = 'image'
68
  doc_state.current_doc_images = [Image.open(file_path).convert("RGB")]
 
72
  def bot_streaming(message, history, max_new_tokens=2048):
73
  txt = message["text"]
74
  messages = []
 
75
 
76
  # Process new file if provided
77
  if message.get("files") and len(message["files"]) > 0:
78
  process_file(message["files"][0])
79
 
80
+ # Process history
81
  for i, msg in enumerate(history):
82
  if isinstance(msg[0], tuple):
83
+ messages.append({"role": "user", "content": [{"type": "text", "text": msg[0][1]}, {"type": "image"}]})
84
+ messages.append({"role": "assistant", "content": [{"type": "text", "text": msg[1]}]})
85
+ elif isinstance(msg[0], str):
 
 
86
  messages.append({"role": "user", "content": [{"type": "text", "text": msg[0]}]})
87
  messages.append({"role": "assistant", "content": [{"type": "text", "text": msg[1]}]})
88
 
89
  # Include document context in the current message
90
  if doc_state.current_doc_images:
91
+ context = f"\nDocument context:\n{doc_state.current_doc_text}" if doc_state.current_doc_text else ""
 
 
 
92
  current_msg = f"{txt}{context}"
93
  messages.append({"role": "user", "content": [{"type": "text", "text": current_msg}, {"type": "image"}]})
94
+
95
+ # Process with single image
96
+ inputs = processor(
97
+ text=texts,
98
+ images=doc_state.current_doc_images[0:1], # Only use first image
99
+ return_tensors="pt"
100
+ ).to("cuda")
101
  else:
102
  messages.append({"role": "user", "content": [{"type": "text", "text": txt}]})
 
 
 
 
103
  inputs = processor(text=texts, return_tensors="pt").to("cuda")
 
 
 
 
 
 
 
 
 
 
104
 
105
  streamer = TextIteratorStreamer(processor, skip_special_tokens=True, skip_prompt=True)
106
  generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=max_new_tokens)
 
119
  doc_state.clear()
120
  return "Document context cleared. You can upload a new document."
121
 
122
+ # Create the Gradio interface
123
  with gr.Blocks() as demo:
124
  gr.Markdown("# Document Analyzer with Chat Support")
125
+ gr.Markdown("Upload a PDF or image and chat about its contents. For PDFs, the first page will be processed for visual analysis.")
126
 
127
  chatbot = gr.ChatInterface(
128
  fn=bot_streaming,