Spaces:
Sleeping
Sleeping
File size: 44,506 Bytes
f6f4388 862e4a8 f6f4388 862e4a8 f6f4388 862e4a8 f6f4388 862e4a8 f6f4388 862e4a8 f6f4388 862e4a8 f6f4388 862e4a8 f6f4388 862e4a8 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 |
import json
import os
import shutil
import time
from typing import Tuple
import cv2
import base64
import uuid
import re
from flask import Flask
import gradio as gr
from google import genai
# --- Config ν΄λμ€ (Gemma, GPT4o μ κ±°, Qwenλ§ μ¬μ©) ---
class Config:
"""μ ν리μΌμ΄μ
μ€μ λ° μμ"""
FOOD_ITEMS = [
{"name": "μ§μ₯λ©΄", "image": "images/food1.jpg", "price": 7.00},
{"name": "짬λ½", "image": "images/food2.jpg", "price": 8.50},
{"name": "νμμ‘", "image": "images/food3.jpg", "price": 15.00},
{"name": "λ³Άμλ°₯", "image": "images/food4.jpg", "price": 7.50},
{"name": "κΉνκΈ°", "image": "images/food5.jpg", "price": 18.00},
{"name": "λ§νλλΆ", "image": "images/food6.jpg", "price": 12.00},
{"name": "μ½λΌ", "image": "images/food6.jpg", "price": 12.00},
{"name": "μ¬μ΄λ€", "image": "images/food6.jpg", "price": 12.00},
]
# μ리λ°λ° Qwen API ν€ (κΈ°λ³Έκ°μ λΉ λ¬Έμμ΄)
QWEN_API_KEY = "sk-2424f0bd26d64fe5a7f3a2bd407adc76"
GEMINI_API_key = "AIzaSyCc8lcm2cZo3ZeMgi4QN1IHSvn9BBpLnz4"
DEFAULT_PROMPT_TEMPLATE = (
"""
### Persona ###
You are an expert tip calculation assistant focusing on service quality observed in video captions, and you also consider the user's review, star rating, and recent Google reviews.
Your role is to evaluate all these aspects, assign scores, and calculate the overall average score to determine the appropriate tip percentage, with special handling for ethical violations.
### Task ###
1. **Video Analysis**: Analyze the service quality depicted in the provided **Video Caption(s)**. If multiple captions are given, perform a **holistic evaluation** based on the overall impression conveyed by all captions combined. **Focus on significant staff actions, expressions, and interactions described across the captions.** Assign a single, overall **Video Service Score** out of 100 based on this comprehensive analysis, rather than averaging scores from individual captions.
2. **Bill Amount Determination**: Determine the bill amount by following these steps:
* Use the 'Calculated Subtotal' provided.
3. **Overall Service Quality Evaluation**:
Evaluate the service quality by evenly scoring the following four components, each out of 100:
a) **Video Service Score**: Service quality derived from the holistic analysis of Video Caption(s).
b) **Google Review Score**: Provide an overall analysis of the recent Google reviews and give the general rating score. Highlight any significant social issues mentioned, such as racist comments or discriminatory behavior. The analysis should consider all reviews collectively.
* **Note**: If any review mentions racist, sexist, or any other ethical violations, the Google Review score must automatically be set to **0**.
c) **User Review Score**: The user's review.
d) **Star Rating Score**: The user's star rating, interpreted on a scale where 5/5 corresponds to 100 points.
* Calculate the overall average score by taking the mean of these four scores.
4. **Service Quality Classification and Tip Guidelines**:
* Based on the overall average score, classify the service quality as follows:
* Poor Service: Overall average score < 60 (Tip range: 0% ~ 5% of the bill)
* Average Service: Overall average score β₯ 60 and < 80 (Tip range: 10% ~ 15% of the bill)
* Good Service: Overall average score β₯ 80 (Tip range: 15% ~ 20% of the bill)
* Select a specific tip percentage within the appropriate range. **Exception**: If ethical violations were noted (Google Review Score is 0), the Final Tip Percentage **must be 0%**.
* Calculate the tip amount by multiplying the determined bill amount by the chosen tip percentage (round to two decimal places).
* Calculate the final total bill by adding the tip amount to the subtotal (round to two decimal places).
5. **Review Prioritization and Score Adjustment**:
* Even though all four factors are evaluated equally, if the user's review **explicitly states that specific issues previously mentioned in Google Reviews (especially ethical violations like racism) have been resolved or are no longer present**, then the Google Review score should be adjusted upwards from its potentially reduced value (e.g., from 0 back towards a score reflecting the *current* situation described by the user). The user's direct, specific, and current assessment takes precedence over older or contradicted Google Review points in such cases. Ensure the User Review Score reflects the user's sentiment.
### Ethical Violations and Tip Adjustment ###
* If there are any racist, discriminatory, or offensive remarks found in the Google reviews, regardless of the overall review sentiment or scores from other factors, the Google Review Score is automatically set to **0**. Consequently, the **Final Tip Percentage must be set to 0%** to strongly reflect the severity and unacceptability of such behavior.
### Recent Google Review ###
#### Google Review 1 ####
[4.0 stars] The atmosphere, the taste of the steak, and the service were all good. It was unique and fun to be able to choose after tasting the dessert tea and coffee. The regrettable points are: 1. The degree of meat cooking must be uniform in the course meal. Everyone has different tastes, but if the degree of cooking must be uniform because it is a course meal, I think I will consider visiting again. Those who are thinking about a course meal, please take note. 2. When serving all the course meals, they pretended not to notice that they spilled something on the table^^ and when they poured water, they spilled a lot, which was a bit embarrassing. 3. I think they could have explained it more comfortably before serving.
#### Google Review 2 ####
[4.0 stars] A steak restaurant with an American-style atmosphere. Thick tenderloin and strips served? The sound stimulated my appetite, but there was a lot of food, so I left it behind. It was a bit difficult to eat because it was undercooked in the middle. I also had stir-fried kimchi as a garnish, and it was a little sweet, so it tasted like Southeast Asia. The ice cream I had for dessert was delicious, and there was a lot of food left over.
### Video Caption Input ###
# Multiple captions can be provided under this section
Video Caption(s):
{{caption_text}}
### Output ###
Return your answer in the exact format below, providing the text analyses first, followed by the JSON block containing the final calculations:
Video Text Analysis: [Provide a summary of the **significant staff actions, expressions, and interactions** observed across all provided **Video Caption(s)**. Explain how these observations contribute to the overall service impression. Include the single, **holistically determined Video Service Score** (out of 100) based on this combined analysis.]
Recent Google Review Analysis: [Summary of the insights from the Google Reviews, including any negative or racist comments, with the assigned score (out of 100). If ethical violations result in a 0 score, state this clearly.]
User Review Analysis: [Summary of the user's review including any improvements or enhanced service mentions, with the assigned score (out of 100). Note if this review led to adjustments in the Google Review score based on explicit statements about resolved issues.]
Star Rating Analysis: [Interpret the user's star rating (e.g., converting 5/5 to 100 points) and include the assigned score (out of 100).]
Overall Analysis: [Step-by-step explanation detailing:
- How the bill amount was determined;
- How each of the four components was scored, including the holistic evaluation of video captions and any adjustments made to the Google Review score based on specific user statements about resolved issues;
- If any review mentioned racist, sexist, or other ethical violations, explicitly state that the Google Review score was set to 0 and the **Final Tip Percentage is consequently set to 0%**, reflecting the severity;
- How the overall average score was calculated;
- The reasoning for the final service quality classification based on the average score;
- How the final tip percentage was chosen (either based on the guideline range or mandatorily set to 0% due to ethical violations) and the detailed calculation for the tip amount and final total bill.
### Final Calculation Results (JSON Format) ###
```json
{{{{
"final_tip_percentage": <calculated_percentage_int>,
"final_tip_amount": <calculated_tip_float>,
"final_total_bill": <calculated_total_bill_float>
}}}}
```
### GUIDE ###
In Final Answer, The ### Final Calculation Results (JSON Format) ### section must strictly follow the JSON structure provided above, containing only the JSON object and its calculated numerical values (use floating-point numbers for all values). **DO NOT include the placeholders like <calculated_percentage_float> in the actual final output; replace them with the real calculated numbers.** Ensure no other special characters like **, $, % are used *within* the JSON structure itself, only standard JSON syntax (keys in double quotes, string values in double quotes, numbers without quotes). The text analysis sections preceding the JSON should still follow their specified format.
Complete all the text analysis and overall analysis sections first, and generate the ### Final Calculation Results (JSON Format) ### section last.
**THIS INSTRUCTION ENSURES THAT ONLY THE NECESSARY SPECIAL CHARACTERS THAT ARE PART OF THE REQUIRED OUTPUT FORMAT (E.G., standard JSON syntax) ARE USED, AND ANY OTHER SPECIAL CHARACTERS SUCH AS **, $, %, LATEX COMMANDS, OR ANY NON-STANDARD CHARACTERS SHOULD BE EXCLUDED FROM THE FINAL JSON BLOCK.**
### User Context ###
* Current Country: USA
* Currently Restaurant Name: The Golden Spoon (Assumed)
* Currently Calculated Subtotal: ${calculated_subtotal:.2f}
* Currently User Star Rating: {star_rating} / 5 (5 is the maximum)
* Currently User Review: {user_review}
"""
)
CUSTOM_CSS = """
#food-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
overflow-y: auto;
height: 600px;
}
#qwen-button {
background-color: #8A2BE2 !important;
color: white !important;
border-color: #8A2BE2 !important;
}
#qwen-button:hover {
background-color: #7722CC !important;
}
#google-button {
background-color: #50C878 !important;
color: white !important;
border-color: #50C878 !important;
}
#google-button:hover {
background-color: #3CB371 !important;
}
"""
def __init__(self):
if not os.path.exists("images"):
print("κ²½κ³ : 'images' ν΄λλ₯Ό μ°Ύμ μ μμ΅λλ€. μμ μ΄λ―Έμ§κ° νμλμ§ μμ μ μμ΅λλ€.")
for item in self.FOOD_ITEMS:
if not os.path.exists(item["image"]):
print(f"κ²½κ³ : μ΄λ―Έμ§ νμΌμ μ°Ύμ μ μμ΅λλ€ - {item['image']}")
# --- ModelClients (μ리λ°λ° Qwen APIλ§ μ¬μ©) ---
class ModelClients:
def __init__(self, config: Config):
self.config = config
from openai import OpenAI as QwenOpenAI
self.qwen_client = QwenOpenAI(
api_key=config.QWEN_API_KEY,
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
self.gemini_client = genai.Client(api_key=config.GEMINI_API_key)
def encode_video_qwen(self, video_path):
with open(video_path, "rb") as video_file:
return base64.b64encode(video_file.read()).decode("utf-8")
# --- VideoProcessor: λΉλμ€ νλ μ μΆμΆ ---
class VideoProcessor:
def extract_video_frames(self, video_path, output_folder=None, fps=1):
if not video_path:
return [], None
if output_folder is None:
output_folder = f"frames_list/frames_{uuid.uuid4().hex}"
os.makedirs(output_folder, exist_ok=True)
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"μ€λ₯: λΉλμ€ νμΌμ μ΄ μ μμ΅λλ€ - {video_path}")
return [], None
frame_paths = []
frame_rate = cap.get(cv2.CAP_PROP_FPS)
if not frame_rate or frame_rate == 0:
print("κ²½κ³ : FPSλ₯Ό μ½μ μ μμ΅λλ€, κΈ°λ³Έκ° 4μΌλ‘ μ€μ ν©λλ€.")
frame_rate = 4.0
frame_interval = int(frame_rate / fps) if fps > 0 else 1
if frame_interval <= 0:
frame_interval = 1
frame_count = 0
saved_frame_count = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
if frame is None:
print(f"κ²½κ³ : {frame_count}λ²μ§Έ νλ μμ΄ λΉμ΄μμ΅λλ€.")
frame_count += 1
continue
if frame_count % frame_interval == 0:
frame_path = os.path.join(output_folder, f"frame_{saved_frame_count}.jpg")
try:
if cv2.imwrite(frame_path, frame):
frame_paths.append(frame_path)
saved_frame_count += 1
else:
print(f"κ²½κ³ : {frame_path} μ μ₯ μ€ν¨.")
except Exception as e:
print(f"κ²½κ³ : νλ μ μ μ₯ μ€λ₯ ({frame_path}): {e}")
frame_count += 1
cap.release()
if not frame_paths:
print("κ²½κ³ : νλ μ μΆμΆ μ€ν¨.")
if os.path.exists(output_folder):
shutil.rmtree(output_folder)
return [], None
return frame_paths, output_folder
def cleanup_temp_files(self, video_path, frame_folder):
if video_path and "temp_video_" in video_path and os.path.exists(video_path):
try:
os.remove(video_path)
print(f"μμ λΉλμ€ νμΌ μμ : {video_path}")
except OSError as e:
print(f"μμ λΉλμ€ νμΌ μμ μ€λ₯: {e}")
if frame_folder and os.path.exists(frame_folder):
try:
shutil.rmtree(frame_folder)
print(f"νλ μ ν΄λ μμ : {frame_folder}")
except OSError as e:
print(f"νλ μ ν΄λ μμ μ€λ₯: {e}")
# --- TipCalculator (μ리λ°λ° Qwen APIλ₯Ό μ¬μ©ν ν κ³μ°) ---
class TipCalculator:
def __init__(self, config: Config, model_clients: ModelClients, video_processor: VideoProcessor):
self.config = config
self.model_clients = model_clients
self.video_processor = video_processor
def parse_llm_output(self, output_text: str) -> Tuple[str, float, float, float, str]:
analysis = "Analysis not found."
tip_percentage = 0.0
tip_amount = 0.0
total_bill = 0.0
# ------------------------------------------------------------------
# 1) JSON λΈλ‘ νμ ```json ... ``` λλ { "final_tip_percentage": ... }
# ------------------------------------------------------------------
json_block = None
# 1βA) ```json ... ``` ν¨ν΄
m = re.search(r"```json\s*(\{.*?\})\s*```", output_text, re.DOTALL | re.IGNORECASE)
if not m:
# 1βB) λ°±ν±μ΄ μλ κ²½μ°, 첫 λ²μ§Έ { ... } μ€μ key κ° ν¬ν¨λΌ μμΌλ©΄ μ‘κΈ°
m = re.search(r"(\{[^{}]*\"final_tip_percentage\"[^{}]*\})", output_text,
re.DOTALL | re.IGNORECASE)
if m:
json_block = m.group(1)
try:
json_data = json.loads(json_block)
tip_percentage = float(json_data.get("final_tip_percentage", 0.0))
tip_amount = float(json_data.get("final_tip_amount", 0.0))
total_bill = float(json_data.get("final_total_bill", 0.0))
except (ValueError, json.JSONDecodeError) as e:
print(f"[WARN] JSON νμ± μ€ν¨: {e}")
# ------------------------------------------------------------------
# 2) JSONμ΄ μμΌλ©΄ ꡬ(θ) ν¬λ§·(**Final Tip β¦**)μΌλ‘ νμ±
# ------------------------------------------------------------------
if json_block is None:
# Tip %
m = re.search(r"\*\*Final Tip Percentage\*\*:\s*([0-9]+(?:\.[0-9]+)?)%", output_text,
re.IGNORECASE)
if m:
tip_percentage = float(m.group(1))
# Tip Amount
m = re.search(r"\*\*Final Tip Amount\*\*:\s*\$?\s*([0-9]+(?:\.[0-9]+)?)", output_text,
re.IGNORECASE)
if m:
tip_amount = float(m.group(1))
# Total Bill
m = re.search(r"\*\*Final Total Bill\*\*:\s*\$?\s*([0-9]+(?:\.[0-9]+)?)", output_text,
re.IGNORECASE)
if m:
total_bill = float(m.group(1))
# ------------------------------------------------------------------
# 3) Analysis μΆμΆ (JSON λΈλ‘ μλΆλΆμ κ·Έλλ‘ μ°κ±°λ, ν€μλλ‘ νμ±)
# ------------------------------------------------------------------
if json_block:
analysis_part = output_text.split(json_block)[0] # JSON μ ν
μ€νΈ
else:
analysis_part = output_text
# βAnalysis:β λλ βOverall Analysis:β μ΄νλ§ μλΌ μ£Όλ©΄ λ κΉλ
m = re.search(r"(?:Overall\s+Analysis|Analysis):\s*(.*)", analysis_part,
re.DOTALL | re.IGNORECASE)
if m:
analysis = m.group(1).strip()
else:
analysis = analysis_part.strip()
return analysis, tip_percentage, tip_amount, output_text
def process_tip_qwen(self, video_file_path, star_rating, user_review, calculated_subtotal, custom_prompt=None):
if not os.path.exists(video_file_path):
return "Error: λΉλμ€ νμΌ κ²½λ‘κ° μ ν¨νμ§ μμ΅λλ€.", 0.0, 0.0, [], None, ""
base64_video = self.model_clients.encode_video_qwen(video_file_path)
omni_caption_prompt = '''
Task 1: Describe the waiters' actions in these restaurant video frames. Please check for mistakes or negative behaviors.
Task 2: Provide a short chronological summary of the entire scene.
'''
omni_result = self.model_clients.qwen_client.chat.completions.create(
model="qwen2.5-omni-7b",
messages=[
{
"role": "system",
"content": [{"type": "text", "text": "You are a helpful assistant."}],
},
{
"role": "user",
"content": [
{"type": "video_url", "video_url": {"url": f"data:;base64,{base64_video}"}},
{"type": "text", "text": omni_caption_prompt},
],
},
],
modalities=["text"],
stream=True,
stream_options={"include_usage": True},
)
all_omni_chunks = list(omni_result)
caption_text = ""
for chunk in all_omni_chunks[:-1]:
if not chunk.choices:
continue
if chunk.choices[0].delta.content:
caption_text += chunk.choices[0].delta.content
if not caption_text.strip():
caption_text = "(No caption from Omni)"
user_review = user_review.strip() if user_review else "(No user review)"
if custom_prompt is None:
prompt = self.config.DEFAULT_PROMPT_TEMPLATE.format(
calculated_subtotal=calculated_subtotal,
star_rating=star_rating,
user_review=user_review
)
else:
try:
prompt = custom_prompt.format(
calculated_subtotal=calculated_subtotal,
star_rating=star_rating,
user_review=user_review
)
except:
prompt = self.config.DEFAULT_PROMPT_TEMPLATE.format(
calculated_subtotal=calculated_subtotal,
star_rating=star_rating,
user_review=user_review
)
final_prompt = prompt.replace("{caption_text}", caption_text)
qvq_result = self.model_clients.qwen_client.chat.completions.create(
model="qwen2.5-vl-32b-instruct",
messages=[
{"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]},
{"role": "user", "content": [{"type": "text", "text": final_prompt}]},
],
modalities=["text"],
stream=True,
)
all_qvq_chunks = list(qvq_result)
final_reasoning = ""
final_answer = ""
is_answering = False
for c in all_qvq_chunks[:-1]:
if not c.choices:
continue
d = c.choices[0].delta
if hasattr(d, "reasoning_content") and d.reasoning_content:
final_reasoning += d.reasoning_content
if d.content:
if not is_answering:
print("\n" + "=" * 20 + "Complete Response" + "=" * 20 + "\n")
is_answering = True
final_answer += d.content
final_text = final_reasoning + "\n" + final_answer
analysis, tip_percentage, tip_amount, output_text = self.parse_llm_output(final_text)
return analysis, tip_percentage, tip_amount, [], None, output_text
def process_tip_gemini(self, video_file_path, star_rating, user_review, calculated_subtotal, custom_prompt=None):
if not video_file_path or not os.path.exists(video_file_path):
return "λΉλμ€ νμΌ κ²½λ‘κ° μ ν¨νμ§ μμ΅λλ€.", [], None
image_captioning_prompt = '''
Task 1: Describe the actions of any waiters or staff visible in these restaurant video. Note any specific interactions, mistakes, or positive actions.
Task 2: Provide a concise overall summary of the scene depicted in the frames, in chronological order if possible.
Task 1 Output:
Task 2 Output:
'''
video_file = self.model_clients.gemini_client.files.upload(file=video_file_path)
print(f"Uploaded file info: {video_file}")
# λμμμ μ²λ¦¬ μ€(Processing) μνμ΄λ―λ‘, ACTIVE μνκ° λ λκΉμ§ λκΈ°ν©λλ€.
while video_file.state.name == "PROCESSING":
print("λμμ μ²λ¦¬ μ€...")
time.sleep(1) # μ: 5μ΄λ§λ€ μν μ κ²
video_file = self.model_clients.gemini_client.files.get(name=video_file.name)
# μ²λ¦¬ μ€ν¨ μ¬λΆ νμΈ
if video_file.state.name == "FAILED":
raise ValueError(f"νμΌ μ²λ¦¬ μ€ν¨: {video_file.state.name}")
# λΉλμ€λ₯Ό ν둬ννΈμ ν¬ν¨ν΄μ μΆλ‘ μμ²
try:
caption_summary = self.model_clients.gemini_client.models.generate_content(
model="gemini-2.0-flash-lite", # μμ: Gemini 2.0 Flash λͺ¨λΈ μ¬μ©
contents=[video_file, image_captioning_prompt]
)
caption_summary = caption_summary.text
except Exception as e:
print(f"λ‘컬 λͺ¨λΈ νλ μ μ²λ¦¬ μ€λ₯: {e}")
return f"Error in processing frames with local model: {e}", None, None
user_review = user_review.strip() if user_review and user_review.strip() else "(No user review provided)"
if custom_prompt is None:
prompt = self.config.DEFAULT_PROMPT_TEMPLATE.format(
calculated_subtotal=calculated_subtotal, star_rating=star_rating, user_review=user_review
)
else:
try:
prompt = custom_prompt.format(
calculated_subtotal=calculated_subtotal, star_rating=star_rating, user_review=user_review
)
except KeyError as e:
print(f"κ²½κ³ : 컀μ€ν
ν둬ννΈμ νμν ν€κ° μμ΅λλ€: {e}. κΈ°λ³Έ ν
νλ¦Ώμ μ¬μ©ν©λλ€.")
prompt = self.config.DEFAULT_PROMPT_TEMPLATE.format(
calculated_subtotal=calculated_subtotal, star_rating=star_rating, user_review=user_review
)
final_prompt = prompt.replace("{caption_text}", caption_summary)
messages = final_prompt
video_file = self.model_clients.gemini_client.files.upload(file=video_file_path)
print(f"Uploaded file info: {video_file}")
# λμμμ μ²λ¦¬ μ€(Processing) μνμ΄λ―λ‘, ACTIVE μνκ° λ λκΉμ§ λκΈ°ν©λλ€.
while video_file.state.name == "PROCESSING":
print("λμμ μ²λ¦¬ μ€...")
time.sleep(1) # μ: 5μ΄λ§λ€ μν μ κ²
video_file = self.model_clients.gemini_client.files.get(name=video_file.name)
# μ²λ¦¬ μ€ν¨ μ¬λΆ νμΈ
if video_file.state.name == "FAILED":
raise ValueError(f"νμΌ μ²λ¦¬ μ€ν¨: {video_file.state.name}")
response = self.model_clients.gemini_client.models.generate_content(
model="gemini-2.0-flash-lite", # μμ: Gemini 2.0 Flash λͺ¨λΈ μ¬μ©
contents=[video_file, messages]
)
llm_output = response.text
analysis, tip_percentage, tip_amount, output_text = self.parse_llm_output(llm_output)
return analysis, tip_percentage, tip_amount, [], None, output_text
def calculate_manual_tip(self, tip_percent, subtotal):
tip_amount = subtotal * (tip_percent / 100)
total_bill = subtotal + tip_amount
analysis_output = f"Manual calculation using fixed tip percentage of {tip_percent}%."
tip_output = f"${tip_amount:.2f} ({tip_percent:.1f}%)"
total_bill_output = f"${total_bill:.2f}"
return analysis_output, tip_output, total_bill_output
# --- UIHandler: Gradio μΈν°νμ΄μ€ μ΄λ²€νΈ μ²λ¦¬ (μ리λ°λ° API ν€ μ
λ ₯ ν¬ν¨) ---
class UIHandler:
def __init__(self, config: Config, tip_calculator: TipCalculator, video_processor: VideoProcessor):
self.config = config
self.tip_calculator = tip_calculator
self.video_processor = video_processor
def update_subtotal_and_prompt(self, *args):
num_food_items = len(self.config.FOOD_ITEMS)
quantities = args[:num_food_items]
star_rating = args[num_food_items]
user_review = args[num_food_items + 1]
calculated_subtotal = 0.0
for i in range(num_food_items):
calculated_subtotal += self.config.FOOD_ITEMS[i]['price'] * quantities[i]
user_review_text = user_review.strip() if user_review and user_review.strip() else "(No user review provided)"
updated_prompt = self.config.DEFAULT_PROMPT_TEMPLATE.format(
calculated_subtotal=calculated_subtotal,
star_rating=star_rating,
user_review=user_review_text
)
updated_prompt = updated_prompt.replace("{caption_text}", "{{caption_text}}")
return calculated_subtotal, updated_prompt
def compute_tip(self, type, video_file_obj, subtotal, star_rating, user_review, custom_prompt_text):
analysis_output = "κ³μ°μ μμν©λλ€..."
tip_percentage = 0.0
tip_output = "$0.00"
total_bill_output = f"${subtotal:.2f}"
if video_file_obj is None:
return "μ€λ₯: λΉλμ€ νμΌμ μ
λ‘λν΄μ£ΌμΈμ.", "$0.00", total_bill_output, custom_prompt_text, gr.update(value=None)
try:
temp_video_path = f"temp_video_{uuid.uuid4().hex}.mp4"
original_path = video_file_obj.name if hasattr(video_file_obj, 'name') else video_file_obj
shutil.copyfile(original_path, temp_video_path)
print(f"μμ λΉλμ€ νμΌ μμ±: {temp_video_path}")
except Exception as e:
print(f"μμ λΉλμ€ νμΌ μμ± μ€λ₯: {e}")
return f"μ€λ₯: λΉλμ€ νμΌμ μ²λ¦¬ν μ μμ΅λλ€: {e}", "$0.00", total_bill_output, custom_prompt_text, None
frame_folder = None
try:
if type == 'qwen':
analysis, tip_percentage, tip_amount, _, _, output_text = self.tip_calculator.process_tip_qwen(
temp_video_path, star_rating, user_review, subtotal, custom_prompt_text
)
else:
analysis, tip_percentage, tip_amount, _, _, output_text = self.tip_calculator.process_tip_gemini(
temp_video_path, star_rating, user_review, subtotal, custom_prompt_text
)
if "Error" in analysis:
analysis_output = analysis
tip_amount = 0.0
else:
analysis_output = f"Tip Percentage: {tip_percentage:.1f}%\n\n{output_text}"
tip_output = f"${tip_amount:.2f} ({tip_percentage:.1f}%)"
total_bill = subtotal + tip_amount
total_bill_output = f"${total_bill:.2f}"
except Exception as e:
print(f"ν κ³μ° μ€ μ€λ₯ λ°μ (qwen): {e}")
analysis_output = f"μ€λ₯ λ°μ: {e}"
tip_output = "$0.00"
total_bill_output = f"${subtotal:.2f}"
finally:
self.video_processor.cleanup_temp_files(temp_video_path, frame_folder)
return analysis_output, tip_output, total_bill_output, custom_prompt_text, gr.update(value=None)
def auto_tip_and_invoice(self, type, video_file_obj, subtotal, star_rating, review, prompt, *quantities):
analysis, tip_disp, total_bill_disp, prompt_out, vid_out = self.compute_tip(
type, video_file_obj, subtotal, star_rating, review, prompt
)
invoice = self.update_invoice_summary(*quantities, tip_disp, total_bill_disp)
return analysis, tip_disp, total_bill_disp, prompt_out, vid_out, invoice
def update_invoice_summary(self, *args):
num_items = len(self.config.FOOD_ITEMS)
quantities = args[:num_items]
if len(args) >= num_items + 2:
tip_str = args[num_items]
total_bill_str = args[num_items + 1]
else:
tip_str = "$0.00"
total_bill_str = "$0.00"
summary = ""
for i, q in enumerate(quantities):
try:
q_val = float(q)
except:
q_val = 0
if q_val > 0:
item = self.config.FOOD_ITEMS[i]
total_price = item['price'] * q_val
summary += f"{item['name']} x{int(q_val)} : ${total_price:.2f}\n"
if summary == "":
summary = "μ£Όλ¬Έν λ©λ΄κ° μμ΅λλ€."
summary += f"\nTip: {tip_str}\nTotal Bill: {total_bill_str}"
return summary
def manual_tip_and_invoice(self, tip_percent, subtotal, *quantities):
analysis, tip_disp, total_bill_disp = self.tip_calculator.calculate_manual_tip(tip_percent, subtotal)
invoice = self.update_invoice_summary(*quantities, tip_disp, total_bill_disp)
return analysis, tip_disp, total_bill_disp, invoice
def process_payment(self, total_bill):
return f"{total_bill} κ²°μ λμμ΅λλ€."
# --- App: λͺ¨λ μ»΄ν¬λνΈ μ°κ²° λ° Gradio μΈν°νμ΄μ€ μ€ν ---
class App:
def __init__(self):
self.config = Config()
self.model_clients = ModelClients(self.config)
self.video_processor = VideoProcessor()
self.tip_calculator = TipCalculator(self.config, self.model_clients, self.video_processor)
self.ui_handler = UIHandler(self.config, self.tip_calculator, self.video_processor)
self.flask_app = Flask(__name__)
def create_gradio_blocks(self):
with gr.Blocks(title="Video Tip Calculation Interface", theme=gr.themes.Soft(),
css=self.config.CUSTOM_CSS) as interface:
gr.Markdown("## Video Tip Calculation Interface (Structured)")
# --- μ»΄ν¬λνΈ λ³μ μ μΈ (ν ꡬ쑰 μμμ μ μλ κ²μ) ---
# μ΄ λ³μλ€μ μλ ν λ΄λΆμμ μ€μ μ»΄ν¬λνΈμ ν λΉλ©λλ€.
quantity_inputs = []
subtotal_display = gr.Number(label="Subtotal ($)", value=0.0, interactive=False, visible=False)
subtotal_visible_display_output = None
review_input, rating_input = None, None
btn_5, btn_10, btn_15, btn_20, btn_25 = None, None, None, None, None
qwen_btn = None
gemini_btn = None
tip_display, total_bill_display, payment_btn, payment_result = None, None, None, None
video_input = None
analysis_display, order_summary_display = None, None
prompt_editor = None # ν둬ννΈ μλν°λ λ€λ₯Έ νμ μ μλ κ²μ
# --- μ΅μμ λ 벨μ ν κ΅¬μ± ---
with gr.Tabs():
# --- ν 1: λ©μΈ μΈν°νμ΄μ€ (μλ λ μ΄μμ μ μ§) ---
with gr.TabItem("Main Interface"):
# μ΄ ν μμ μλμ 2λ¨ λ μ΄μμμ κ·Έλλ‘ μ¬ν
with gr.Row():
# --- μΌμͺ½ μ΄ (μλλλ‘) ---
with gr.Column(scale=2):
gr.Markdown("### 1. Select Food Items")
with gr.Column(elem_id="food-container"):
for item in self.config.FOOD_ITEMS:
with gr.Column():
gr.Image(value=item["image"], label=None, show_label=False, width=150,
height=150, interactive=False)
gr.Markdown(f"**{item['name']}** (${item['price']:.2f})")
q_input = gr.Number(label="Qty", value=0, minimum=0, step=1,
elem_id=f"qty_{item['name'].replace(' ', '_')}")
quantity_inputs.append(q_input)
gr.Markdown("### Subtotal")
subtotal_visible_display_output = gr.Textbox(value="$0.00", label="Subtotal",
interactive=False)
gr.Markdown("### 2. Service Feedback")
review_input = gr.Textbox(label="Review", placeholder="μλΉμ€ 리뷰 μμ±", lines=3)
rating_input = gr.Radio(choices=[1, 2, 3, 4, 5], value=3, label="βStar Rating (1-5)β",
type="value")
gr.Markdown("### 3. Calculate Tip (Manual)")
with gr.Row():
btn_5 = gr.Button("5%")
btn_10 = gr.Button("10%")
btn_15 = gr.Button("15%")
btn_20 = gr.Button("20%")
btn_25 = gr.Button("25%")
with gr.Row():
# Qwen λ²νΌ μ μλ₯Ό μ¬κΈ°λ‘ μ΄λ!
gemini_btn = gr.Button("Google-Gemini AI Tip Calculation", variant="secondary", elem_id="google-button")
qwen_btn = gr.Button("Alibaba-Qwen AI Tip Calculation", variant="primary",
elem_id="qwen-button")
gr.Markdown("### 4. Results")
tip_display = gr.Textbox(label="Calculated Tip", value="$0.00", interactive=False)
total_bill_display = gr.Textbox(label="Total Bill (Subtotal + Tip)", value="$0.00",
interactive=False)
payment_btn = gr.Button("κ²°μ νκΈ°")
payment_result = gr.Textbox(label="Payment Result", value="", interactive=False)
# --- μ€λ₯Έμͺ½ μ΄ (μλλλ‘, ν둬ννΈ λμ€νλ μ΄ μ μΈ) ---
with gr.Column(scale=1):
gr.Markdown("### 5. Upload & Prompt Access")
video_input = gr.Video(label="Upload Service Video")
gr.Markdown("### 6. AI Analysis")
analysis_display = gr.Textbox(label="AI Analysis", lines=8, max_lines=12, interactive=False)
gr.Markdown("### 7. μ²κ΅¬μ")
order_summary_display = gr.Textbox(label="μ²κ΅¬μ", value="μ£Όλ¬Έ λ©λ΄ μμ", lines=8, max_lines=12,
interactive=False)
# --- ν 2: ν둬ννΈ νΈμ§ μ μ© (λκ²!) ---
with gr.TabItem("Edit Prompt"):
gr.Markdown("### Prompt Editor")
gr.Markdown("μλ μμ±λ ν둬ννΈλ₯Ό μ¬κΈ°μ νμΈνκ³ **μ§μ μμ **ν μ μμ΅λλ€. AI λΆμ μ μ¬κΈ°μ μλ μ΅μ’
λ΄μ©μ΄ μ¬μ©λ©λλ€.")
# μ΄ νμλ ν둬ννΈ νΈμ§κΈ°λ§ λ°°μΉνμ¬ κ°λ‘ λλΉλ₯Ό μ΅λν νμ©
prompt_editor = gr.Code(
label="Tip Calculation Prompt (Editable)",
language="python", # νμ΄λΌμ΄ν
μ΄ νμ μμΌλ©΄ "text"
value="Loading prompt...",
lines=35, # μΈλ‘ λμ΄.
)
gr.Examples(
examples=[
# μ
λ ₯ μμ: [Alibaba API Key, Video, Subtotal, Star Rating, Review] + [κ° μμμ Qty]
["./video/sample.mp4", 0.0, 1, "He drop the tray..so bad", 0, 0, 0, 0, 0, 2, 0, 0],
["./video/sample2.mp4", 0.0, 5, "Good service!", 0, 0, 0, 0, 0, 2, 0, 0]
],
inputs=[video_input, subtotal_display, rating_input,
review_input] + quantity_inputs,
outputs=[analysis_display, tip_display, total_bill_display, video_input, order_summary_display],
label="Example: Bad Service, Good Service"
)
# --- μ΄λ²€νΈ νΈλ€λ¬ μ°κ²° ---
# μ»΄ν¬λνΈλ€μ΄ λͺ¨λ μ μλ νμ μ°κ²°ν΄μΌ ν¨
# (μ€μ μ½λμμλ μ»΄ν¬λνΈ None μ²΄ν¬ λλ λ λμ ꡬ쑰ν νμ)
if all([subtotal_display, subtotal_visible_display_output, review_input, rating_input, prompt_editor,
order_summary_display, video_input, analysis_display, tip_display,
total_bill_display, payment_result, qwen_btn, gemini_btn] + quantity_inputs):
# 1. μκ³ μ
λ°μ΄νΈ (μ¨κ²¨μ§ Number -> 보μ΄λ Textbox)
subtotal_display.change(
fn=lambda x: f"${x:.2f}",
inputs=subtotal_display,
outputs=subtotal_visible_display_output
)
# 2. μ
λ ₯ λ³κ²½ μ -> μκ³ κ³μ° λ° ν둬ννΈ νΈμ§κΈ°('Edit Prompt' ν) μ
λ°μ΄νΈ
inputs_for_prompt_update = quantity_inputs + [rating_input, review_input]
outputs_for_prompt_update = [subtotal_display, prompt_editor] # μ¨κ²¨μ§ μκ³μ λ€λ₯Έ νμ ν둬ννΈ μλν°
for comp in inputs_for_prompt_update:
comp.change(
fn=self.ui_handler.update_subtotal_and_prompt,
inputs=inputs_for_prompt_update,
outputs=outputs_for_prompt_update
)
# 3. μλ λ³κ²½ μ -> μ²κ΅¬μ('Main Interface' ν) μ
λ°μ΄νΈ
for comp in quantity_inputs:
comp.change(
fn=self.ui_handler.update_invoice_summary,
inputs=quantity_inputs,
outputs=order_summary_display
)
# 4. AI κ³μ° λ²νΌ('Main Interface' ν) ν΄λ¦ μ
# μ
λ ₯: λ©μΈ νμ μ»΄ν¬λνΈλ€ + 'Edit Prompt' νμ prompt_editor
# μΆλ ₯: λ©μΈ νμ μ»΄ν¬λνΈλ€ + 'Edit Prompt' νμ prompt_editor (μ
λ°μ΄νΈ λ μ μμΌλ―λ‘)
qwen_btn.click(
fn=lambda vid, sub, rat, rev, prom, *qty: self.ui_handler.auto_tip_and_invoice('qwen', vid, sub,
rat, rev, prom,
*qty),
inputs=[video_input, subtotal_display, rating_input, review_input, prompt_editor] + quantity_inputs,
outputs=[analysis_display, tip_display, total_bill_display, prompt_editor, video_input,
order_summary_display]
)
gemini_btn.click(
fn=lambda vid, sub, rat, rev, prom, *qty: self.ui_handler.auto_tip_and_invoice('gemini', vid, sub,
rat, rev, prom,
*qty),
inputs=[video_input, subtotal_display, rating_input, review_input, prompt_editor] + quantity_inputs,
outputs=[analysis_display, tip_display, total_bill_display, prompt_editor, video_input,
order_summary_display]
)
# 5. μλ ν λ²νΌ('Main Interface' ν) ν΄λ¦ μ
manual_tip_outputs = [analysis_display, tip_display, total_bill_display, order_summary_display]
if btn_5: btn_5.click(fn=lambda sub, *qty: self.ui_handler.manual_tip_and_invoice(5, sub, *qty),
inputs=[subtotal_display] + quantity_inputs, outputs=manual_tip_outputs)
# ... (btn_10, btn_15, btn_20, btn_25 μ λν΄μλ λμΌνκ²)
if btn_10: btn_10.click(fn=lambda sub, *qty: self.ui_handler.manual_tip_and_invoice(10, sub, *qty),
inputs=[subtotal_display] + quantity_inputs, outputs=manual_tip_outputs)
if btn_15: btn_15.click(fn=lambda sub, *qty: self.ui_handler.manual_tip_and_invoice(15, sub, *qty),
inputs=[subtotal_display] + quantity_inputs, outputs=manual_tip_outputs)
if btn_20: btn_20.click(fn=lambda sub, *qty: self.ui_handler.manual_tip_and_invoice(20, sub, *qty),
inputs=[subtotal_display] + quantity_inputs, outputs=manual_tip_outputs)
if btn_25: btn_25.click(fn=lambda sub, *qty: self.ui_handler.manual_tip_and_invoice(25, sub, *qty),
inputs=[subtotal_display] + quantity_inputs, outputs=manual_tip_outputs)
# 6. κ²°μ λ²νΌ('Main Interface' ν) ν΄λ¦ μ
if payment_btn: payment_btn.click(
fn=self.ui_handler.process_payment,
inputs=[total_bill_display],
outputs=[payment_result]
)
else:
print("Warning: Component initialization might be out of order for event handlers.")
return interface
def run_gradio(self):
interface = self.create_gradio_blocks()
interface.launch(share=False)
def run_flask(self):
@self.flask_app.route("/")
def index():
return "Hello Flask"
self.flask_app.run(host="0.0.0.0", port=5000, debug=True)
if __name__ == "__main__":
app = App()
app.run_gradio()
|