vivek9chavan commited on
Commit
9c2cb20
·
verified ·
1 Parent(s): 6d0794f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -47
app.py CHANGED
@@ -1,76 +1,123 @@
1
  import gradio as gr
2
- import google.generativeai as genai # This is the correct, modern import
3
  import os
4
  import time
 
5
  from dotenv import load_dotenv
6
 
7
  # --- Configuration ---
8
- # To deploy on Hugging Face Spaces, set the GEMINI_API_KEY in the Space's secrets
9
  load_dotenv()
10
 
11
  try:
12
- # Configure the Gemini API key using the modern SDK's method
13
  genai.configure(api_key=os.environ["GEMINI_API_KEY"])
14
  except KeyError:
15
- raise gr.Error("GEMINI_API_KEY not found. Please set it in your Hugging Face Space secrets.")
16
 
17
-
18
- # --- Core Function using the Modern SDK ---
19
 
20
  def analyze_device_condition(video_file_path):
 
 
 
21
  if not video_file_path:
22
- return "Please upload or record a video first."
23
-
24
- print(f"Uploading file: {video_file_path}...")
25
- # The new SDK provides a clean file upload API, which is what we need for video
26
- video_file = genai.upload_file(path=video_file_path)
27
-
28
- # Wait for the video to be processed by Google's servers
29
- while video_file.state.name == "PROCESSING":
30
- print("Waiting for video to be processed...")
31
- time.sleep(2) # Wait 2 seconds before checking again
32
- video_file = genai.get_file(video_file.name)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- if video_file.state.name == "FAILED":
35
- raise gr.Error("Video processing failed. Please try another video.")
 
36
 
37
- print(f"File uploaded successfully: {video_file.name}")
 
 
38
 
39
- # --- Prompt for the Model ---
40
- prompt = """
41
- You are an expert in analyzing the condition of electronic devices from videos.
42
- Please analyze the provided video and give me the following information in a clear, structured format:
43
 
44
- 1. **Device Type:** Identify the specific device model (e.g., iPhone 14 Pro, Dell XPS 15). Be as specific as possible.
45
- 2. **Visual Condition:** Describe the physical condition in detail. Mention any visible scratches, dents, or cracks on the screen or body. Grade the condition on a scale of 'Mint', 'Good', 'Fair', or 'Poor'.
46
- """
 
 
47
 
48
- # --- Model Interaction ---
49
- # Use the latest available model that's best for video
50
- model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest")
51
-
52
- # Send the prompt and the processed video file to the model
53
- print("Generating analysis...")
54
- response = model.generate_content([prompt, video_file], request_options={"timeout": 600})
55
-
56
- # Clean up the file from Google's servers after we're done
57
- genai.delete_file(video_file.name)
58
- print(f"File {video_file.name} deleted.")
59
-
60
- return response.text
61
 
 
62
 
63
- # --- Gradio Interface (No changes here) ---
64
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
65
- gr.Markdown("# 📱 Device Condition Analyzer")
66
- video_input = gr.Video(label="Upload or Record Video", sources=["upload", "webcam"])
 
 
 
 
 
 
 
 
 
 
 
67
  submit_button = gr.Button("Analyze Device", variant="primary")
68
- output_text = gr.Markdown(label="Analysis Results")
69
-
 
 
 
 
 
 
 
70
  submit_button.click(
71
  fn=analyze_device_condition,
72
  inputs=video_input,
73
- outputs=output_text
 
 
74
  )
75
 
76
- demo.launch()
 
1
  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
+
30
+ while video_file.state.name == "PROCESSING":
31
+ print("Log: Waiting for video processing...")
32
+ time.sleep(5)
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
  )
122
 
123
+ demo.launch(debug=True)