shukdevdatta123 commited on
Commit
37c6da0
·
verified ·
1 Parent(s): 7a90624

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -6
app.py CHANGED
@@ -1,5 +1,6 @@
1
  import gradio as gr
2
  import os
 
3
  from openai import OpenAI
4
  import json
5
  import requests
@@ -25,6 +26,8 @@ found on nature trails. For any image sent, please:
25
  5. Offer suggestions for what to observe or learn about next on the trail
26
 
27
  Keep explanations informative yet accessible to people of all ages and backgrounds.
 
 
28
  """
29
 
30
  def encode_image_to_base64(image_path):
@@ -32,14 +35,60 @@ def encode_image_to_base64(image_path):
32
  with open(image_path, "rb") as image_file:
33
  return base64.b64encode(image_file.read()).decode('utf-8')
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  def analyze_image(api_key, image, prompt="What can you identify in this nature trail image? Provide detailed educational information.", site_url=DEFAULT_SITE_URL, site_name=DEFAULT_SITE_NAME, model=DEFAULT_MODEL):
36
  """Analyze the uploaded image using the InternVL3 model via OpenRouter"""
37
  # Remove the placeholder text check
38
  if not api_key:
39
- return "Please provide an OpenRouter API key."
40
 
41
  if image is None:
42
- return "Please upload an image to analyze."
43
 
44
  # Save the image temporarily
45
  temp_image_path = "temp_image.jpg"
@@ -83,10 +132,11 @@ def analyze_image(api_key, image, prompt="What can you identify in this nature t
83
  )
84
 
85
  analysis_result = response.choices[0].message.content
86
- return analysis_result
87
 
88
  except Exception as e:
89
- return f"Error analyzing image: {str(e)}"
 
90
 
91
  finally:
92
  # Clean up the temporary file
@@ -119,7 +169,7 @@ def build_custom_prompt(identification=True, education=True, seasonal=True, cons
119
  return "What can you identify in this nature trail image?"
120
 
121
  numbered_prompt = "\n".join([f"{i+1}. {part}" for i, part in enumerate(prompt_parts)])
122
- return f"For this nature trail image, please: \n{numbered_prompt}"
123
 
124
  def create_interface():
125
  """Create the Gradio interface for the Dynamic Nature Trail Guide"""
@@ -167,7 +217,7 @@ def create_interface():
167
  analyze_button = gr.Button("Analyze Nature Image", variant="primary")
168
 
169
  with gr.Column(scale=1):
170
- output_text = gr.Markdown(label="Analysis Results")
171
 
172
  # Set up the click event for the analyze button
173
  analyze_button.click(
 
1
  import gradio as gr
2
  import os
3
+ import re
4
  from openai import OpenAI
5
  import json
6
  import requests
 
26
  5. Offer suggestions for what to observe or learn about next on the trail
27
 
28
  Keep explanations informative yet accessible to people of all ages and backgrounds.
29
+
30
+ IMPORTANT: Structure your responses with clear sections and headings.
31
  """
32
 
33
  def encode_image_to_base64(image_path):
 
35
  with open(image_path, "rb") as image_file:
36
  return base64.b64encode(image_file.read()).decode('utf-8')
37
 
38
+ def format_response_as_html(text):
39
+ """Convert the model's text response to formatted HTML"""
40
+ if not text:
41
+ return ""
42
+
43
+ # Check if the response is an error message
44
+ if text.startswith("Error analyzing image:"):
45
+ return f'<div style="color: red; padding: 10px; border: 1px solid red; border-radius: 5px;">{text}</div>'
46
+
47
+ # Replace newlines with HTML breaks
48
+ text = text.replace('\n\n', '</p><p>').replace('\n', '<br>')
49
+
50
+ # Handle headings - look for patterns like "1. Identification:" or "Species Identified:"
51
+ heading_patterns = [
52
+ (r'([A-Za-z\s]+):(?=<br>|</p>)', r'<h3>\1</h3>'), # "Category:" at start of line
53
+ (r'(\d+\.\s+[A-Za-z\s]+):(?=<br>|</p>)', r'<h3>\1</h3>'), # "1. Category:" format
54
+ ]
55
+
56
+ for pattern, replacement in heading_patterns:
57
+ text = re.sub(pattern, replacement, text)
58
+
59
+ # Enhance species names with bold
60
+ text = re.sub(r'\b([A-Z][a-z]+\s+[a-z]+)\b(?!\<\/)', r'<strong>\1</strong>', text)
61
+
62
+ # Add some color to certain keywords
63
+ color_mappings = {
64
+ 'endangered': 'red',
65
+ 'rare': '#FF6600',
66
+ 'native': '#006600',
67
+ 'invasive': '#CC0000',
68
+ 'ecosystem': '#006699',
69
+ 'habitat': '#336699',
70
+ }
71
+
72
+ for keyword, color in color_mappings.items():
73
+ text = re.sub(r'\b' + keyword + r'\b', f'<span style="color: {color};">{keyword}</span>', text, flags=re.IGNORECASE)
74
+
75
+ # Wrap the entire content in a styled div
76
+ html = f'''
77
+ <div style="padding: 15px; font-family: Arial, sans-serif; line-height: 1.6;">
78
+ <p>{text}</p>
79
+ </div>
80
+ '''
81
+
82
+ return html
83
+
84
  def analyze_image(api_key, image, prompt="What can you identify in this nature trail image? Provide detailed educational information.", site_url=DEFAULT_SITE_URL, site_name=DEFAULT_SITE_NAME, model=DEFAULT_MODEL):
85
  """Analyze the uploaded image using the InternVL3 model via OpenRouter"""
86
  # Remove the placeholder text check
87
  if not api_key:
88
+ return "<div style='color: red; padding: 10px; border: 1px solid red; border-radius: 5px;'>Please provide an OpenRouter API key.</div>"
89
 
90
  if image is None:
91
+ return "<div style='color: red; padding: 10px; border: 1px solid red; border-radius: 5px;'>Please upload an image to analyze.</div>"
92
 
93
  # Save the image temporarily
94
  temp_image_path = "temp_image.jpg"
 
132
  )
133
 
134
  analysis_result = response.choices[0].message.content
135
+ return format_response_as_html(analysis_result)
136
 
137
  except Exception as e:
138
+ error_message = f"Error analyzing image: {str(e)}"
139
+ return f'<div style="color: red; padding: 10px; border: 1px solid red; border-radius: 5px;">{error_message}</div>'
140
 
141
  finally:
142
  # Clean up the temporary file
 
169
  return "What can you identify in this nature trail image?"
170
 
171
  numbered_prompt = "\n".join([f"{i+1}. {part}" for i, part in enumerate(prompt_parts)])
172
+ return f"For this nature trail image, please: \n{numbered_prompt}\n\nIMPORTANT: Structure your response with clear sections and headings for better readability."
173
 
174
  def create_interface():
175
  """Create the Gradio interface for the Dynamic Nature Trail Guide"""
 
217
  analyze_button = gr.Button("Analyze Nature Image", variant="primary")
218
 
219
  with gr.Column(scale=1):
220
+ output_text = gr.HTML(label="Analysis Results")
221
 
222
  # Set up the click event for the analyze button
223
  analyze_button.click(