vivek9chavan commited on
Commit
2955ae6
·
verified ·
1 Parent(s): 9c2cb20

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -53
app.py CHANGED
@@ -2,28 +2,26 @@ import gradio as gr
2
  import google.generativeai as genai
3
  import os
4
  import time
5
- import json # We need this library to parse the JSON output
6
  from dotenv import load_dotenv
7
 
8
  # --- Configuration ---
9
  load_dotenv()
10
 
 
11
  try:
12
  genai.configure(api_key=os.environ["GEMINI_API_KEY"])
13
  except KeyError:
14
  raise gr.Error("FATAL: GEMINI_API_KEY not found. Please set it in your Hugging Face Space secrets.")
15
 
16
- # --- Core Function with JSON Parsing ---
17
 
18
  def analyze_device_condition(video_file_path):
19
- """
20
- Analyzes a video and returns structured JSON data with three fields.
21
- """
22
  if not video_file_path:
23
- return "Please upload video", "", "" # Return empty strings for the other fields
24
 
25
  try:
26
- # 1. Upload the file (same as before)
27
  print("Log: Uploading file to Google...")
28
  video_file = genai.upload_file(path=video_file_path)
29
 
@@ -33,89 +31,60 @@ def analyze_device_condition(video_file_path):
33
  video_file = genai.get_file(video_file.name)
34
 
35
  if video_file.state.name == "FAILED":
36
- error_message = "Error: Video processing failed."
37
- return error_message, "", ""
38
 
39
  print(f"Log: File processed successfully.")
40
 
41
- # 2. ** NEW: Update the prompt to request JSON output **
42
  prompt = """
43
- Analyze the provided video of a device. Respond ONLY with a valid JSON object.
44
- The JSON object must have the following three keys and nothing else:
45
- 1. "device_type": A short string identifying the device (e.g., "iPhone 14 Pro", "Washing Machine", "Laptop").
46
- 2. "condition": A single word describing its condition. Choose from: "Mint", "Excellent", "Good", "Fair", "Poor".
47
- 3. "reason": A brief string explaining the condition rating, mentioning specific defects like "minor screen scratches", "dents on corner", or "clean".
48
-
49
- Example JSON output:
50
- {
51
- "device_type": "Samsung Galaxy S22",
52
- "condition": "Fair",
53
- "reason": "Visible cracks on the screen and scratches on the back panel."
54
- }
55
  """
56
 
57
- # 3. Call the Gemini Model
58
- model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest")
 
59
 
60
  print("Log: Sending prompt and video to Gemini...")
61
  response = model.generate_content(
62
  [prompt, video_file],
63
- # Ask the model specifically for a JSON response
64
- generation_config=genai.types.GenerationConfig(response_mime_type="application/json")
 
 
65
  )
66
 
67
  print("Log: Analysis received from Gemini.")
68
  genai.delete_file(video_file.name)
69
- print(f"Log: Uploaded file deleted.")
70
 
71
- # 4. ** NEW: Parse the JSON response **
72
- print(f"Raw model response: {response.text}")
73
  parsed_json = json.loads(response.text)
74
-
75
  device_type = parsed_json.get("device_type", "N/A")
76
  condition = parsed_json.get("condition", "N/A")
77
  reason = parsed_json.get("reason", "N/A")
78
 
79
- # The function now returns three separate values
80
  return device_type, condition, reason
81
 
82
  except Exception as e:
83
  print(f"!!!!!!!! AN ERROR OCCURRED !!!!!!!!\n{e}")
84
  error_message = f"An error occurred: {e}"
85
- # Return the error message in the first field and empty strings for the others
86
  return error_message, "", ""
87
 
88
-
89
- # --- ** NEW: Gradio Interface with Multiple Output Fields ** ---
90
-
91
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
92
- gr.Markdown(
93
- """
94
- # 📱 Device Condition Analyzer
95
- Upload or record a short video of an electronic device to get a structured analysis of its condition.
96
- """
97
- )
98
-
99
- video_input = gr.Video(
100
- label="Upload or Record Video",
101
- sources=["upload", "webcam"],
102
- format="mp4"
103
- )
104
-
105
  submit_button = gr.Button("Analyze Device", variant="primary")
106
-
107
- # Create a row layout for the output fields
108
  with gr.Row():
109
- # Create three separate Textbox outputs
110
  device_type_output = gr.Textbox(label="Device Type")
111
  condition_output = gr.Textbox(label="Condition")
112
  reason_output = gr.Textbox(label="Reason / Details")
113
 
114
- # The click function now maps to three outputs instead of one
115
  submit_button.click(
116
  fn=analyze_device_condition,
117
  inputs=video_input,
118
- # The list of outputs must match the order of the return values in the function
119
  outputs=[device_type_output, condition_output, reason_output],
120
  show_progress='full'
121
  )
 
2
  import google.generativeai as genai
3
  import os
4
  import time
5
+ import json
6
  from dotenv import load_dotenv
7
 
8
  # --- Configuration ---
9
  load_dotenv()
10
 
11
+ # This is the correct way to initialize for the 'google-genai' library
12
  try:
13
  genai.configure(api_key=os.environ["GEMINI_API_KEY"])
14
  except KeyError:
15
  raise gr.Error("FATAL: GEMINI_API_KEY not found. Please set it in your Hugging Face Space secrets.")
16
 
17
+ # --- Core Function ---
18
 
19
  def analyze_device_condition(video_file_path):
 
 
 
20
  if not video_file_path:
21
+ return "Please upload video", "", ""
22
 
23
  try:
24
+ # 1. This library has a simple helper to upload and process the file
25
  print("Log: Uploading file to Google...")
26
  video_file = genai.upload_file(path=video_file_path)
27
 
 
31
  video_file = genai.get_file(video_file.name)
32
 
33
  if video_file.state.name == "FAILED":
34
+ raise gr.Error("Video processing failed. The file might be corrupted or in an unsupported format.")
 
35
 
36
  print(f"Log: File processed successfully.")
37
 
38
+ # 2. Prompt for JSON output
39
  prompt = """
40
+ Analyze the provided video. Respond ONLY with a valid JSON object with three keys:
41
+ 1. "device_type": A short string identifying the device.
42
+ 2. "condition": A single word: "Mint", "Excellent", "Good", "Fair", or "Poor".
43
+ 3. "reason": A brief string explaining the condition.
 
 
 
 
 
 
 
 
44
  """
45
 
46
+ # 3. Call the Gemini Model using the simpler syntax
47
+ # Using a reliable flash model
48
+ model = genai.GenerativeModel(model_name="gemini-1.5-flash-latest")
49
 
50
  print("Log: Sending prompt and video to Gemini...")
51
  response = model.generate_content(
52
  [prompt, video_file],
53
+ generation_config=genai.types.GenerationConfig(
54
+ response_mime_type="application/json",
55
+ temperature=0.2
56
+ )
57
  )
58
 
59
  print("Log: Analysis received from Gemini.")
60
  genai.delete_file(video_file.name)
 
61
 
62
+ # 4. Parse the JSON response
 
63
  parsed_json = json.loads(response.text)
 
64
  device_type = parsed_json.get("device_type", "N/A")
65
  condition = parsed_json.get("condition", "N/A")
66
  reason = parsed_json.get("reason", "N/A")
67
 
 
68
  return device_type, condition, reason
69
 
70
  except Exception as e:
71
  print(f"!!!!!!!! AN ERROR OCCURRED !!!!!!!!\n{e}")
72
  error_message = f"An error occurred: {e}"
 
73
  return error_message, "", ""
74
 
75
+ # --- Gradio Interface ---
 
 
76
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
77
+ gr.Markdown("# 📱 Device Condition Analyzer")
78
+ video_input = gr.Video(label="Upload or Record Video", sources=["upload", "webcam"], format="mp4")
 
 
 
 
 
 
 
 
 
 
 
79
  submit_button = gr.Button("Analyze Device", variant="primary")
 
 
80
  with gr.Row():
 
81
  device_type_output = gr.Textbox(label="Device Type")
82
  condition_output = gr.Textbox(label="Condition")
83
  reason_output = gr.Textbox(label="Reason / Details")
84
 
 
85
  submit_button.click(
86
  fn=analyze_device_condition,
87
  inputs=video_input,
 
88
  outputs=[device_type_output, condition_output, reason_output],
89
  show_progress='full'
90
  )