kfkas commited on
Commit
f7425b0
·
1 Parent(s): 4299e47
Files changed (2) hide show
  1. app.py +202 -116
  2. requirements.txt +3 -1
app.py CHANGED
@@ -1,11 +1,16 @@
1
  import os
2
  import shutil
 
 
3
  import cv2
4
  import base64
5
  import uuid
6
  import re
7
  from flask import Flask
8
  import gradio as gr
 
 
 
9
 
10
  # --- Config 클래스 (Gemma, GPT4o 제거, Qwen만 사용) ---
11
  class Config:
@@ -21,57 +26,44 @@ class Config:
21
  {"name": "사이다", "image": "images/food6.jpg", "price": 12.00},
22
  ]
23
  # 알리바바 Qwen API 키 (기본값은 빈 문자열)
24
- QWEN_API_KEY = ""
25
-
26
  DEFAULT_PROMPT_TEMPLATE = (
27
- "### Persona ###\n"
28
- "You are an expert tip calculation assistant focusing on service quality observed in a video, and you also consider the user's review, star rating, and recent Google reviews. "
29
- "Your role is to evaluate all these aspects evenly by assigning each a score out of 100, then calculate the overall average score to determine the appropriate tip percentage.\n\n"
30
-
31
- "### Task ###\n"
32
- "1. **Video Analysis**: Analyze the video frames as described in the 'Video Caption' to observe the staff's actions and interactions. "
33
- "Assign a score out of 100 based on the observed service quality.\n\n"
34
-
35
- "2. **Bill Amount Determination**: Determine the bill amount by following these steps:\n"
36
- " - If an explicit bill amount is mentioned in the 'Video Caption', use it.\n"
37
- " - Otherwise, use the 'Calculated Subtotal' provided.\n"
38
- " - If neither is available, assume a default value of $50.\n\n"
39
-
40
- "3. **Overall Service Quality Evaluation**:\n"
41
- " Evaluate the service quality by evenly scoring the following four components, each out of 100:\n"
42
- " a) **Video Service Score**: Service quality observed in the video (from Video Caption).\n"
43
- " b) **Google Review Score**: Please provide an overall analysis of the recent Google reviews and give the general rating score. Highlight any significant social issues mentioned in the reviews, such as racist comments, discriminatory behavior, or other major societal concerns. The analysis should consider all reviews collectively, not individually. Regardless of the rating score, tips should be calculated very low.\n"
44
- " - **Note**: If any review mentions racist, sexist, or any other ethical violations, all Google Review scores should automatically be set to 0. This is to account for the severity of such violations. "
45
- " - Additionally, when such violations are found, the tip should be calculated **very low**, even lower than the typical range for poor service.\n"
46
- " c) **User Review Score**: The user's review (if the review mentions improvements or enhanced service, especially if it indicates that previously reported issues like racism have been resolved, adjust the negative impact accordingly).\n"
47
- " d) **Star Rating Score**: The user's star rating, interpreted on a scale where 5/5 corresponds to 100 points.\n"
48
- " - Calculate the overall average score by taking the mean of these four scores.\n\n"
49
-
50
- "4. **Service Quality Classification and Tip Guidelines**:\n"
51
- " - Based on the overall average score, classify the service quality as follows:\n"
52
- " - Poor Service: Overall average score < 60 (Tip range: 0% ~ 5% of the bill)\n"
53
- " - Average Service: Overall average score 60 and < 80 (Tip range: 10% ~ 15% of the bill)\n"
54
- " - Good Service: Overall average score 80 (Tip range: 15% ~ 20% of the bill)\n"
55
- " - Select a specific tip percentage within the appropriate range.\n"
56
- " - Calculate the tip amount by multiplying the determined bill amount by the chosen tip percentage (round to two decimal places).\n"
57
- " - Calculate the final total bill by adding the tip amount to the subtotal (round to two decimal places).\n\n"
58
-
59
- "5. **Review Prioritization and Score Adjustment**:\n"
60
- " - Even though all four factors are evaluated equally, if the user's review explicitly indicates improvements (e.g., stating 'There's no racism!' or similar phrases), then increase the Google Review score by adjusting or restoring it to a value higher than the score initially reduced due to negative comments. In other words, if improvements are noted, add a positive increment (using a '+' adjustment) to the Google Review score, ensuring it is higher than the negatively impacted value.\n"
61
- " - Ensure that the user's review score takes priority when there is a conflict with the negative tone of the Google Reviews.\n\n"
62
-
63
- "### Ethical Violations and Tip Adjustment ###\n"
64
- " - If there are any racist, discriminatory, or offensive remarks in the Google reviews, regardless of the review score, the tip should be significantly reduced. "
65
- " - In these cases, the tip should be calculated at a very low percentage, often close to 0%, to reflect the severity of such behavior. "
66
- " - This adjustment should result in an even lower tip amount than would be calculated for poor service alone.\n\n"
67
-
68
- "### User Context ###\n"
69
- " - Current Country: USA\n"
70
- " - Restaurant Name: The Golden Spoon (Assumed)\n"
71
- " - Calculated Subtotal: ${calculated_subtotal:.2f}\n"
72
- " - User Star Rating: {star_rating} / 5\n"
73
- " - Currently User Review: {user_review}\n\n"
74
-
75
  "### Recent Google Review ###\n\n"
76
 
77
  "#### Google Review 1 ####\n"
@@ -80,45 +72,50 @@ class Config:
80
  "#### Google Review 2 ####\n"
81
  "[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."
82
  "\n\n"
83
-
84
- "### Input ###\n"
85
- "Video Caption:\n{{caption_text}}\n\n"
86
-
87
- "### Output ###\n"
88
- "Return your answer in the exact format below:\n"
89
- "Video Text Analysis: [Summary of the observed actions and interactions of the staff in the video along with the assigned score (out of 100) based on video analysis.]\n"
90
- "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).]\n"
91
- "User Review Analysis: [Summary of the user's review including any improvements or enhanced service mentions, with the assigned score (out of 100).]\n"
92
- "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).]\n"
93
- "Overall Analysis: [Step-by-step explanation detailing:\n"
94
- " - How the bill amount was determined;\n"
95
- " - How each of the four components was scored and how any negative scores (e.g., for racism) were adjusted based on improvement indications in the user's review;\n"
96
- " - If any review mentions racist, sexist, or other ethical violations, the Google Review score is automatically set to 0, and a **very low** tip percentage is calculated. This reflects the severity of such violations and ensures that the tip is significantly reduced.\n"
97
- " - How the overall average score was calculated;\n"
98
- " - The reasoning for the final service quality classification based on the average score;\n"
99
- " - How the tip percentage was chosen within the guideline range and the detailed calculation for the tip amount and final total bill, taking into account the 0% tip percentage due to the ethical violations.]\n\n"
100
-
101
-
102
- "### Example Output Indicators (for reference only) ###\n"
103
- "**Final Tip Percentage**: 12.5%\n"
104
- "**Final Tip Amount**: $6.25\n"
105
- "**Final Total Bill**: $56.25\n\n"
106
-
107
- "### Example Output Indicators (for reference only) ###\n"
108
- "**Final Tip Percentage**: 12.5%\n"
109
- "**Final Tip Amount**: $6.25\n"
110
- "**Final Total Bill**: $56.25\n\n"
111
-
112
- "### Output Indicators ###\n"
113
- "**Final Tip Percentage**: [X]% (only floating point)\n"
114
- "**Final Tip Amount**: $[Calculated Tip]\n"
115
- "**Final Total Bill**: $[Subtotal + Tip]\n"
116
-
117
- "### GUIDE ###"
118
-
119
- "\n\nIn Final Answer,The ### Output Indicators ### must strictly follow the format of ### Example Output Indicators (for reference only) ###\n\n"
120
- "### FINAL ANSWER: **THIS INSTRUCTION ENSURES THAT ONLY THE NECESSARY SPECIAL CHARACTERS THAT ARE PART OF THE REQUIRED OUTPUT FORMAT (E.G., **, $, %) ARE USED, AND ANY OTHER SPECIAL CHARACTERS SUCH AS \\textbf, LATEX COMMANDS, OR ANY NON-STANDARD CHARACTERS SHOULD BE EXCLUDED.**"
121
- "Complete all the ### Task ### and ### Output ### first, and perform the ### Output Indicators ### last. Do not perform the ### Output Indicators ### in advance."
 
 
 
 
 
122
  )
123
 
124
  CUSTOM_CSS = """
@@ -156,6 +153,7 @@ class ModelClients:
156
  api_key=config.QWEN_API_KEY,
157
  base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
158
  )
 
159
 
160
  def encode_video_qwen(self, video_path):
161
  with open(video_path, "rb") as video_file:
@@ -368,6 +366,86 @@ Task 2: Provide a short chronological summary of the entire scene.
368
  analysis, tip_percentage, tip_amount, output_text = self.parse_llm_output(final_text)
369
  return analysis, tip_percentage, tip_amount, [], None, output_text
370
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  def calculate_manual_tip(self, tip_percent, subtotal):
372
  tip_amount = subtotal * (tip_percent / 100)
373
  total_bill = subtotal + tip_amount
@@ -401,7 +479,7 @@ class UIHandler:
401
  updated_prompt = updated_prompt.replace("{caption_text}", "{{caption_text}}")
402
  return calculated_subtotal, updated_prompt
403
 
404
- def compute_tip(self, alibaba_key, video_file_obj, subtotal, star_rating, user_review, custom_prompt_text):
405
  analysis_output = "계산을 시작합니다..."
406
  tip_percentage = 0.0
407
  tip_output = "$0.00"
@@ -409,12 +487,6 @@ class UIHandler:
409
  if video_file_obj is None:
410
  return "오류: 비디오 파일을 업로드해주세요.", "$0.00", total_bill_output, custom_prompt_text, gr.update(value=None)
411
  try:
412
- if alibaba_key and alibaba_key.strip():
413
- from openai import OpenAI as QwenOpenAI
414
- self.tip_calculator.model_clients.qwen_client = QwenOpenAI(
415
- api_key=alibaba_key,
416
- base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
417
- )
418
  temp_video_path = f"temp_video_{uuid.uuid4().hex}.mp4"
419
  original_path = video_file_obj.name if hasattr(video_file_obj, 'name') else video_file_obj
420
  shutil.copyfile(original_path, temp_video_path)
@@ -424,9 +496,14 @@ class UIHandler:
424
  return f"오류: 비디오 파일을 처리할 수 없습니다: {e}", "$0.00", total_bill_output, custom_prompt_text, None
425
  frame_folder = None
426
  try:
427
- analysis, tip_percentage, tip_amount, _, _, output_text = self.tip_calculator.process_tip_qwen(
428
- temp_video_path, star_rating, user_review, subtotal, custom_prompt_text
429
- )
 
 
 
 
 
430
  if "Error" in analysis:
431
  analysis_output = analysis
432
  tip_amount = 0.0
@@ -444,9 +521,9 @@ class UIHandler:
444
  self.video_processor.cleanup_temp_files(temp_video_path, frame_folder)
445
  return analysis_output, tip_output, total_bill_output, custom_prompt_text, gr.update(value=None)
446
 
447
- def auto_tip_and_invoice(self, alibaba_key, video_file_obj, subtotal, star_rating, review, prompt, *quantities):
448
  analysis, tip_disp, total_bill_disp, prompt_out, vid_out = self.compute_tip(
449
- alibaba_key, video_file_obj, subtotal, star_rating, review, prompt
450
  )
451
  invoice = self.update_invoice_summary(*quantities, tip_disp, total_bill_disp)
452
  return analysis, tip_disp, total_bill_disp, prompt_out, vid_out, invoice
@@ -507,8 +584,9 @@ class App:
507
  review_input, rating_input = None, None
508
  btn_5, btn_10, btn_15, btn_20, btn_25 = None, None, None, None, None
509
  qwen_btn = None
 
510
  tip_display, total_bill_display, payment_btn, payment_result = None, None, None, None
511
- alibaba_key_input, video_input = None, None
512
  analysis_display, order_summary_display = None, None
513
  prompt_editor = None # 프롬프트 에디터는 다른 탭에 정의될 것임
514
 
@@ -549,6 +627,8 @@ class App:
549
  btn_25 = gr.Button("25%")
550
  with gr.Row():
551
  # Qwen 버튼 정의를 여기로 이동!
 
 
552
  qwen_btn = gr.Button("Alibaba-Qwen AI Tip Calculation", variant="primary",
553
  elem_id="qwen-button")
554
  gr.Markdown("### 4. Results")
@@ -561,8 +641,7 @@ class App:
561
  # --- 오른쪽 열 (원래대로, 프롬프트 디스플레이 제외) ---
562
  with gr.Column(scale=1):
563
  gr.Markdown("### 5. Upload & Prompt Access")
564
- alibaba_key_input = gr.Textbox(label="Alibaba API Key", placeholder="Enter Key", lines=1,
565
- type="password")
566
  video_input = gr.Video(label="Upload Service Video")
567
 
568
  gr.Markdown("### 6. AI Analysis")
@@ -589,10 +668,10 @@ class App:
589
  gr.Examples(
590
  examples=[
591
  # 입력 순서: [Alibaba API Key, Video, Subtotal, Star Rating, Review] + [각 음식의 Qty]
592
- ["", "video/sample.mp4", 0.0, 1, "He drop the tray..so bad", 0, 0, 0, 0, 0, 2, 0, 0],
593
- ["", "video/sample2.mp4", 0.0, 5, "Good service!", 0, 0, 0, 0, 0, 2, 0, 0]
594
  ],
595
- inputs=[alibaba_key_input, video_input, subtotal_display, rating_input,
596
  review_input] + quantity_inputs,
597
  outputs=[analysis_display, tip_display, total_bill_display, video_input, order_summary_display],
598
  label="Example: Bad Service, Good Service"
@@ -603,8 +682,8 @@ class App:
603
  # (실제 코드에서는 컴포넌트 None 체크 또는 더 나은 구조화 필요)
604
 
605
  if all([subtotal_display, subtotal_visible_display_output, review_input, rating_input, prompt_editor,
606
- order_summary_display, alibaba_key_input, video_input, analysis_display, tip_display,
607
- total_bill_display, payment_result, qwen_btn] + quantity_inputs):
608
 
609
  # 1. 소계 업데이트 (숨겨진 Number -> 보이는 Textbox)
610
  subtotal_display.change(
@@ -634,14 +713,21 @@ class App:
634
  # 4. AI 계산 버튼('Main Interface' 탭) 클릭 시
635
  # 입력: 메인 탭의 컴포넌트들 + 'Edit Prompt' 탭의 prompt_editor
636
  # 출력: 메인 탭의 컴포넌트들 + 'Edit Prompt' 탭의 prompt_editor (업데이트 될 수 있으므로)
637
- qwen_compute_inputs = [alibaba_key_input, video_input, subtotal_display, rating_input, review_input,
638
- prompt_editor] + quantity_inputs
639
- qwen_compute_outputs = [analysis_display, tip_display, total_bill_display, prompt_editor, video_input,
640
- order_summary_display]
641
  qwen_btn.click(
642
- fn=self.ui_handler.auto_tip_and_invoice,
643
- inputs=qwen_compute_inputs,
644
- outputs=qwen_compute_outputs
 
 
 
 
 
 
 
 
 
 
 
645
  )
646
 
647
  # 5. 수동 팁 버튼('Main Interface' 탭) 클릭 시
 
1
  import os
2
  import shutil
3
+ import time
4
+
5
  import cv2
6
  import base64
7
  import uuid
8
  import re
9
  from flask import Flask
10
  import gradio as gr
11
+ from google import genai
12
+ from openai import OpenAI as QwenOpenAI
13
+
14
 
15
  # --- Config 클래스 (Gemma, GPT4o 제거, Qwen만 사용) ---
16
  class Config:
 
26
  {"name": "사이다", "image": "images/food6.jpg", "price": 12.00},
27
  ]
28
  # 알리바바 Qwen API 키 (기본값은 빈 문자열)
29
+ QWEN_API_KEY = "sk-2424f0bd26d64fe5a7f3a2bd407adc76"
30
+ GEMINI_API_key = "AIzaSyCc8lcm2cZo3ZeMgi4QN1IHSvn9BBpLnz4"
31
  DEFAULT_PROMPT_TEMPLATE = (
32
+ """
33
+ ### Persona ###
34
+ 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.
35
+ 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.
36
+
37
+ ### Task ###
38
+ 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.
39
+
40
+ 2. **Bill Amount Determination**: Determine the bill amount by following these steps:
41
+ * Use the 'Calculated Subtotal' provided.
42
+
43
+ 3. **Overall Service Quality Evaluation**:
44
+ Evaluate the service quality by evenly scoring the following four components, each out of 100:
45
+ a) **Video Service Score**: Service quality derived from the holistic analysis of Video Caption(s).
46
+ 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.
47
+ * **Note**: If any review mentions racist, sexist, or any other ethical violations, the Google Review score must automatically be set to **0**.
48
+ c) **User Review Score**: The user's review.
49
+ d) **Star Rating Score**: The user's star rating, interpreted on a scale where 5/5 corresponds to 100 points.
50
+ * Calculate the overall average score by taking the mean of these four scores.
51
+
52
+ 4. **Service Quality Classification and Tip Guidelines**:
53
+ * Based on the overall average score, classify the service quality as follows:
54
+ * Poor Service: Overall average score < 60 (Tip range: 0% ~ 5% of the bill)
55
+ * Average Service: Overall average score ≥ 60 and < 80 (Tip range: 10% ~ 15% of the bill)
56
+ * Good Service: Overall average score 80 (Tip range: 15% ~ 20% of the bill)
57
+ * 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%**.
58
+ * Calculate the tip amount by multiplying the determined bill amount by the chosen tip percentage (round to two decimal places).
59
+ * Calculate the final total bill by adding the tip amount to the subtotal (round to two decimal places).
60
+
61
+ 5. **Review Prioritization and Score Adjustment**:
62
+ * 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.
63
+
64
+ ### Ethical Violations and Tip Adjustment ###
65
+ * 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.
66
+
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  "### Recent Google Review ###\n\n"
68
 
69
  "#### Google Review 1 ####\n"
 
72
  "#### Google Review 2 ####\n"
73
  "[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."
74
  "\n\n"
75
+
76
+ ### Video Caption Input ###
77
+ # Multiple captions can be provided under this section
78
+ Video Caption(s):
79
+ {{caption_text}}
80
+
81
+ ### Output ###
82
+ Return your answer in the exact format below, providing the text analyses first, followed by the JSON block containing the final calculations:
83
+
84
+ 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.]
85
+ 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.]
86
+ 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.]
87
+ 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).]
88
+ Overall Analysis: [Step-by-step explanation detailing:
89
+ - How the bill amount was determined;
90
+ - 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;
91
+ - 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;
92
+ - How the overall average score was calculated;
93
+ - The reasoning for the final service quality classification based on the average score;
94
+ - 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.
95
+
96
+ ### Final Calculation Results (JSON Format) ###
97
+ ```json
98
+ {{{{
99
+ "final_tip_percentage": <calculated_percentage_int>,
100
+ "final_tip_amount": <calculated_tip_float>,
101
+ "final_total_bill": <calculated_total_bill_float>
102
+ }}}}
103
+ ```
104
+
105
+ ### GUIDE ###
106
+
107
+ 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.
108
+ Complete all the text analysis and overall analysis sections first, and generate the ### Final Calculation Results (JSON Format) ### section last.
109
+ **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.**
110
+
111
+ ### User Context ###
112
+ * Current Country: USA
113
+ * Currently Restaurant Name: The Golden Spoon (Assumed)
114
+ * Currently Calculated Subtotal: ${calculated_subtotal:.2f}
115
+ * Currently User Star Rating: {star_rating} / 5 (5 is the maximum)
116
+ * Currently User Review: {user_review}
117
+
118
+ """
119
  )
120
 
121
  CUSTOM_CSS = """
 
153
  api_key=config.QWEN_API_KEY,
154
  base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
155
  )
156
+ self.gemini_client = genai.Client(api_key=config.GEMINI_API_key)
157
 
158
  def encode_video_qwen(self, video_path):
159
  with open(video_path, "rb") as video_file:
 
366
  analysis, tip_percentage, tip_amount, output_text = self.parse_llm_output(final_text)
367
  return analysis, tip_percentage, tip_amount, [], None, output_text
368
 
369
+ def process_tip_gemini(self, video_file_path, star_rating, user_review, calculated_subtotal, custom_prompt=None):
370
+
371
+ if not video_file_path or not os.path.exists(video_file_path):
372
+ return "비디오 파일 경로가 유효하지 않습니다.", [], None
373
+ image_captioning_prompt = '''
374
+ Task 1: Describe the actions of any waiters or staff visible in these restaurant video. Note any specific interactions, mistakes, or positive actions.
375
+ Task 2: Provide a concise overall summary of the scene depicted in the frames, in chronological order if possible.
376
+
377
+ Task 1 Output:
378
+ Task 2 Output:
379
+ '''
380
+
381
+ video_file = self.model_clients.gemini_client.files.upload(file=video_file_path)
382
+ print(f"Uploaded file info: {video_file}")
383
+
384
+ # 동영상은 처리 중(Processing) 상태이므로, ACTIVE 상태가 될 때까지 대기합니다.
385
+ while video_file.state.name == "PROCESSING":
386
+ print("동영상 처리 중...")
387
+ time.sleep(1) # 예: 5초마다 상태 점검
388
+ video_file = self.model_clients.gemini_client.files.get(name=video_file.name)
389
+
390
+ # 처리 실패 여부 확인
391
+ if video_file.state.name == "FAILED":
392
+ raise ValueError(f"파일 처리 실패: {video_file.state.name}")
393
+
394
+ # 비디오를 프롬프트에 포함해서 추론 요청
395
+ try:
396
+ caption_summary = self.model_clients.gemini_client.models.generate_content(
397
+ model="gemini-2.0-flash-lite", # 예시: Gemini 2.0 Flash 모델 사용
398
+ contents=[video_file, image_captioning_prompt]
399
+ )
400
+ caption_summary = caption_summary.text
401
+
402
+ except Exception as e:
403
+ print(f"로컬 모델 프레임 처리 오류: {e}")
404
+ return f"Error in processing frames with local model: {e}", None, None
405
+
406
+ user_review = user_review.strip() if user_review and user_review.strip() else "(No user review provided)"
407
+
408
+ if custom_prompt is None:
409
+ prompt = self.config.DEFAULT_PROMPT_TEMPLATE.format(
410
+ calculated_subtotal=calculated_subtotal, star_rating=star_rating, user_review=user_review
411
+ )
412
+ else:
413
+ try:
414
+ prompt = custom_prompt.format(
415
+ calculated_subtotal=calculated_subtotal, star_rating=star_rating, user_review=user_review
416
+ )
417
+ except KeyError as e:
418
+ print(f"경고: 커스텀 프롬프트에 필요한 키가 없습니다: {e}. 기본 템플릿을 사용합니다.")
419
+ prompt = self.config.DEFAULT_PROMPT_TEMPLATE.format(
420
+ calculated_subtotal=calculated_subtotal, star_rating=star_rating, user_review=user_review
421
+ )
422
+
423
+ final_prompt = prompt.replace("{caption_text}", caption_summary)
424
+ messages = final_prompt
425
+
426
+ video_file = self.model_clients.gemini_client.files.upload(file=video_file_path)
427
+ print(f"Uploaded file info: {video_file}")
428
+
429
+ # 동영상은 처리 중(Processing) 상태이므로, ACTIVE 상태가 될 때까지 대기합니다.
430
+ while video_file.state.name == "PROCESSING":
431
+ print("동영상 처리 중...")
432
+ time.sleep(1) # 예: 5초마다 상태 점검
433
+ video_file = self.model_clients.gemini_client.files.get(name=video_file.name)
434
+
435
+ # 처리 실패 여부 확인
436
+ if video_file.state.name == "FAILED":
437
+ raise ValueError(f"파일 처리 실패: {video_file.state.name}")
438
+
439
+
440
+ response = self.model_clients.gemini_client.models.generate_content(
441
+ model="gemini-2.0-flash-lite", # 예시: Gemini 2.0 Flash 모델 사용
442
+ contents=[video_file, messages]
443
+ )
444
+ llm_output = response.text
445
+ analysis, tip_percentage, tip_amount, output_text = self.parse_llm_output(llm_output)
446
+ return analysis, tip_percentage, tip_amount, [], None, output_text
447
+
448
+
449
  def calculate_manual_tip(self, tip_percent, subtotal):
450
  tip_amount = subtotal * (tip_percent / 100)
451
  total_bill = subtotal + tip_amount
 
479
  updated_prompt = updated_prompt.replace("{caption_text}", "{{caption_text}}")
480
  return calculated_subtotal, updated_prompt
481
 
482
+ def compute_tip(self, type, video_file_obj, subtotal, star_rating, user_review, custom_prompt_text):
483
  analysis_output = "계산을 시작합니다..."
484
  tip_percentage = 0.0
485
  tip_output = "$0.00"
 
487
  if video_file_obj is None:
488
  return "오류: 비디오 파일을 업로드해주세요.", "$0.00", total_bill_output, custom_prompt_text, gr.update(value=None)
489
  try:
 
 
 
 
 
 
490
  temp_video_path = f"temp_video_{uuid.uuid4().hex}.mp4"
491
  original_path = video_file_obj.name if hasattr(video_file_obj, 'name') else video_file_obj
492
  shutil.copyfile(original_path, temp_video_path)
 
496
  return f"오류: 비디오 파일을 처리할 수 없습니다: {e}", "$0.00", total_bill_output, custom_prompt_text, None
497
  frame_folder = None
498
  try:
499
+ if type == 'qwen':
500
+ analysis, tip_percentage, tip_amount, _, _, output_text = self.tip_calculator.process_tip_qwen(
501
+ temp_video_path, star_rating, user_review, subtotal, custom_prompt_text
502
+ )
503
+ else:
504
+ analysis, tip_percentage, tip_amount, _, _, output_text = self.tip_calculator.process_tip_gemini(
505
+ temp_video_path, star_rating, user_review, subtotal, custom_prompt_text
506
+ )
507
  if "Error" in analysis:
508
  analysis_output = analysis
509
  tip_amount = 0.0
 
521
  self.video_processor.cleanup_temp_files(temp_video_path, frame_folder)
522
  return analysis_output, tip_output, total_bill_output, custom_prompt_text, gr.update(value=None)
523
 
524
+ def auto_tip_and_invoice(self, type, video_file_obj, subtotal, star_rating, review, prompt, *quantities):
525
  analysis, tip_disp, total_bill_disp, prompt_out, vid_out = self.compute_tip(
526
+ type, video_file_obj, subtotal, star_rating, review, prompt
527
  )
528
  invoice = self.update_invoice_summary(*quantities, tip_disp, total_bill_disp)
529
  return analysis, tip_disp, total_bill_disp, prompt_out, vid_out, invoice
 
584
  review_input, rating_input = None, None
585
  btn_5, btn_10, btn_15, btn_20, btn_25 = None, None, None, None, None
586
  qwen_btn = None
587
+ gemini_btn = None
588
  tip_display, total_bill_display, payment_btn, payment_result = None, None, None, None
589
+ video_input = None
590
  analysis_display, order_summary_display = None, None
591
  prompt_editor = None # 프롬프트 에디터는 다른 탭에 정의될 것임
592
 
 
627
  btn_25 = gr.Button("25%")
628
  with gr.Row():
629
  # Qwen 버튼 정의를 여기로 이동!
630
+ gemini_btn = gr.Button("Google-Gemini AI Tip Calculation", variant="primary",
631
+ elem_id="Gemini-button")
632
  qwen_btn = gr.Button("Alibaba-Qwen AI Tip Calculation", variant="primary",
633
  elem_id="qwen-button")
634
  gr.Markdown("### 4. Results")
 
641
  # --- 오른쪽 열 (원래대로, 프롬프트 디스플레이 제외) ---
642
  with gr.Column(scale=1):
643
  gr.Markdown("### 5. Upload & Prompt Access")
644
+
 
645
  video_input = gr.Video(label="Upload Service Video")
646
 
647
  gr.Markdown("### 6. AI Analysis")
 
668
  gr.Examples(
669
  examples=[
670
  # 입력 순서: [Alibaba API Key, Video, Subtotal, Star Rating, Review] + [각 음식의 Qty]
671
+ ["video/sample.mp4", 0.0, 1, "He drop the tray..so bad", 0, 0, 0, 0, 0, 2, 0, 0],
672
+ ["video/sample2.mp4", 0.0, 5, "Good service!", 0, 0, 0, 0, 0, 2, 0, 0]
673
  ],
674
+ inputs=[video_input, subtotal_display, rating_input,
675
  review_input] + quantity_inputs,
676
  outputs=[analysis_display, tip_display, total_bill_display, video_input, order_summary_display],
677
  label="Example: Bad Service, Good Service"
 
682
  # (실제 코드에서는 컴포넌트 None 체크 또는 더 나은 구조화 필요)
683
 
684
  if all([subtotal_display, subtotal_visible_display_output, review_input, rating_input, prompt_editor,
685
+ order_summary_display, video_input, analysis_display, tip_display,
686
+ total_bill_display, payment_result, qwen_btn, gemini_btn] + quantity_inputs):
687
 
688
  # 1. 소계 업데이트 (숨겨진 Number -> 보이는 Textbox)
689
  subtotal_display.change(
 
713
  # 4. AI 계산 버튼('Main Interface' 탭) 클릭 시
714
  # 입력: 메인 탭의 컴포넌트들 + 'Edit Prompt' 탭의 prompt_editor
715
  # 출력: 메인 탭의 컴포넌트들 + 'Edit Prompt' 탭의 prompt_editor (업데이트 될 수 있으므로)
 
 
 
 
716
  qwen_btn.click(
717
+ fn=lambda vid, sub, rat, rev, prom, *qty: self.ui_handler.auto_tip_and_invoice('qwen', vid, sub,
718
+ rat, rev, prom,
719
+ *qty),
720
+ inputs=[video_input, subtotal_display, rating_input, review_input, prompt_editor] + quantity_inputs,
721
+ outputs=[analysis_display, tip_display, total_bill_display, prompt_editor, video_input,
722
+ order_summary_display]
723
+ )
724
+ gemini_btn.click(
725
+ fn=lambda vid, sub, rat, rev, prom, *qty: self.ui_handler.auto_tip_and_invoice('gemini', vid, sub,
726
+ rat, rev, prom,
727
+ *qty),
728
+ inputs=[video_input, subtotal_display, rating_input, review_input, prompt_editor] + quantity_inputs,
729
+ outputs=[analysis_display, tip_display, total_bill_display, prompt_editor, video_input,
730
+ order_summary_display]
731
  )
732
 
733
  # 5. 수동 팁 버튼('Main Interface' 탭) 클릭 시
requirements.txt CHANGED
@@ -1,4 +1,6 @@
1
  gradio
2
  opencv-python
3
  flask
4
- openai
 
 
 
1
  gradio
2
  opencv-python
3
  flask
4
+ openai
5
+ genai
6
+ google-generativeai