bala00712200502 commited on
Commit
893d44e
Β·
verified Β·
1 Parent(s): 1ba926f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +87 -73
app.py CHANGED
@@ -1,86 +1,100 @@
1
- import os
2
- from dotenv import load_dotenv
3
  import streamlit as st
4
- from crewai import Agent, Task, Crew, Process
5
  import google.generativeai as genai
6
 
7
- # === Load environment variables ===
8
- load_dotenv() # loads API_KEY from .env
9
-
10
- # === API Key Config ===
11
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
12
- os.environ["GEMINI_API_KEY"] = GEMINI_API_KEY # Set for potential other uses
13
-
14
- # Configure Gemini
15
  genai.configure(api_key=GEMINI_API_KEY)
16
 
17
- # === Streamlit UI Config ===
18
- st.set_page_config(
19
- page_title="β˜• Java Coding Assistant",
20
- page_icon="β˜•",
21
- layout="wide"
22
- )
23
 
24
- # Initialize chat history
25
- if "messages" not in st.session_state:
26
- st.session_state.messages = []
 
 
 
 
 
 
27
 
28
- # Java Coding Assistant function
29
- def java_coding_assistant(query: str, temperature: float = 0.7) -> str:
30
- try:
31
- # Initialize Gemini model
32
- model = genai.GenerativeModel('gemini-1.5-pro')
33
-
34
- # Create prompt with the query
35
  prompt = f"""
36
- You are a Senior Java Full Stack Developer with 10+ years of experience.
37
- Provide a comprehensive solution for this Java-related query:
38
- {query}
39
-
40
- Your response should include:
41
- 1. Problem analysis
42
- 2. Complete Java code solution with proper syntax
43
- 3. Explanation of key concepts
44
- 4. Best practices
45
- 5. Potential edge cases
46
-
47
- Format your response with:
48
- - Problem breakdown
49
- - Complete Java code with syntax highlighting (use ```java markers)
50
- - Detailed explanation
51
- - Best practices
52
- - Runtime complexity analysis (if applicable)
53
  """
54
-
55
- # Generate response
56
- response = model.generate_content(prompt)
57
-
58
- # Get the text from the response
59
- result = response.text
60
-
61
- # Replace java fences for Streamlit if needed
62
- if "```java" in result:
63
- result = result.replace("```java", "```python")
64
- return result
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- except Exception as e:
67
- return f"❌ Error: {e}"
 
68
 
69
- # === Streamlit interface ===
70
- st.title("β˜• Java Coding Assistant")
71
- st.caption("Ask me anything about Java backend, Android development, or coding problems")
 
 
 
 
 
 
 
 
72
 
73
- # Render chat history
74
- for msg in st.session_state.messages:
75
- with st.chat_message(msg["role"]):
76
- st.markdown(msg["content"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
- # Chat input
79
- if user_input := st.chat_input("Ask your Java question (e.g., 'How to implement REST API in Spring Boot?'):"):
80
- st.session_state.messages.append({"role": "user", "content": user_input})
81
- with st.chat_message("user"):
82
- st.markdown(user_input)
83
- with st.chat_message("assistant"):
84
- answer = java_coding_assistant(user_input)
85
- st.markdown(answer, unsafe_allow_html=True)
86
- st.session_state.messages.append({"role": "assistant", "content": answer})
 
1
+ # Importing libraries
 
2
  import streamlit as st
 
3
  import google.generativeai as genai
4
 
5
+ # Configuring Gemini API Key
6
+ GEMINI_API_KEY = "AIzaSyCdMDLOh9jv4H7Mj-4Qtq8f_SAuuPejAHE" # Replace with your actual API key
 
 
 
 
 
 
7
  genai.configure(api_key=GEMINI_API_KEY)
8
 
9
+ # Function to query Gemini API to generate response
10
+ def generate_response(prompt):
11
+ """Uses Gemini API to generate AI-powered responses."""
12
+ model = genai.GenerativeModel("gemini-2.0-flash")
13
+ response = model.generate_content(prompt)
14
+ return response.text
15
 
16
+ # Function to refine and clarify user inputs
17
+ def refine_user_inputs(inputs):
18
+ """Checks for missing details and asks clarifying questions."""
19
+ missing_fields = []
20
+
21
+ # Identify missing inputs
22
+ for key, value in inputs.items():
23
+ if not value or value == "Select an option":
24
+ missing_fields.append(key)
25
 
26
+ if missing_fields:
27
+ # Generate a dynamic clarification prompt
28
+ missing_fields_str = ", ".join(missing_fields)
 
 
 
 
29
  prompt = f"""
30
+ The user has provided incomplete travel details. They have not specified the following: {missing_fields_str}.
31
+ Ask clear, user-friendly follow-up questions to fill in these gaps.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  """
33
+ return generate_response(prompt)
34
+
35
+ return "Thank you for providing all details! Proceeding with itinerary generation for required no.of days."
36
+
37
+ # Function to generate a detailed travel itinerary
38
+ def generate_itinerary(user_inputs):
39
+ """Creates a structured day-by-day itinerary based on user preferences."""
40
+ prompt = f"""
41
+ Generate a **{user_inputs.get('trip_duration')}-day travel itinerary** for {user_inputs.get('destination')}.
42
+ Customize it based on:
43
+ - Budget: {user_inputs.get('budget')}
44
+ - Interests: {user_inputs.get('preferences')}
45
+ - Purpose: {user_inputs.get('purpose')}
46
+ - Accommodation: {user_inputs.get('accommodation')}
47
+ - Transport: {user_inputs.get('transport')}
48
+ - Dietary Needs: {user_inputs.get('dietary')}
49
+
50
+ Ensure the itinerary includes:
51
+ - Morning, Afternoon, and Evening Activities
52
+ - Top attractions & restaurants
53
+ - Relaxation time & hidden gems
54
+ - Logical time slots for activities
55
+ """
56
+ return generate_response(prompt)
57
 
58
+ # πŸ”Ή Streamlit UI
59
+ st.title("AI-Powered Traveler Guide")
60
+ st.write("Plan your trip with a personalized AI-generated itinerary!")
61
 
62
+ # User input fields
63
+ destination = st.text_input("Where are you traveling to?")
64
+ starting_location = st.text_input("Where are you traveling from?")
65
+ budget = st.selectbox("Budget:", ["Select an option", "Low", "Mid-range", "Luxury"])
66
+ trip_duration = st.number_input("Trip Duration (days):", min_value=1, max_value=30, step=1)
67
+ travel_dates = st.text_input("Provide me Travel Dates (e.g., Jan 10 - Jan 17):")
68
+ purpose = st.selectbox("Trip Purpose:", ["Select an option", "Vacation", "Business", "Adventure", "Honeymoon", "Cultural"])
69
+ preferences = st.multiselect("What interests you?", ["Nature", "Culture", "Food", "Shopping", "Adventure", "History"])
70
+ accommodation = st.selectbox("Accommodation Preference:", ["Select an option", "Luxury Hotel", "Budget Hotel", "Hostel", "Airbnb"])
71
+ transport = st.selectbox("Preferred Transport:", ["Select an option", "Public Transport", "Car Rental", "Walking", "Private Tours"])
72
+ dietary = st.selectbox("Dietary Preferences:", ["Select an option", "No Preference", "Vegetarian", "Vegan", "Non-Vegetarian", "Halal"])
73
 
74
+ # Button to generate itinerary
75
+ if st.button("Generate Itinerary"):
76
+ user_inputs = {
77
+ "destination": destination,
78
+ "starting_location": starting_location,
79
+ "budget": budget,
80
+ "trip_duration": trip_duration,
81
+ "travel_dates": travel_dates,
82
+ "purpose": purpose,
83
+ "preferences": ", ".join(preferences) if preferences else "Not specified",
84
+ "accommodation": accommodation,
85
+ "transport": transport,
86
+ "dietary": dietary,
87
+ }
88
+
89
+ # Step 1: Check and clarify missing inputs
90
+ st.write("Checking the provided travel details...")
91
+ refinement_message = refine_user_inputs(user_inputs)
92
+ st.write(refinement_message)
93
 
94
+ if "Thank you for providing all details!" in refinement_message:
95
+ # Step 2: Generate Itinerary
96
+ st.write("Creating your AI-powered travel itinerary...")
97
+ itinerary = generate_itinerary(user_inputs)
98
+ st.write(itinerary)
99
+ else:
100
+ st.warning("Some details are missing, please provide the missing details before generating the itinerary.")