WebashalarForML commited on
Commit
256a3a8
·
verified ·
1 Parent(s): d9c0385

Update server.py

Browse files
Files changed (1) hide show
  1. server.py +108 -111
server.py CHANGED
@@ -154,148 +154,145 @@ SOURCE:
154
 
155
  # Helper functions for different file types
156
  async def process_pdf(file_bytes: bytes) -> str:
157
- """Process PDF file and extract text/info"""
158
- pdf_file = io.BytesIO(file_bytes)
159
- reader = PdfReader(pdf_file)
160
-
161
- num_pages = len(reader.pages)
162
- text = ""
163
- for page in reader.pages:
164
- text += page.extract_text()
165
-
166
- return f"PDF Analysis:\n- Pages: {num_pages}\n- Text length: {len(text)} chars\n\nFirst 500 chars:\n{text[:500]}"
 
 
 
 
 
 
 
 
 
167
 
168
  async def process_image(file_bytes: bytes) -> str:
169
- """Process image file"""
170
- img = Image.open(io.BytesIO(file_bytes))
171
- return f"Image Analysis:\n- Format: {img.format}\n- Size: {img.size}\n- Mode: {img.mode}"
 
 
 
 
 
 
 
 
172
 
173
  async def process_text(file_bytes: bytes) -> str:
174
- """Process text file"""
175
  try:
176
- text = file_bytes.decode('utf-8')
177
- lines = text.split('\n')
178
  words = len(text.split())
179
- return f"Text Analysis:\n- Lines: {len(lines)}\n- Words: {words}\n- Characters: {len(text)}\n\nFirst 500 chars:\n{text[:500]}"
 
 
 
 
 
 
 
180
  except UnicodeDecodeError:
181
  return "Error: File is not valid UTF-8 text"
182
 
183
- def decode_file(file_data: str | bytes) -> bytes:
184
- """Decode base64 file data to bytes"""
185
- if isinstance(file_data, bytes):
186
- return file_data
187
-
188
- # If it's a string, decode from base64
189
- try:
190
- return base64.b64decode(file_data)
191
- except Exception as e:
192
- raise ValueError(f"Failed to decode base64: {e}")
193
 
194
  def detect_file_type(file_bytes: bytes) -> str:
195
- """Detect file type from magic bytes"""
196
- if file_bytes.startswith(b'%PDF'):
197
  return "pdf"
198
- elif file_bytes.startswith(b'\x89PNG'):
199
  return "image"
200
- elif file_bytes.startswith(b'\xff\xd8\xff'):
201
  return "image" # JPEG
202
- elif file_bytes.startswith(b'GIF87a') or file_bytes.startswith(b'GIF89a'):
203
- return "image" # GIF
204
- elif file_bytes.startswith(b'\x42\x4d'):
205
  return "image" # BMP
206
  else:
207
- # Try to decode as text
208
  try:
209
- file_bytes[:1000].decode('utf-8')
210
  return "text"
211
  except:
212
  return "unknown"
213
 
214
- async def process_pdf(file_bytes: bytes) -> str:
215
- """Process PDF file and extract text/info"""
216
- try:
217
- pdf_file = io.BytesIO(file_bytes)
218
- reader = PdfReader(pdf_file)
219
-
220
- num_pages = len(reader.pages)
221
- text = ""
222
- for page in reader.pages:
223
- text += page.extract_text()
224
-
225
- return f"PDF Analysis:\n- Pages: {num_pages}\n- Text length: {len(text)} chars\n\nFirst 500 chars:\n{text[:500]}"
226
- except Exception as e:
227
- return f"PDF processing failed: {str(e)}\nThis might not be a valid PDF file."
228
 
229
- async def process_image(file_bytes: bytes) -> str:
230
- """Process image file"""
231
- try:
232
- img = Image.open(io.BytesIO(file_bytes))
233
- return f"Image Analysis:\n- Format: {img.format}\n- Size: {img.size[0]}x{img.size[1]} pixels\n- Mode: {img.mode}"
234
- except Exception as e:
235
- return f"Image processing failed: {str(e)}"
236
 
237
- async def process_text(file_bytes: bytes) -> str:
238
- """Process text file"""
239
- try:
240
- text = file_bytes.decode('utf-8')
241
- lines = text.split('\n')
242
- words = len(text.split())
243
- return f"Text Analysis:\n- Lines: {len(lines)}\n- Words: {words}\n- Characters: {len(text)}\n\nFirst 500 chars:\n{text[:500]}"
244
- except UnicodeDecodeError:
245
- return "Error: File is not valid UTF-8 text"
246
-
247
- @mcp.tool
248
  async def analyze_file(
249
- ctx: Context,
250
- file: str, # MCP sends base64-encoded string
251
- file_type: Optional[Literal["text", "image", "pdf"]] = None
252
- ) -> str:
253
  """
254
- Analyzes a file with auto-detection.
255
-
256
- Args:
257
- file: The file content (base64-encoded)
258
- file_type: Optional. If not provided, will auto-detect.
259
  """
260
- # Decode base64 to bytes
 
261
  try:
262
- file_bytes = decode_file(file)
263
- except ValueError as e:
264
- return f"Error decoding file: {e}"
265
-
266
- info = f"Received file of size {len(file_bytes)} bytes.\n"
267
-
268
- # Auto-detect if not provided
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
269
  if file_type is None:
270
- file_type = detect_file_type(file_bytes)
271
- info += f"Auto-detected type: {file_type}\n\n"
272
-
273
- if file_type == "unknown":
274
- return info + "Could not detect file type. Please call again with file_type parameter (text/image/pdf)"
 
 
275
  else:
276
- # Verify the file_type matches actual content
277
  detected = detect_file_type(file_bytes)
278
- info += f"Specified type: {file_type}\n"
279
- info += f"Detected type: {detected}\n\n"
280
-
281
  if detected != file_type and detected != "unknown":
282
- info += f"⚠️ Warning: Specified type '{file_type}' doesn't match detected type '{detected}'\n\n"
283
-
284
- # Process based on file_type
285
- try:
286
- if file_type == "pdf":
287
- result = await process_pdf(file_bytes)
288
- elif file_type == "image":
289
- result = await process_image(file_bytes)
290
- elif file_type == "text":
291
- result = await process_text(file_bytes)
292
- else:
293
- return info + f"Unknown file type: {file_type}"
294
-
295
- return info + result
296
-
297
- except Exception as e:
298
- return info + f"Error processing {file_type}: {str(e)}"
299
 
300
  if __name__ == "__main__":
301
  print("Starting FastMCP server on port 7860...")
 
154
 
155
  # Helper functions for different file types
156
  async def process_pdf(file_bytes: bytes) -> str:
157
+ try:
158
+ pdf_file = io.BytesIO(file_bytes)
159
+ reader = PdfReader(pdf_file)
160
+
161
+ num_pages = len(reader.pages)
162
+ text = ""
163
+ for page in reader.pages:
164
+ extracted = page.extract_text() or ""
165
+ text += extracted
166
+
167
+ return (
168
+ f"PDF Analysis:\n"
169
+ f"- Pages: {num_pages}\n"
170
+ f"- Text length: {len(text)} chars\n\n"
171
+ f"First 500 chars:\n{text[:500]}"
172
+ )
173
+ except Exception as e:
174
+ return f"PDF processing failed: {str(e)}\nThis might not be a valid PDF file."
175
+
176
 
177
  async def process_image(file_bytes: bytes) -> str:
178
+ try:
179
+ img = Image.open(io.BytesIO(file_bytes))
180
+ return (
181
+ f"Image Analysis:\n"
182
+ f"- Format: {img.format}\n"
183
+ f"- Size: {img.size[0]}x{img.size[1]} pixels\n"
184
+ f"- Mode: {img.mode}"
185
+ )
186
+ except Exception as e:
187
+ return f"Image processing failed: {str(e)}"
188
+
189
 
190
  async def process_text(file_bytes: bytes) -> str:
 
191
  try:
192
+ text = file_bytes.decode("utf-8")
193
+ lines = text.split("\n")
194
  words = len(text.split())
195
+
196
+ return (
197
+ f"Text Analysis:\n"
198
+ f"- Lines: {len(lines)}\n"
199
+ f"- Words: {words}\n"
200
+ f"- Characters: {len(text)}\n\n"
201
+ f"First 500 chars:\n{text[:500]}"
202
+ )
203
  except UnicodeDecodeError:
204
  return "Error: File is not valid UTF-8 text"
205
 
 
 
 
 
 
 
 
 
 
 
206
 
207
  def detect_file_type(file_bytes: bytes) -> str:
208
+ if file_bytes.startswith(b"%PDF"):
 
209
  return "pdf"
210
+ elif file_bytes.startswith(b"\x89PNG"):
211
  return "image"
212
+ elif file_bytes.startswith(b"\xff\xd8\xff"):
213
  return "image" # JPEG
214
+ elif file_bytes.startswith(b"GIF87a") or file_bytes.startswith(b"GIF89a"):
215
+ return "image"
216
+ elif file_bytes.startswith(b"\x42\x4d"):
217
  return "image" # BMP
218
  else:
 
219
  try:
220
+ file_bytes[:1000].decode("utf-8")
221
  return "text"
222
  except:
223
  return "unknown"
224
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
225
 
226
+ # ---------------- MCP TOOL ---------------- #
 
 
 
 
 
 
227
 
228
+ @mcp.tool
 
 
 
 
 
 
 
 
 
 
229
  async def analyze_file(
230
+ ctx: Context,
231
+ file_uri: str, # <-- file path/uri from client
232
+ file_type: Optional[Literal["text", "image", "pdf"]] = None,
233
+ ) -> str:
234
  """
235
+ Analyze a file using MCP resource URI (recommended).
236
+
237
+ file_uri examples:
238
+ - file:///C:/Users/Admin/Desktop/sample.pdf
239
+ - resource://uploads/123/sample.pdf
240
  """
241
+
242
+ # Read file bytes via MCP resource API
243
  try:
244
+ resource_result = await ctx.read_resource(file_uri)
245
+ except Exception as e:
246
+ return f"Failed to read resource '{file_uri}': {str(e)}"
247
+
248
+ if not resource_result.contents:
249
+ return f"No content returned for resource: {file_uri}"
250
+
251
+ content = resource_result.contents[0]
252
+
253
+ # If it's text resource
254
+ if hasattr(content, "text") and content.text is not None:
255
+ file_bytes = content.text.encode("utf-8")
256
+ else:
257
+ # Blob resource (bytes might be base64 encoded depending on client)
258
+ blob_data = content.blob
259
+
260
+ # some clients give blob as base64 string
261
+ if isinstance(blob_data, str):
262
+ file_bytes = base64.b64decode(blob_data)
263
+ else:
264
+ file_bytes = blob_data
265
+
266
+ info = f"Loaded file from URI: {file_uri}\nSize: {len(file_bytes)} bytes\n"
267
+
268
+ # Auto detect if not specified
269
  if file_type is None:
270
+ detected = detect_file_type(file_bytes)
271
+ info += f"Auto-detected type: {detected}\n\n"
272
+
273
+ if detected == "unknown":
274
+ return info + "Could not detect file type. Please specify file_type=text/image/pdf"
275
+
276
+ file_type = detected
277
  else:
 
278
  detected = detect_file_type(file_bytes)
279
+ info += f"Specified type: {file_type}\nDetected type: {detected}\n\n"
280
+
 
281
  if detected != file_type and detected != "unknown":
282
+ info += f"⚠️ Warning: mismatch (specified={file_type}, detected={detected})\n\n"
283
+
284
+ # Process file
285
+ if file_type == "pdf":
286
+ result = await process_pdf(file_bytes)
287
+ elif file_type == "image":
288
+ result = await process_image(file_bytes)
289
+ elif file_type == "text":
290
+ result = await process_text(file_bytes)
291
+ else:
292
+ return info + f"Unsupported file_type: {file_type}"
293
+
294
+ return info + result
295
+
 
 
 
296
 
297
  if __name__ == "__main__":
298
  print("Starting FastMCP server on port 7860...")