Update app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,5 @@
|
|
1 |
import gradio as gr
|
2 |
import os
|
3 |
-
import re
|
4 |
from openai import OpenAI
|
5 |
import json
|
6 |
import requests
|
@@ -10,6 +9,7 @@ import base64
|
|
10 |
|
11 |
# Constants
|
12 |
DEFAULT_MODEL = "opengvlab/internvl3-14b:free"
|
|
|
13 |
DEFAULT_SITE_URL = "https://dynamic-nature-trail-guide.app"
|
14 |
DEFAULT_SITE_NAME = "Dynamic Nature Trail Guide"
|
15 |
|
@@ -21,9 +21,8 @@ found on nature trails. For any image sent, please:
|
|
21 |
2. Provide educational information about identified elements
|
22 |
3. Mention any seasonal characteristics visible in the image
|
23 |
4. Note any ecological significance or conservation considerations
|
24 |
-
5. Offer suggestions for what to observe or learn next on the trail
|
25 |
Keep explanations informative yet accessible to people of all ages and backgrounds.
|
26 |
-
IMPORTANT: Structure your responses with clear sections and headings.
|
27 |
"""
|
28 |
|
29 |
def encode_image_to_base64(image_path):
|
@@ -31,98 +30,14 @@ def encode_image_to_base64(image_path):
|
|
31 |
with open(image_path, "rb") as image_file:
|
32 |
return base64.b64encode(image_file.read()).decode('utf-8')
|
33 |
|
34 |
-
def format_response_as_html(text):
|
35 |
-
"""Convert the model's text response to formatted HTML with improved section handling"""
|
36 |
-
if not text:
|
37 |
-
return ""
|
38 |
-
|
39 |
-
# Check if the response is an error message
|
40 |
-
if text.startswith("Error analyzing image:"):
|
41 |
-
return f'<div style="color: red; padding: 10px; border: 1px solid red; border-radius: 5px;">{text}</div>'
|
42 |
-
|
43 |
-
# Parse sections using regex patterns
|
44 |
-
# Look for patterns like "### 1. Identification of Elements" or "## Plants:"
|
45 |
-
sections = re.split(r'(?:#{1,3}\s*\d*\.?\s*|\*\*)([\w\s]+)(?:\*\*|:)', text)
|
46 |
-
|
47 |
-
# If splitting didn't work well, fall back to a simpler approach
|
48 |
-
if len(sections) <= 1:
|
49 |
-
# Simple formatting with paragraphs
|
50 |
-
text = text.replace('\n\n', '</p><p>')
|
51 |
-
return f'<div style="padding: 15px; font-family: Arial, sans-serif; line-height: 1.6;"><p>{text}</p></div>'
|
52 |
-
|
53 |
-
# Build HTML from sections
|
54 |
-
html_parts = ['<div style="padding: 15px; font-family: Arial, sans-serif; line-height: 1.6;">']
|
55 |
-
|
56 |
-
for i in range(1, len(sections), 2):
|
57 |
-
if i < len(sections) - 1:
|
58 |
-
section_title = sections[i].strip()
|
59 |
-
section_content = sections[i+1].strip()
|
60 |
-
|
61 |
-
# Apply formatting to section content
|
62 |
-
section_content = format_section_content(section_content)
|
63 |
-
|
64 |
-
html_parts.append(f'<div class="section">')
|
65 |
-
html_parts.append(f'<h3 style="color: #336699; border-bottom: 1px solid #ccc; padding-bottom: 5px;">{section_title}</h3>')
|
66 |
-
html_parts.append(f'<div class="content">{section_content}</div>')
|
67 |
-
html_parts.append('</div>')
|
68 |
-
|
69 |
-
# If we couldn't parse sections properly, use the original text
|
70 |
-
if len(html_parts) == 1:
|
71 |
-
text = format_section_content(text)
|
72 |
-
html_parts.append(f'<p>{text}</p>')
|
73 |
-
|
74 |
-
html_parts.append('</div>')
|
75 |
-
return ''.join(html_parts)
|
76 |
-
|
77 |
-
def format_section_content(content):
|
78 |
-
"""Format the content of a section with enhanced styling"""
|
79 |
-
# Replace line breaks with paragraph breaks for better readability
|
80 |
-
content = re.sub(r'\n\s*\n', '</p><p>', content)
|
81 |
-
content = re.sub(r'\n(?!<\/p>)', '<br>', content)
|
82 |
-
|
83 |
-
# Convert bullet points
|
84 |
-
content = re.sub(r'^\s*-\s*(.+?)$', r'<li>\1</li>', content, flags=re.MULTILINE)
|
85 |
-
content = re.sub(r'(<li>.*?</li>)', r'<ul>\1</ul>', content, flags=re.DOTALL)
|
86 |
-
# Fix nested lists (remove empty ul tags)
|
87 |
-
content = re.sub(r'<ul>\s*</ul>', '', content)
|
88 |
-
|
89 |
-
# Handle subsections like "**Plants:**"
|
90 |
-
content = re.sub(r'\*\*([\w\s]+):\*\*', r'<h4 style="margin-bottom: 5px; color: #336699;">\1</h4>', content)
|
91 |
-
|
92 |
-
# Enhance species names with bold and italics for scientific names
|
93 |
-
content = re.sub(r'\b([A-Z][a-z]+\s+[a-z]+)\b(?!\<\/)', r'<strong><em>\1</em></strong>', content)
|
94 |
-
|
95 |
-
# Add some color to certain keywords
|
96 |
-
color_mappings = {
|
97 |
-
'endangered': '#e74c3c',
|
98 |
-
'rare': '#FF6600',
|
99 |
-
'native': '#27ae60',
|
100 |
-
'invasive': '#CC0000',
|
101 |
-
'ecosystem': '#3498db',
|
102 |
-
'habitat': '#336699',
|
103 |
-
'conservation': '#16a085',
|
104 |
-
'protected': '#9b59b6',
|
105 |
-
'biodiversity': '#2ecc71'
|
106 |
-
}
|
107 |
-
|
108 |
-
for keyword, color in color_mappings.items():
|
109 |
-
content = re.sub(r'\b' + keyword + r'\b', f'<span style="color: {color}; font-weight: bold;">{keyword}</span>', content, flags=re.IGNORECASE)
|
110 |
-
|
111 |
-
# Ensure the content starts and ends with paragraph tags if needed
|
112 |
-
if not content.startswith('<p>') and not content.startswith('<ul>') and not content.startswith('<h4'):
|
113 |
-
content = '<p>' + content
|
114 |
-
if not content.endswith('</p>') and not content.endswith('</ul>'):
|
115 |
-
content = content + '</p>'
|
116 |
-
|
117 |
-
return content
|
118 |
-
|
119 |
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):
|
120 |
"""Analyze the uploaded image using the InternVL3 model via OpenRouter"""
|
|
|
121 |
if not api_key:
|
122 |
-
return "
|
123 |
|
124 |
if image is None:
|
125 |
-
return "
|
126 |
|
127 |
# Save the image temporarily
|
128 |
temp_image_path = "temp_image.jpg"
|
@@ -166,11 +81,10 @@ def analyze_image(api_key, image, prompt="What can you identify in this nature t
|
|
166 |
)
|
167 |
|
168 |
analysis_result = response.choices[0].message.content
|
169 |
-
return
|
170 |
|
171 |
except Exception as e:
|
172 |
-
|
173 |
-
return f'<div style="color: red; padding: 10px; border: 1px solid red; border-radius: 5px;">{error_message}</div>'
|
174 |
|
175 |
finally:
|
176 |
# Clean up the temporary file
|
@@ -203,7 +117,7 @@ def build_custom_prompt(identification=True, education=True, seasonal=True, cons
|
|
203 |
return "What can you identify in this nature trail image?"
|
204 |
|
205 |
numbered_prompt = "\n".join([f"{i+1}. {part}" for i, part in enumerate(prompt_parts)])
|
206 |
-
return f"For this nature trail image, please: \n{numbered_prompt}
|
207 |
|
208 |
def create_interface():
|
209 |
"""Create the Gradio interface for the Dynamic Nature Trail Guide"""
|
@@ -251,7 +165,7 @@ def create_interface():
|
|
251 |
analyze_button = gr.Button("Analyze Nature Image", variant="primary")
|
252 |
|
253 |
with gr.Column(scale=1):
|
254 |
-
output_text = gr.
|
255 |
|
256 |
# Set up the click event for the analyze button
|
257 |
analyze_button.click(
|
|
|
1 |
import gradio as gr
|
2 |
import os
|
|
|
3 |
from openai import OpenAI
|
4 |
import json
|
5 |
import requests
|
|
|
9 |
|
10 |
# Constants
|
11 |
DEFAULT_MODEL = "opengvlab/internvl3-14b:free"
|
12 |
+
# No need for placeholder text as we'll use password type input
|
13 |
DEFAULT_SITE_URL = "https://dynamic-nature-trail-guide.app"
|
14 |
DEFAULT_SITE_NAME = "Dynamic Nature Trail Guide"
|
15 |
|
|
|
21 |
2. Provide educational information about identified elements
|
22 |
3. Mention any seasonal characteristics visible in the image
|
23 |
4. Note any ecological significance or conservation considerations
|
24 |
+
5. Offer suggestions for what to observe or learn about next on the trail
|
25 |
Keep explanations informative yet accessible to people of all ages and backgrounds.
|
|
|
26 |
"""
|
27 |
|
28 |
def encode_image_to_base64(image_path):
|
|
|
30 |
with open(image_path, "rb") as image_file:
|
31 |
return base64.b64encode(image_file.read()).decode('utf-8')
|
32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
33 |
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):
|
34 |
"""Analyze the uploaded image using the InternVL3 model via OpenRouter"""
|
35 |
+
# Remove the placeholder text check
|
36 |
if not api_key:
|
37 |
+
return "Please provide an OpenRouter API key."
|
38 |
|
39 |
if image is None:
|
40 |
+
return "Please upload an image to analyze."
|
41 |
|
42 |
# Save the image temporarily
|
43 |
temp_image_path = "temp_image.jpg"
|
|
|
81 |
)
|
82 |
|
83 |
analysis_result = response.choices[0].message.content
|
84 |
+
return analysis_result
|
85 |
|
86 |
except Exception as e:
|
87 |
+
return f"Error analyzing image: {str(e)}"
|
|
|
88 |
|
89 |
finally:
|
90 |
# Clean up the temporary file
|
|
|
117 |
return "What can you identify in this nature trail image?"
|
118 |
|
119 |
numbered_prompt = "\n".join([f"{i+1}. {part}" for i, part in enumerate(prompt_parts)])
|
120 |
+
return f"For this nature trail image, please: \n{numbered_prompt}"
|
121 |
|
122 |
def create_interface():
|
123 |
"""Create the Gradio interface for the Dynamic Nature Trail Guide"""
|
|
|
165 |
analyze_button = gr.Button("Analyze Nature Image", variant="primary")
|
166 |
|
167 |
with gr.Column(scale=1):
|
168 |
+
output_text = gr.Markdown(label="Analysis Results")
|
169 |
|
170 |
# Set up the click event for the analyze button
|
171 |
analyze_button.click(
|