Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -16,6 +16,8 @@ from transformers import AutoProcessor, Gemma3ForConditionalGeneration, TextIter
|
|
16 |
|
17 |
# [PDF] PyPDF2 ์ถ๊ฐ
|
18 |
import PyPDF2
|
|
|
|
|
19 |
|
20 |
model_id = os.getenv("MODEL_ID", "google/gemma-3-27b-it")
|
21 |
processor = AutoProcessor.from_pretrained(model_id, padding_side="left")
|
@@ -25,7 +27,46 @@ model = Gemma3ForConditionalGeneration.from_pretrained(
|
|
25 |
|
26 |
MAX_NUM_IMAGES = int(os.getenv("MAX_NUM_IMAGES", "5"))
|
27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
|
|
|
|
|
|
29 |
def count_files_in_new_message(paths: list[str]) -> tuple[int, int]:
|
30 |
image_count = 0
|
31 |
video_count = 0
|
@@ -36,7 +77,6 @@ def count_files_in_new_message(paths: list[str]) -> tuple[int, int]:
|
|
36 |
image_count += 1
|
37 |
return image_count, video_count
|
38 |
|
39 |
-
|
40 |
def count_files_in_history(history: list[dict]) -> tuple[int, int]:
|
41 |
image_count = 0
|
42 |
video_count = 0
|
@@ -49,18 +89,22 @@ def count_files_in_history(history: list[dict]) -> tuple[int, int]:
|
|
49 |
image_count += 1
|
50 |
return image_count, video_count
|
51 |
|
52 |
-
|
|
|
|
|
53 |
def validate_media_constraints(message: dict, history: list[dict]) -> bool:
|
54 |
"""
|
55 |
์ด๋ฏธ์ง/๋น๋์ค ๊ฐ์์ ํผํฉ ์ฌ๋ถ ๋ฑ์ ๊ฒ์ฌํ๋ ํจ์.
|
56 |
-
PDF
|
57 |
"""
|
58 |
-
#
|
59 |
pdf_files = [f for f in message["files"] if f.endswith(".pdf")]
|
60 |
-
|
|
|
|
|
61 |
|
62 |
-
# ๊ธฐ์กด ๋ก์ง์
|
63 |
-
new_image_count, new_video_count = count_files_in_new_message(
|
64 |
history_image_count, history_video_count = count_files_in_history(history)
|
65 |
image_count = history_image_count + new_image_count
|
66 |
video_count = history_video_count + new_video_count
|
@@ -75,25 +119,22 @@ def validate_media_constraints(message: dict, history: list[dict]) -> bool:
|
|
75 |
if "<image>" in message["text"]:
|
76 |
gr.Warning("Using <image> tags with video files is not supported.")
|
77 |
return False
|
78 |
-
# TODO: Add frame count validation for videos similar to image count limits # noqa: FIX002, TD002, TD003
|
79 |
|
80 |
if video_count == 0 and image_count > MAX_NUM_IMAGES:
|
81 |
gr.Warning(f"You can upload up to {MAX_NUM_IMAGES} images.")
|
82 |
return False
|
83 |
|
84 |
-
#
|
85 |
-
# ์ผ๋จ ์ ํ์ ๋์ง ์๊ณ ๋ฐ๋ก True ๋ฐํ
|
86 |
-
|
87 |
-
# <image> ํ๊ทธ๊ฐ ์์ ๊ฒฝ์ฐ, ์ด๋ฏธ์ง ๊ฐ์์ ๋งค์นญ ๊ฒ์ฌ
|
88 |
if "<image>" in message["text"]:
|
89 |
-
# new_image_count๋ pdf ์ ์ธ๋ ์ด๋ฏธ์ง ์
|
90 |
if message["text"].count("<image>") != new_image_count:
|
91 |
gr.Warning("The number of <image> tags in the text does not match the number of images.")
|
92 |
return False
|
93 |
|
94 |
return True
|
95 |
|
96 |
-
|
|
|
|
|
97 |
def downsample_video(video_path: str) -> list[tuple[Image.Image, float]]:
|
98 |
vidcap = cv2.VideoCapture(video_path)
|
99 |
fps = vidcap.get(cv2.CAP_PROP_FPS)
|
@@ -114,7 +155,6 @@ def downsample_video(video_path: str) -> list[tuple[Image.Image, float]]:
|
|
114 |
vidcap.release()
|
115 |
return frames
|
116 |
|
117 |
-
|
118 |
def process_video(video_path: str) -> list[dict]:
|
119 |
content = []
|
120 |
frames = downsample_video(video_path)
|
@@ -127,7 +167,9 @@ def process_video(video_path: str) -> list[dict]:
|
|
127 |
logger.debug(f"{content=}")
|
128 |
return content
|
129 |
|
130 |
-
|
|
|
|
|
131 |
def process_interleaved_images(message: dict) -> list[dict]:
|
132 |
logger.debug(f"{message['files']=}")
|
133 |
parts = re.split(r"(<image>)", message["text"])
|
@@ -148,40 +190,25 @@ def process_interleaved_images(message: dict) -> list[dict]:
|
|
148 |
logger.debug(f"{content=}")
|
149 |
return content
|
150 |
|
151 |
-
|
152 |
-
#
|
153 |
-
|
154 |
-
"""
|
155 |
-
PDF ํ์ผ์ ํ
์คํธ๋ก ์ถ์ถ ํ, ๊ฐ๋จํ Markdown ํํ๋ก ๋ฐํ.
|
156 |
-
"""
|
157 |
-
text_chunks = []
|
158 |
-
with open(pdf_path, "rb") as f:
|
159 |
-
reader = PyPDF2.PdfReader(f)
|
160 |
-
for page_num, page in enumerate(reader.pages, start=1):
|
161 |
-
page_text = page.extract_text()
|
162 |
-
page_text = page_text.strip() if page_text else ""
|
163 |
-
if page_text:
|
164 |
-
# ํ์ด์ง๋ณ๋ก ๊ฐ๋จํ ํค๋์ ๋ณธ๋ฌธ์ Markdown์ผ๋ก ํฉ์นจ
|
165 |
-
text_chunks.append(f"## Page {page_num}\n\n{page_text}\n")
|
166 |
-
return "\n".join(text_chunks)
|
167 |
-
|
168 |
-
|
169 |
def process_new_user_message(message: dict) -> list[dict]:
|
170 |
-
"""
|
171 |
-
์ user message์์ text, ํ์ผ(์ด๋ฏธ์ง/๋น๋์ค/PDF)์ ์ฒ๋ฆฌ.
|
172 |
-
"""
|
173 |
if not message["files"]:
|
174 |
return [{"type": "text", "text": message["text"]}]
|
175 |
|
176 |
-
#
|
177 |
pdf_files = [f for f in message["files"] if f.endswith(".pdf")]
|
178 |
-
#
|
179 |
-
|
|
|
|
|
|
|
180 |
|
181 |
-
# ์ผ๋จ ์ฌ์ฉ์์ text๋ฅผ
|
182 |
content_list = [{"type": "text", "text": message["text"]}]
|
183 |
|
184 |
-
# PDF ๋ณํ ํ ์ถ๊ฐ
|
185 |
for pdf_path in pdf_files:
|
186 |
pdf_markdown = pdf_to_markdown(pdf_path)
|
187 |
if pdf_markdown.strip():
|
@@ -189,12 +216,14 @@ def process_new_user_message(message: dict) -> list[dict]:
|
|
189 |
else:
|
190 |
content_list.append({"type": "text", "text": "(PDF์์ ํ
์คํธ ์ถ์ถ ์คํจ)"})
|
191 |
|
|
|
|
|
|
|
|
|
192 |
|
193 |
-
#
|
194 |
video_files = [f for f in other_files if f.endswith(".mp4")]
|
195 |
if video_files:
|
196 |
-
# ๋น๋์ค๋ ํ ๊ฐ๋ง ์ฒ๋ฆฌํ๋ค๋ ์ ์ (validate_media_constraints์์ ์ด๋ฏธ ๊ฒ์ฌ)
|
197 |
-
# ์ฌ๋ฌ ๊ฐ์ผ ๊ฒฝ์ฐ ์ฒซ ๋ฒ์งธ ๊ฒ๋ง ์ฒ๋ฆฌํ๊ฑฐ๋, ๊ฒฝ๊ณ ์ฒ๋ฆฌ
|
198 |
content_list += process_video(video_files[0])
|
199 |
return content_list
|
200 |
|
@@ -209,7 +238,9 @@ def process_new_user_message(message: dict) -> list[dict]:
|
|
209 |
|
210 |
return content_list
|
211 |
|
212 |
-
|
|
|
|
|
213 |
def process_history(history: list[dict]) -> list[dict]:
|
214 |
messages = []
|
215 |
current_user_content: list[dict] = []
|
@@ -227,7 +258,9 @@ def process_history(history: list[dict]) -> list[dict]:
|
|
227 |
current_user_content.append({"type": "image", "url": content[0]})
|
228 |
return messages
|
229 |
|
230 |
-
|
|
|
|
|
231 |
@spaces.GPU(duration=120)
|
232 |
def run(message: dict, history: list[dict], system_prompt: str = "", max_new_tokens: int = 512) -> Iterator[str]:
|
233 |
if not validate_media_constraints(message, history):
|
@@ -262,7 +295,9 @@ def run(message: dict, history: list[dict], system_prompt: str = "", max_new_tok
|
|
262 |
output += delta
|
263 |
yield output
|
264 |
|
265 |
-
|
|
|
|
|
266 |
examples = [
|
267 |
[
|
268 |
{
|
@@ -385,22 +420,34 @@ examples = [
|
|
385 |
],
|
386 |
]
|
387 |
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
demo = gr.ChatInterface(
|
392 |
fn=run,
|
393 |
type="messages",
|
394 |
chatbot=gr.Chatbot(type="messages", scale=1, allow_tags=["image"]),
|
395 |
textbox=gr.MultimodalTextbox(
|
396 |
-
file_types=["image", ".mp4", ".pdf"], #
|
397 |
file_count="multiple",
|
398 |
autofocus=True
|
399 |
),
|
400 |
multimodal=True,
|
401 |
additional_inputs=[
|
402 |
-
gr.Textbox(
|
403 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
404 |
],
|
405 |
stop_btn=False,
|
406 |
title="Gemma 3 27B IT",
|
|
|
16 |
|
17 |
# [PDF] PyPDF2 ์ถ๊ฐ
|
18 |
import PyPDF2
|
19 |
+
# [CSV] Pandas ์ถ๊ฐ
|
20 |
+
import pandas as pd
|
21 |
|
22 |
model_id = os.getenv("MODEL_ID", "google/gemma-3-27b-it")
|
23 |
processor = AutoProcessor.from_pretrained(model_id, padding_side="left")
|
|
|
27 |
|
28 |
MAX_NUM_IMAGES = int(os.getenv("MAX_NUM_IMAGES", "5"))
|
29 |
|
30 |
+
###################################################################
|
31 |
+
# CSV๋ฅผ Markdown์ผ๋ก ๋ณํํ๋ ์ ํธ ํจ์
|
32 |
+
###################################################################
|
33 |
+
def csv_to_markdown(csv_path: str) -> str:
|
34 |
+
"""
|
35 |
+
CSV ํ์ผ ์ ์ฒด๋ฅผ ๋ฌธ์์ด๋ก ๋ณํํ์ฌ Markdown ํํ๋ก ๋ฐํ.
|
36 |
+
(๋งค์ฐ ํฐ CSV๋ผ๋ฉด ์ ์ฒด๋ฅผ ๋๊ธฐ๋ ๊ฒ์ด ์ํํ ์ ์์ -> ํ์ ์ ์๋ผ๋ผ ๊ฒ)
|
37 |
+
"""
|
38 |
+
try:
|
39 |
+
df = pd.read_csv(csv_path)
|
40 |
+
df_str = df.to_string()
|
41 |
+
# ํ์ํ๋ค๋ฉด ๊ธธ์ด ์ ํ์ ๊ฑธ์ด๋ ๋จ
|
42 |
+
# if len(df_str) > 10000:
|
43 |
+
# df_str = df_str[:10000] + "\n...(truncated)..."
|
44 |
+
|
45 |
+
return f"**[CSV File: {os.path.basename(csv_path)}]**\n\n```\n{df_str}\n```"
|
46 |
+
except Exception as e:
|
47 |
+
return f"Failed to read CSV ({os.path.basename(csv_path)}): {str(e)}"
|
48 |
+
|
49 |
+
###################################################################
|
50 |
+
# PDF -> Markdown ๋ณํ ํจ์ (๊ธฐ์กด)
|
51 |
+
###################################################################
|
52 |
+
def pdf_to_markdown(pdf_path: str) -> str:
|
53 |
+
"""
|
54 |
+
PDF ํ์ผ์ ํ
์คํธ๋ก ์ถ์ถ ํ, ๊ฐ๋จํ Markdown ํํ๋ก ๋ฐํ.
|
55 |
+
"""
|
56 |
+
text_chunks = []
|
57 |
+
with open(pdf_path, "rb") as f:
|
58 |
+
reader = PyPDF2.PdfReader(f)
|
59 |
+
for page_num, page in enumerate(reader.pages, start=1):
|
60 |
+
page_text = page.extract_text()
|
61 |
+
page_text = page_text.strip() if page_text else ""
|
62 |
+
if page_text:
|
63 |
+
# ํ์ด์ง๋ณ๋ก ๊ฐ๋จํ ํค๋์ ๋ณธ๋ฌธ์ Markdown์ผ๋ก ํฉ์นจ
|
64 |
+
text_chunks.append(f"## Page {page_num}\n\n{page_text}\n")
|
65 |
+
return "\n".join(text_chunks)
|
66 |
|
67 |
+
###################################################################
|
68 |
+
# ์ด๋ฏธ์ง/๋น๋์ค ๊ฐ์ ์นด์ดํธ (๊ธฐ์กด)
|
69 |
+
###################################################################
|
70 |
def count_files_in_new_message(paths: list[str]) -> tuple[int, int]:
|
71 |
image_count = 0
|
72 |
video_count = 0
|
|
|
77 |
image_count += 1
|
78 |
return image_count, video_count
|
79 |
|
|
|
80 |
def count_files_in_history(history: list[dict]) -> tuple[int, int]:
|
81 |
image_count = 0
|
82 |
video_count = 0
|
|
|
89 |
image_count += 1
|
90 |
return image_count, video_count
|
91 |
|
92 |
+
###################################################################
|
93 |
+
# ๋ฏธ๋์ด(์ด๋ฏธ์ง/๋น๋์ค) ์ ํ ๊ฒ์ฌ + PDF/CSV ์์ธ (๊ธฐ์กด/์์ )
|
94 |
+
###################################################################
|
95 |
def validate_media_constraints(message: dict, history: list[dict]) -> bool:
|
96 |
"""
|
97 |
์ด๋ฏธ์ง/๋น๋์ค ๊ฐ์์ ํผํฉ ์ฌ๋ถ ๋ฑ์ ๊ฒ์ฌํ๋ ํจ์.
|
98 |
+
PDF, CSV ๋ฑ์ ๊ฒ์ฌ ๋ก์ง์์ ์ ์ธํ์ฌ ์
๋ก๋๋ง ํ์ฉ.
|
99 |
"""
|
100 |
+
# pdf, csv ํ์ผ ์ ์ธ
|
101 |
pdf_files = [f for f in message["files"] if f.endswith(".pdf")]
|
102 |
+
csv_files = [f for f in message["files"] if f.lower().endswith(".csv")]
|
103 |
+
non_pdf_csv_files = [f for f in message["files"]
|
104 |
+
if not f.endswith(".pdf") and not f.lower().endswith(".csv")]
|
105 |
|
106 |
+
# ๊ธฐ์กด ๋ก์ง์ ์ด๋ฏธ์ง/๋น๋์ค์ ๋ํด์๋ง ์ฒดํฌ
|
107 |
+
new_image_count, new_video_count = count_files_in_new_message(non_pdf_csv_files)
|
108 |
history_image_count, history_video_count = count_files_in_history(history)
|
109 |
image_count = history_image_count + new_image_count
|
110 |
video_count = history_video_count + new_video_count
|
|
|
119 |
if "<image>" in message["text"]:
|
120 |
gr.Warning("Using <image> tags with video files is not supported.")
|
121 |
return False
|
|
|
122 |
|
123 |
if video_count == 0 and image_count > MAX_NUM_IMAGES:
|
124 |
gr.Warning(f"You can upload up to {MAX_NUM_IMAGES} images.")
|
125 |
return False
|
126 |
|
127 |
+
# <image> ํ๊ทธ๊ฐ ์์ ๊ฒฝ์ฐ, ์ด๋ฏธ์ง ์์ ํ๊ทธ ์ ์ผ์น
|
|
|
|
|
|
|
128 |
if "<image>" in message["text"]:
|
|
|
129 |
if message["text"].count("<image>") != new_image_count:
|
130 |
gr.Warning("The number of <image> tags in the text does not match the number of images.")
|
131 |
return False
|
132 |
|
133 |
return True
|
134 |
|
135 |
+
###################################################################
|
136 |
+
# ๋์์ ์ฒ๋ฆฌ (๊ธฐ์กด)
|
137 |
+
###################################################################
|
138 |
def downsample_video(video_path: str) -> list[tuple[Image.Image, float]]:
|
139 |
vidcap = cv2.VideoCapture(video_path)
|
140 |
fps = vidcap.get(cv2.CAP_PROP_FPS)
|
|
|
155 |
vidcap.release()
|
156 |
return frames
|
157 |
|
|
|
158 |
def process_video(video_path: str) -> list[dict]:
|
159 |
content = []
|
160 |
frames = downsample_video(video_path)
|
|
|
167 |
logger.debug(f"{content=}")
|
168 |
return content
|
169 |
|
170 |
+
###################################################################
|
171 |
+
# <image> ํ๊ทธ interleaved ์ด๋ฏธ์ง ์ฒ๋ฆฌ (๊ธฐ์กด)
|
172 |
+
###################################################################
|
173 |
def process_interleaved_images(message: dict) -> list[dict]:
|
174 |
logger.debug(f"{message['files']=}")
|
175 |
parts = re.split(r"(<image>)", message["text"])
|
|
|
190 |
logger.debug(f"{content=}")
|
191 |
return content
|
192 |
|
193 |
+
###################################################################
|
194 |
+
# ์ user message ์ฒ๋ฆฌ (PDF + CSV + ์ด๋ฏธ์ง/๋น๋์ค)
|
195 |
+
###################################################################
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
196 |
def process_new_user_message(message: dict) -> list[dict]:
|
|
|
|
|
|
|
197 |
if not message["files"]:
|
198 |
return [{"type": "text", "text": message["text"]}]
|
199 |
|
200 |
+
# PDF ํ์ผ ๋ชฉ๋ก
|
201 |
pdf_files = [f for f in message["files"] if f.endswith(".pdf")]
|
202 |
+
# CSV ํ์ผ ๋ชฉ๋ก
|
203 |
+
csv_files = [f for f in message["files"] if f.lower().endswith(".csv")]
|
204 |
+
# ์ด๋ฏธ์ง/๋น๋์ค (๊ธฐ์กด)
|
205 |
+
other_files = [f for f in message["files"]
|
206 |
+
if not f.endswith(".pdf") and not f.lower().endswith(".csv")]
|
207 |
|
208 |
+
# ์ผ๋จ ์ฌ์ฉ์์ text๋ฅผ ๋จผ์ ๋ฃ๋๋ค
|
209 |
content_list = [{"type": "text", "text": message["text"]}]
|
210 |
|
211 |
+
# [PDF] ๋ณํ ํ ์ถ๊ฐ
|
212 |
for pdf_path in pdf_files:
|
213 |
pdf_markdown = pdf_to_markdown(pdf_path)
|
214 |
if pdf_markdown.strip():
|
|
|
216 |
else:
|
217 |
content_list.append({"type": "text", "text": "(PDF์์ ํ
์คํธ ์ถ์ถ ์คํจ)"})
|
218 |
|
219 |
+
# [CSV] ๋ณํ ํ ์ถ๊ฐ
|
220 |
+
for cfile in csv_files:
|
221 |
+
csv_md = csv_to_markdown(cfile)
|
222 |
+
content_list.append({"type": "text", "text": csv_md})
|
223 |
|
224 |
+
# ์์ ์ฒ๋ฆฌ
|
225 |
video_files = [f for f in other_files if f.endswith(".mp4")]
|
226 |
if video_files:
|
|
|
|
|
227 |
content_list += process_video(video_files[0])
|
228 |
return content_list
|
229 |
|
|
|
238 |
|
239 |
return content_list
|
240 |
|
241 |
+
###################################################################
|
242 |
+
# ํ์คํ ๋ฆฌ -> LLM์ฉ ๋ฉ์์ง ๋ณํ (๊ธฐ์กด)
|
243 |
+
###################################################################
|
244 |
def process_history(history: list[dict]) -> list[dict]:
|
245 |
messages = []
|
246 |
current_user_content: list[dict] = []
|
|
|
258 |
current_user_content.append({"type": "image", "url": content[0]})
|
259 |
return messages
|
260 |
|
261 |
+
###################################################################
|
262 |
+
# ๋ฉ์ธ ์ถ๋ก ํจ์ (๊ธฐ์กด)
|
263 |
+
###################################################################
|
264 |
@spaces.GPU(duration=120)
|
265 |
def run(message: dict, history: list[dict], system_prompt: str = "", max_new_tokens: int = 512) -> Iterator[str]:
|
266 |
if not validate_media_constraints(message, history):
|
|
|
295 |
output += delta
|
296 |
yield output
|
297 |
|
298 |
+
###################################################################
|
299 |
+
# ์์๋ค (๊ธฐ์กด ๊ทธ๋๋ก)
|
300 |
+
###################################################################
|
301 |
examples = [
|
302 |
[
|
303 |
{
|
|
|
420 |
],
|
421 |
]
|
422 |
|
423 |
+
###################################################################
|
424 |
+
# PDF + CSV๋ฅผ ํ์ฉํ๋ Gradio ChatInterface
|
425 |
+
###################################################################
|
426 |
demo = gr.ChatInterface(
|
427 |
fn=run,
|
428 |
type="messages",
|
429 |
chatbot=gr.Chatbot(type="messages", scale=1, allow_tags=["image"]),
|
430 |
textbox=gr.MultimodalTextbox(
|
431 |
+
file_types=["image", ".mp4", ".pdf", ".csv"], # pdf & csv ํ์ฉ
|
432 |
file_count="multiple",
|
433 |
autofocus=True
|
434 |
),
|
435 |
multimodal=True,
|
436 |
additional_inputs=[
|
437 |
+
gr.Textbox(
|
438 |
+
label="System Prompt",
|
439 |
+
value=(
|
440 |
+
"You are a deeply thoughtful AI. Consider problems thoroughly and derive correct "
|
441 |
+
"solutions through systematic reasoning. Please answer in korean."
|
442 |
+
)
|
443 |
+
),
|
444 |
+
gr.Slider(
|
445 |
+
label="Max New Tokens",
|
446 |
+
minimum=100,
|
447 |
+
maximum=8000,
|
448 |
+
step=50,
|
449 |
+
value=2000
|
450 |
+
),
|
451 |
],
|
452 |
stop_btn=False,
|
453 |
title="Gemma 3 27B IT",
|