gnumanth commited on
Commit
d7c8d35
·
verified ·
1 Parent(s): 0a27e5d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -26
app.py CHANGED
@@ -26,40 +26,34 @@ import os
26
  import io
27
 
28
  def save_uploaded_file(file):
29
- """Save uploaded file to temporary location and return path.
30
- Handles only file uploads, not URLs."""
31
 
32
  if file is None:
33
  return None
34
 
35
  try:
36
  temp_dir = tempfile.gettempdir()
37
- temp_filename = tempfile.mkstemp(dir=temp_dir, suffix=os.path.splitext(file.name)[1])[1]
38
-
39
- # Crucial: Check for valid file-like object
40
- if hasattr(file, 'read'):
41
- with open(temp_filename, 'wb') as f:
42
- try:
43
- while True:
44
- chunk = file.read(8192)
45
- if not chunk:
46
- break
47
- f.write(chunk)
48
- except Exception as e:
49
- return f"Error during file write: {str(e)}"
50
-
51
- elif hasattr(file, 'getvalue'): # In-memory file-like
52
- with open(temp_filename, 'wb') as f:
53
- try:
54
- f.write(file.getvalue())
55
- except Exception as e:
56
- return f"Error during file write: {str(e)}"
57
-
58
- else:
59
- return "Error: Unsupported file type."
60
 
61
  return temp_filename
62
-
63
  except Exception as e:
64
  return f"Error saving file: {str(e)}"
65
 
 
26
  import io
27
 
28
  def save_uploaded_file(file):
29
+ """Saves a file uploaded with gardio to a temporary location."""
 
30
 
31
  if file is None:
32
  return None
33
 
34
  try:
35
  temp_dir = tempfile.gettempdir()
36
+ temp_filename = tempfile.mkstemp(dir=temp_dir, suffix=os.path.splitext(file.filename)[1])[1]
37
+
38
+ # Check if the file object is valid before attempting to read it
39
+ if not hasattr(file, 'filename') or not file.filename:
40
+ return "Error: Invalid file object. Missing filename."
41
+
42
+
43
+ with open(temp_filename, 'wb') as f:
44
+ try:
45
+ # Crucial: Check for a 'read' attribute to handle various file-like objects
46
+ if hasattr(file, 'read'):
47
+ for chunk in file.chunks():
48
+ f.write(chunk)
49
+ elif hasattr(file, 'getvalue'):
50
+ f.write(file.getvalue())
51
+ else:
52
+ return "Error: Unsupported file-like object. Missing 'read' or 'getvalue'."
53
+ except Exception as e:
54
+ return f"Error writing to file: {str(e)}"
 
 
 
 
55
 
56
  return temp_filename
 
57
  except Exception as e:
58
  return f"Error saving file: {str(e)}"
59