Skip to content

Commit 146c359

Browse files
logger and exception added
1 parent badbc53 commit 146c359

9 files changed

+132
-43
lines changed

.streamlit/config.toml

+3
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,5 @@
1+
[client]
2+
showErrorDetails = false
3+
14
[theme]
25
base="dark"

app.py

+11-8
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
import os
33
from PIL import Image
44

5+
# Streamlit imports
56
import streamlit as st
67
from streamlit_image_select import image_select
78

9+
# Local imports
810
from src.utils import input_image_details
9-
from src.llm_response import (
11+
from src.model.llm_response import (
1012
generate_image_response,
1113
generate_text_response,
1214
generate_example_image_response,
@@ -63,7 +65,7 @@
6365
start_button = st.button("Build", key="button_image_start", disabled=False)
6466

6567
# If image is uploaded or example image is selected
66-
if any([upload_img, example_img]) == True:
68+
if any([upload_img, example_img]):
6769
if "img" in locals() or "img" in globals():
6870
if start_button:
6971

@@ -121,12 +123,12 @@
121123

122124
# Raise error if any error occurs during response generation
123125
except Exception as e:
124-
st.error(f"An error occurred: {e}")
126+
st.error("Error on image prompt generation response")
127+
print(e)
125128

126-
else:
127-
if not image_upload and start_button:
128-
# Warn user to upload image
129-
st.warning("Please upload your preview image.")
129+
elif not image_upload and start_button:
130+
# Warn user to upload image
131+
st.warning("Please upload your preview image.")
130132

131133

132134
# Tell how the app should be built
@@ -160,7 +162,8 @@
160162

161163
# Raise error if any error occurs during response generation
162164
except Exception as e:
163-
st.error(f"An error occurred: {e}")
165+
st.error("Error on text prompt generation response")
166+
print(e)
164167

165168
# If text prompt is not provided and start button is clicked
166169
elif not text_prompt and start_button:

requirements.txt

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@ streamlit==1.36.0
22
Pillow==10.3.0
33
streamlit-image-select==0.6.0
44
google-generativeai==0.7.1
5-
python-dotenv==1.0.1
5+
python-dotenv==1.0.1
6+
weave

src/exception.py

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""
2+
This module defines a custom exception handling class and a function to get error message with details of the error.
3+
"""
4+
5+
# Standard Library
6+
import sys
7+
8+
# Local imports
9+
from src.logger import logging
10+
11+
12+
# Function Definition to get error message with details of the error (file name and line number) when an error occurs in the program
13+
def get_error_message(error, error_detail: sys):
14+
"""
15+
Get error message with details of the error.
16+
17+
Parameters:
18+
error (Exception): The error that occurred.
19+
error_detail (sys): The details of the error.
20+
21+
Returns:
22+
str: A string containing the error message along with the file name and line number where the error occurred.
23+
"""
24+
25+
_, _, exc_tb = error_detail.exc_info()
26+
27+
# Get error details
28+
file_name = exc_tb.tb_frame.f_code.co_filename
29+
return "Error occured in python script name [{0}] line number [{1}] error message[{2}]".format(
30+
file_name, exc_tb.tb_lineno, str(error)
31+
)
32+
33+
34+
# Custom Exception Handling Class Definition
35+
class CustomExceptionHandling(Exception):
36+
"""
37+
Custom Exception Handling
38+
39+
This class defines a custom exception that can be raised when an error occurs in the program.
40+
It takes an error message and an error detail as input and returns a formatted error message
41+
when the exception is raised.
42+
"""
43+
44+
# Constructor
45+
def __init__(self, error_message, error_detail: sys):
46+
"""Initialize the exception"""
47+
super().__init__(error_message)
48+
49+
self.error_message = get_error_message(error_message, error_detail=error_detail)
50+
51+
def __str__(self):
52+
"""String representation of the exception"""
53+
return self.error_message

src/logger.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Importing the required modules
2+
import logging
3+
import os
4+
from datetime import datetime
5+
6+
# Creating a log file with the current date and time as the name of the file
7+
LOG_FILE = f"{datetime.now().strftime('%m_%d_%Y_%H_%M_%S')}.log"
8+
9+
# Creating a logs folder if it does not exist
10+
logs_path = os.path.join(os.getcwd(), "logs", LOG_FILE)
11+
os.makedirs(logs_path, exist_ok=True)
12+
13+
# Setting the log file path and the log level
14+
LOG_FILE_PATH = os.path.join(logs_path, LOG_FILE)
15+
16+
# Configuring the logger
17+
logging.basicConfig(
18+
filename=LOG_FILE_PATH,
19+
format="[ %(asctime)s ] %(lineno)d %(name)s - %(levelname)s - %(message)s",
20+
level=logging.INFO,
21+
)

src/config.py src/model/config.py

File renamed without changes.

src/llm_response.py src/model/llm_response.py

+30-18
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
11
# Necessary imports
22
import os
3+
import sys
34
from dotenv import load_dotenv
45

56
import google.generativeai as genai
67

7-
from src.config import generation_config, safety_settings, model_name
8-
from src.prompt import system_prompt
8+
# Local imports
9+
from src.model.config import generation_config, safety_settings, model_name
10+
from src.model.prompt import system_prompt
11+
from src.logger import logging
12+
from src.exception import CustomExceptionHandling
913

1014

1115
# Load the Environment Variables from .env file
@@ -27,7 +31,7 @@
2731
instruction = "Generate the complete Streamlit app code based on the provided preview image or example. Ensure the code includes layout, functionality, and any specified features visible in the image. Incorporate common Streamlit components such as sliders, buttons, and charts where applicable, handle any specific UI elements shown in the image, and ensure proper data handling and user interactions are implemented."
2832

2933

30-
def generate_text_response(text_prompt):
34+
def generate_text_response(text_prompt: str) -> str:
3135
"""
3236
Generate Streamlit app code based on the provided text prompt.
3337
@@ -44,16 +48,19 @@ def generate_text_response(text_prompt):
4448
# Response generation for text using Gemini API
4549
response = model.generate_content(text_prompt)
4650

47-
# Extract the actual content part from the response
48-
content = response.text
49-
return content
51+
# Log the successful response generation
52+
logging.info("Response generated successfully for text prompt")
53+
54+
# Return the extracted content from the response
55+
return response.text
5056

5157
# Raise error if any error occurs during response generation
5258
except Exception as e:
53-
raise RuntimeError(f"An error occurred during text response generation: {e}")
59+
# Custom exception handling
60+
raise CustomExceptionHandling(e, sys) from e
5461

5562

56-
def generate_example_image_response(img):
63+
def generate_example_image_response(img: str) -> str:
5764
"""
5865
Generate Streamlit app code based on the provided example image.
5966
@@ -70,16 +77,18 @@ def generate_example_image_response(img):
7077
# Response generation for example image using Gemini API
7178
response = model.generate_content([instruction, img])
7279

73-
# Extract the actual content part from the response
74-
content = response.text
75-
return content
80+
# Log the successful response generation
81+
logging.info("Response generated successfully for example image")
82+
83+
# Return the extracted content from the response
84+
return response.text
7685

77-
# Raise error if any error occurs during response generation
7886
except Exception as e:
79-
raise RuntimeError(f"An error occurred during image response generation: {e}")
87+
# Custom exception handling
88+
raise CustomExceptionHandling(e, sys) from e
8089

8190

82-
def generate_image_response(image_data):
91+
def generate_image_response(image_data: list) -> str:
8392
"""
8493
Generate a response for an uploaded image using the Gemini API.
8594
@@ -96,10 +105,13 @@ def generate_image_response(image_data):
96105
# Response generation for uploaded image using Gemini API
97106
response = model.generate_content([instruction, image_data[0]])
98107

99-
# Extract the actual content part from the response
100-
content = response.text
101-
return content
108+
# Log the successful response generation
109+
logging.info("Response generated successfully for uploaded image")
110+
111+
# Return the extracted content from the response
112+
return response.text
102113

103114
# Raise error if any error occurs during response generation
104115
except Exception as e:
105-
raise RuntimeError(f"An error occurred during image response generation: {e}")
116+
# Custom exception handling
117+
raise CustomExceptionHandling(e, sys) from e

src/prompt.py src/model/prompt.py

File renamed without changes.

src/utils.py

+12-16
Original file line numberDiff line numberDiff line change
@@ -11,21 +11,17 @@ def input_image_details(uploaded_file):
1111
Raises:
1212
FileNotFoundError: If no file is uploaded.
1313
"""
14-
if uploaded_file is not None:
15-
# Read the file into bytes
16-
bytes_data = uploaded_file.getvalue()
17-
18-
# Create a list of image parts with the mime type and data
19-
image_parts = [
20-
{
21-
"mime_type": uploaded_file.type, # Get the mime type of the uploaded file
22-
"data": bytes_data,
23-
}
24-
]
14+
if uploaded_file is None:
15+
# If no file is uploaded, raise an error
16+
raise FileNotFoundError("No file uploaded")
2517

26-
# Return the list of image parts
27-
return image_parts
18+
# Read the file into bytes
19+
bytes_data = uploaded_file.getvalue()
2820

29-
# If no file is uploaded, raise an error
30-
else:
31-
raise FileNotFoundError("No file uploaded")
21+
# Return a list containing a dictionary with the mime type and data of the uploaded file
22+
return [
23+
{
24+
"mime_type": uploaded_file.type, # Get the mime type of the uploaded file
25+
"data": bytes_data,
26+
}
27+
]

0 commit comments

Comments
 (0)