AC2513 commited on
Commit
54e151e
·
1 Parent(s): af6d2bd

added documentation

Browse files
Files changed (1) hide show
  1. utils.py +136 -9
utils.py CHANGED
@@ -24,7 +24,21 @@ PRESET_PROMPTS = {
24
  }
25
 
26
  def check_file_size(file_path: str) -> bool:
27
- """Check if a file meets the size requirements."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  if not os.path.exists(file_path):
29
  raise ValueError(f"File not found: {file_path}")
30
 
@@ -41,7 +55,25 @@ def check_file_size(file_path: str) -> bool:
41
 
42
 
43
  def get_frames(video_path: str, max_images: int) -> list[tuple[Image.Image, float]]:
44
- """Extract frames from a video file."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  check_file_size(video_path)
46
 
47
  frames: list[tuple[Image.Image, float]] = []
@@ -72,7 +104,26 @@ def get_frames(video_path: str, max_images: int) -> list[tuple[Image.Image, floa
72
 
73
 
74
  def process_video(video_path: str, max_images: int) -> list[dict]:
75
- """Process a video file and return formatted content for the model."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  result_content = []
77
  frames = get_frames(video_path, max_images)
78
  for frame in frames:
@@ -88,7 +139,22 @@ def process_video(video_path: str, max_images: int) -> list[dict]:
88
 
89
 
90
  def extract_pdf_text(pdf_path: str) -> str:
91
- """Extract text content from a PDF file."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  check_file_size(pdf_path)
93
 
94
  try:
@@ -114,7 +180,23 @@ def extract_pdf_text(pdf_path: str) -> str:
114
 
115
 
116
  def process_user_input(message: dict, max_images: int) -> list[dict]:
117
- """Process user input including files and return formatted content for the model."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  if not message["files"]:
119
  return [{"type": "text", "text": message["text"]}]
120
 
@@ -153,7 +235,26 @@ def process_user_input(message: dict, max_images: int) -> list[dict]:
153
 
154
 
155
  def process_history(history: list[dict]) -> list[dict]:
156
- """Process chat history into the format expected by the model."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  messages = []
158
  content_buffer = []
159
 
@@ -189,12 +290,38 @@ def process_history(history: list[dict]) -> list[dict]:
189
 
190
 
191
  def update_custom_prompt(preset_choice: str) -> str:
192
- """Update the custom prompt based on preset selection."""
 
 
 
 
 
 
 
 
 
 
 
 
193
  if preset_choice == "Custom Prompt":
194
  return ""
195
  return PRESET_PROMPTS.get(preset_choice, "")
196
 
197
 
198
  def get_preset_prompts() -> dict[str, str]:
199
- """Return the dictionary of preset prompts for the main application."""
200
- return PRESET_PROMPTS.copy()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  }
25
 
26
  def check_file_size(file_path: str) -> bool:
27
+ """Check if a file meets the size requirements for processing.
28
+
29
+ Validates that the file exists and is within the allowed size limits based on file type.
30
+ Video files (.mp4, .mov) have a limit of 100MB, while image files have a limit of 10MB.
31
+
32
+ Args:
33
+ file_path (str): The absolute path to the file to be checked.
34
+
35
+ Returns:
36
+ bool: True if the file meets size requirements.
37
+
38
+ Raises:
39
+ ValueError: If the file doesn't exist, or if the file size exceeds the maximum
40
+ allowed size for its type.
41
+ """
42
  if not os.path.exists(file_path):
43
  raise ValueError(f"File not found: {file_path}")
44
 
 
55
 
56
 
57
  def get_frames(video_path: str, max_images: int) -> list[tuple[Image.Image, float]]:
58
+ """Extract frames from a video file at regular intervals.
59
+
60
+ Opens a video file and extracts frames at evenly distributed intervals to get
61
+ a representative sample of the video content. Each frame is converted to RGB
62
+ format and returned as a PIL Image along with its timestamp.
63
+
64
+ Args:
65
+ video_path (str): The absolute path to the video file (.mp4 or .mov).
66
+ max_images (int): The maximum number of frames to extract from the video.
67
+ Must be a positive integer.
68
+
69
+ Returns:
70
+ list[tuple[Image.Image, float]]: A list of tuples where each tuple contains
71
+ an Image.Image object (the extracted frame in RGB format) and a float
72
+ (the timestamp of the frame in seconds, rounded to 2 decimal places).
73
+
74
+ Raises:
75
+ ValueError: If the video file cannot be opened or if file size validation fails.
76
+ """
77
  check_file_size(video_path)
78
 
79
  frames: list[tuple[Image.Image, float]] = []
 
104
 
105
 
106
  def process_video(video_path: str, max_images: int) -> list[dict]:
107
+ """Process a video file and return formatted content for model input.
108
+
109
+ Extracts frames from a video file, saves them as temporary PNG files, and
110
+ formats them into a structure suitable for multimodal model input. Each frame
111
+ is paired with descriptive text indicating its timestamp.
112
+
113
+ Args:
114
+ video_path (str): The absolute path to the video file to be processed.
115
+ max_images (int): The maximum number of frames to extract and process.
116
+
117
+ Returns:
118
+ list[dict]: A list of dictionaries representing the processed video content.
119
+ The structure alternates between text descriptions and image references:
120
+ {"type": "text", "text": "Frame {timestamp}:"} and
121
+ {"type": "image", "url": "/path/to/temp/frame.png"}.
122
+
123
+ Note:
124
+ Creates temporary PNG files that are not automatically cleaned up.
125
+ The caller is responsible for cleanup if needed.
126
+ """
127
  result_content = []
128
  frames = get_frames(video_path, max_images)
129
  for frame in frames:
 
139
 
140
 
141
  def extract_pdf_text(pdf_path: str) -> str:
142
+ """Extract text content from a PDF file.
143
+
144
+ Opens a PDF file and extracts all readable text content from each page.
145
+ Pages are numbered and formatted for readability. Empty pages are skipped.
146
+
147
+ Args:
148
+ pdf_path (str): The absolute path to the PDF file to be processed.
149
+
150
+ Returns:
151
+ str: The extracted text content with page numbers and formatting.
152
+ If no text is found, returns a message indicating no content was found.
153
+
154
+ Raises:
155
+ ValueError: If the file size validation fails or if PDF processing encounters
156
+ an error that prevents text extraction.
157
+ """
158
  check_file_size(pdf_path)
159
 
160
  try:
 
180
 
181
 
182
  def process_user_input(message: dict, max_images: int) -> list[dict]:
183
+ """Process user input including files and return formatted content for the model.
184
+
185
+ Takes a user message that may contain text and file attachments, processes each
186
+ file according to its type, and returns a structured format suitable for
187
+ multimodal model input. Handles videos, PDFs, and image files.
188
+
189
+ Args:
190
+ message (dict): A dictionary containing user input with keys:
191
+ "text" (str) - The user's text message, and
192
+ "files" (list[str]) - List of file paths attached to the message.
193
+ max_images (int): Maximum number of frames to extract from video files.
194
+
195
+ Returns:
196
+ list[dict]: A list of dictionaries representing the processed content with
197
+ types "text" or "image" and corresponding content data. Includes error
198
+ messages for files that cannot be processed.
199
+ """
200
  if not message["files"]:
201
  return [{"type": "text", "text": message["text"]}]
202
 
 
235
 
236
 
237
  def process_history(history: list[dict]) -> list[dict]:
238
+ """Process chat history into the format expected by the model.
239
+
240
+ Converts chat history from the UI format into the structured format required
241
+ by multimodal language models. Groups consecutive user messages and handles
242
+ different content types (text, images, videos, PDFs) appropriately.
243
+
244
+ Args:
245
+ history (list[dict]): A list of chat history items, where each item contains
246
+ "role" (str) - either "user" or "assistant", and
247
+ "content" - the message content (str for text, tuple for files).
248
+
249
+ Returns:
250
+ list[dict]: A list of messages formatted for the model with "role" and
251
+ "content" keys, where content is a list of dictionaries with "type"
252
+ and associated data.
253
+
254
+ Note:
255
+ Groups consecutive user messages into a single message. Videos and PDFs
256
+ in history are replaced with placeholder text to avoid reprocessing.
257
+ """
258
  messages = []
259
  content_buffer = []
260
 
 
290
 
291
 
292
  def update_custom_prompt(preset_choice: str) -> str:
293
+ """Update the custom prompt based on preset selection.
294
+
295
+ Returns the appropriate preset prompt text based on the user's selection.
296
+ If "Custom Prompt" is selected, returns an empty string to allow manual input.
297
+
298
+ Args:
299
+ preset_choice (str): The name of the selected preset prompt. Should match
300
+ one of the keys in PRESET_PROMPTS or be "Custom Prompt".
301
+
302
+ Returns:
303
+ str: The preset prompt text corresponding to the selection, or an empty
304
+ string if "Custom Prompt" is selected or if the preset is not found.
305
+ """
306
  if preset_choice == "Custom Prompt":
307
  return ""
308
  return PRESET_PROMPTS.get(preset_choice, "")
309
 
310
 
311
  def get_preset_prompts() -> dict[str, str]:
312
+ """Return the dictionary of preset prompts for the main application.
313
+
314
+ Provides a copy of the predefined prompt templates that can be used throughout
315
+ the application. Each preset is designed for a specific use case and contains
316
+ detailed instructions for the AI model's behavior.
317
+
318
+ Returns:
319
+ dict[str, str]: A dictionary mapping preset names to their prompt texts.
320
+ Includes prompts for general assistance, document analysis, visual content
321
+ analysis, educational tutoring, technical review, and creative storytelling.
322
+
323
+ Note:
324
+ Returns a copy of the PRESET_PROMPTS dictionary to prevent accidental
325
+ modification of the original constants.
326
+ """
327
+ return PRESET_PROMPTS.copy()