shaheerawan3 commited on
Commit
35c818d
·
verified ·
1 Parent(s): 2e89c5b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +248 -131
app.py CHANGED
@@ -1,145 +1,262 @@
1
  import streamlit as st
2
- import requests
3
- import json
 
 
 
 
 
 
4
  from pathlib import Path
 
 
 
5
 
6
- # Pre-defined components and templates
7
- COMPONENTS = {
8
- "navbar": """
9
- <nav class="bg-white shadow">
10
- <div class="max-w-7xl mx-auto px-4">
11
- <div class="flex justify-between h-16">
12
- <div class="flex">
13
- <div class="flex-shrink-0 flex items-center">
14
- <a href="/" class="text-xl font-bold">Logo</a>
15
- </div>
16
- <div class="hidden sm:ml-6 sm:flex sm:space-x-8">
17
- <a href="#" class="text-gray-900 inline-flex items-center px-1 pt-1">Home</a>
18
- <a href="#" class="text-gray-500 hover:text-gray-900 inline-flex items-center px-1 pt-1">About</a>
19
- <a href="#" class="text-gray-500 hover:text-gray-900 inline-flex items-center px-1 pt-1">Services</a>
20
- <a href="#" class="text-gray-500 hover:text-gray-900 inline-flex items-center px-1 pt-1">Contact</a>
21
- </div>
22
- </div>
23
- </div>
24
- </div>
25
- </nav>
26
- """,
27
- "hero": """
28
- <div class="relative bg-white overflow-hidden">
29
- <div class="max-w-7xl mx-auto">
30
- <div class="relative z-10 pb-8 bg-white sm:pb-16 md:pb-20 lg:max-w-2xl lg:w-full lg:pb-28 xl:pb-32">
31
- <main class="mt-10 mx-auto max-w-7xl px-4 sm:mt-12 sm:px-6 md:mt-16 lg:mt-20 lg:px-8 xl:mt-28">
32
- <div class="sm:text-center lg:text-left">
33
- <h1 class="text-4xl tracking-tight font-extrabold text-gray-900 sm:text-5xl md:text-6xl">
34
- <span class="block xl:inline">Your Awesome</span>
35
- <span class="block text-indigo-600 xl:inline">Website Title</span>
36
- </h1>
37
- <p class="mt-3 text-base text-gray-500 sm:mt-5 sm:text-lg sm:max-w-xl sm:mx-auto md:mt-5 md:text-xl lg:mx-0">
38
- Your compelling description goes here.
39
- </p>
40
- <div class="mt-5 sm:mt-8 sm:flex sm:justify-center lg:justify-start">
41
- <div class="rounded-md shadow">
42
- <a href="#" class="w-full flex items-center justify-center px-8 py-3 border border-transparent text-base font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 md:py-4 md:text-lg md:px-10">
43
- Get Started
44
- </a>
45
- </div>
46
- </div>
47
- </div>
48
- </main>
49
- </div>
50
- </div>
51
- </div>
52
- """,
53
- "features": """
54
- <div class="py-12 bg-white">
55
- <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
56
- <div class="grid grid-cols-1 gap-8 sm:grid-cols-2 lg:grid-cols-3">
57
- <!-- Feature 1 -->
58
- <div class="p-6 border rounded-lg">
59
- <h3 class="text-lg font-medium text-gray-900">Feature 1</h3>
60
- <p class="mt-2 text-base text-gray-500">Description of feature 1</p>
61
- </div>
62
- <!-- Feature 2 -->
63
- <div class="p-6 border rounded-lg">
64
- <h3 class="text-lg font-medium text-gray-900">Feature 2</h3>
65
- <p class="mt-2 text-base text-gray-500">Description of feature 2</p>
66
- </div>
67
- <!-- Feature 3 -->
68
- <div class="p-6 border rounded-lg">
69
- <h3 class="text-lg font-medium text-gray-900">Feature 3</h3>
70
- <p class="mt-2 text-base text-gray-500">Description of feature 3</p>
71
- </div>
72
- </div>
73
- </div>
74
- </div>
75
- """
76
- }
77
 
78
- def generate_website():
79
- # Base HTML template with Tailwind CSS
80
- html_template = """
81
- <!DOCTYPE html>
82
- <html lang="en">
83
- <head>
84
- <meta charset="UTF-8">
85
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
86
- <title>{title}</title>
87
- <script src="https://cdn.tailwindcss.com"></script>
88
- </head>
89
- <body>
90
- {components}
91
- </body>
92
- </html>
93
- """
94
- return html_template
95
 
96
- def main():
97
- st.set_page_config(page_title="Fast Web Builder", layout="wide")
98
-
99
- st.title("🚀 Fast Web Builder")
100
-
101
- # Simple configuration
102
- title = st.text_input("Website Title", "My Awesome Website")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
- # Component selection
105
- st.subheader("Select Components")
106
- use_navbar = st.checkbox("Navigation Bar", value=True)
107
- use_hero = st.checkbox("Hero Section", value=True)
108
- use_features = st.checkbox("Features Section", value=True)
109
 
110
- # Color scheme
111
- color_scheme = st.selectbox(
112
- "Color Scheme",
113
- ["Default", "Dark", "Light", "Colorful"]
114
- )
115
 
116
- if st.button("Generate Website"):
117
- # Build components string
118
- components = ""
119
- if use_navbar:
120
- components += COMPONENTS["navbar"]
121
- if use_hero:
122
- components += COMPONENTS["hero"]
123
- if use_features:
124
- components += COMPONENTS["features"]
125
-
126
- # Generate complete website
127
- website = generate_website().format(
128
- title=title,
129
- components=components
130
  )
131
 
132
- # Show preview
133
- st.subheader("Preview")
134
- st.components.v1.html(website, height=600)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
- # Download option
137
- st.download_button(
138
- "Download Website",
139
- website,
140
- file_name="website.html",
141
- mime="text/html"
 
 
 
 
 
 
 
 
 
 
 
142
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
  if __name__ == "__main__":
145
- main()
 
1
  import streamlit as st
2
+ from langchain.embeddings import HuggingFaceEmbeddings
3
+ from langchain.vectorstores import FAISS
4
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain.document_loaders import TextLoader, DirectoryLoader
6
+ from langchain.chains import RetrievalQA
7
+ from langchain.prompts import PromptTemplate
8
+ from langchain.chat_models import ChatOpenAI
9
+ import os
10
  from pathlib import Path
11
+ import json
12
+ import logging
13
+ from typing import Dict, List, Optional
14
 
15
+ class WebDevRAG:
16
+ def __init__(self, api_key: str, model_name: str = "gpt-4"):
17
+ self.api_key = api_key
18
+ self.model_name = model_name
19
+ self.embeddings = HuggingFaceEmbeddings(
20
+ model_name="sentence-transformers/all-MiniLM-L6-v2"
21
+ )
22
+ self.initialize_logging()
23
+ self.initialize_vector_store()
24
+ self.setup_llm()
25
+
26
+ def initialize_logging(self):
27
+ logging.basicConfig(
28
+ level=logging.INFO,
29
+ format='%(asctime)s - %(levelname)s - %(message)s'
30
+ )
31
+ self.logger = logging.getLogger(__name__)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ def initialize_vector_store(self):
34
+ """Initialize FAISS vector store with web development knowledge"""
35
+ try:
36
+ # Load from existing if available
37
+ if Path("vector_store").exists():
38
+ self.vector_store = FAISS.load_local(
39
+ "vector_store",
40
+ self.embeddings
41
+ )
42
+ self.logger.info("Loaded existing vector store")
43
+ else:
44
+ self.create_new_vector_store()
45
+ except Exception as e:
46
+ self.logger.error(f"Vector store initialization failed: {e}")
47
+ raise
 
 
48
 
49
+ def create_new_vector_store(self):
50
+ """Create new vector store from knowledge base"""
51
+ loader = DirectoryLoader(
52
+ "./knowledge_base",
53
+ glob="**/*.txt",
54
+ loader_cls=TextLoader
55
+ )
56
+ documents = loader.load()
57
+ text_splitter = RecursiveCharacterTextSplitter(
58
+ chunk_size=1000,
59
+ chunk_overlap=200
60
+ )
61
+ texts = text_splitter.split_documents(documents)
62
+ self.vector_store = FAISS.from_documents(texts, self.embeddings)
63
+ self.vector_store.save_local("vector_store")
64
+ self.logger.info("Created new vector store")
65
+
66
+ def setup_llm(self):
67
+ """Setup LLM with custom prompts"""
68
+ self.llm = ChatOpenAI(
69
+ model_name=self.model_name,
70
+ temperature=0.7,
71
+ api_key=self.api_key
72
+ )
73
+
74
+ self.qa_prompt = PromptTemplate(
75
+ template="""You are an expert web developer AI assistant. Using the context provided,
76
+ generate high-quality, production-ready code for the user's request. Include best practices,
77
+ security considerations, and modern development patterns.
78
+
79
+ Context: {context}
80
+
81
+ Question: {question}
82
+
83
+ Provide a detailed, professional solution with explanations for key decisions.""",
84
+ input_variables=["context", "question"]
85
+ )
86
+
87
+ self.qa_chain = RetrievalQA.from_chain_type(
88
+ llm=self.llm,
89
+ chain_type="stuff",
90
+ retriever=self.vector_store.as_retriever(
91
+ search_kwargs={"k": 5}
92
+ ),
93
+ chain_type_kwargs={"prompt": self.qa_prompt}
94
+ )
95
+
96
+ def generate_code(self,
97
+ description: str,
98
+ tech_stack: Dict[str, str],
99
+ requirements: List[str]) -> Dict:
100
+ """
101
+ Generate web application code based on description and requirements
102
+
103
+ Args:
104
+ description: Project description
105
+ tech_stack: Dictionary of technology choices
106
+ requirements: List of specific requirements
107
+
108
+ Returns:
109
+ Dictionary containing generated code and documentation
110
+ """
111
+ try:
112
+ # Construct detailed prompt
113
+ prompt = f"""
114
+ Project Description: {description}
115
+
116
+ Technology Stack:
117
+ {json.dumps(tech_stack, indent=2)}
118
+
119
+ Requirements:
120
+ {json.dumps(requirements, indent=2)}
121
+
122
+ Generate a complete solution including:
123
+ 1. Frontend code (component architecture)
124
+ 2. Backend API design
125
+ 3. Database schema
126
+ 4. Security implementations
127
+ 5. Deployment considerations
128
+ """
129
+
130
+ # Get RAG-enhanced response
131
+ response = self.qa_chain.run(prompt)
132
+
133
+ # Process and structure the response
134
+ return self.process_response(response)
135
+
136
+ except Exception as e:
137
+ self.logger.error(f"Code generation failed: {e}")
138
+ raise
139
+
140
+ def process_response(self, response: str) -> Dict:
141
+ """Process and structure the LLM response"""
142
+ # Add processing logic here
143
+ return {
144
+ "frontend": self.extract_frontend_code(response),
145
+ "backend": self.extract_backend_code(response),
146
+ "database": self.extract_database_schema(response),
147
+ "documentation": self.extract_documentation(response)
148
+ }
149
+
150
+ def extract_frontend_code(self, response: str) -> Dict:
151
+ # Add extraction logic
152
+ pass
153
+
154
+ def extract_backend_code(self, response: str) -> Dict:
155
+ # Add extraction logic
156
+ pass
157
+
158
+ def extract_database_schema(self, response: str) -> Dict:
159
+ # Add extraction logic
160
+ pass
161
+
162
+ def extract_documentation(self, response: str) -> str:
163
+ # Add extraction logic
164
+ pass
165
+
166
+ def create_streamlit_interface():
167
+ st.set_page_config(page_title="AI Web Developer", layout="wide")
168
 
169
+ # API key handling
170
+ api_key = st.secrets["OPENAI_API_KEY"]
 
 
 
171
 
172
+ if "rag_system" not in st.session_state:
173
+ st.session_state.rag_system = WebDevRAG(api_key)
174
+
175
+ st.title("AI Web Development Assistant")
 
176
 
177
+ # Project Configuration
178
+ with st.form("project_config"):
179
+ description = st.text_area(
180
+ "Project Description",
181
+ "Describe your web application in detail..."
 
 
 
 
 
 
 
 
 
182
  )
183
 
184
+ # Technology Stack Selection
185
+ col1, col2 = st.columns(2)
186
+ with col1:
187
+ frontend = st.selectbox(
188
+ "Frontend Framework",
189
+ ["React", "Vue", "Angular", "Next.js"]
190
+ )
191
+ database = st.selectbox(
192
+ "Database",
193
+ ["PostgreSQL", "MongoDB", "MySQL"]
194
+ )
195
+
196
+ with col2:
197
+ backend = st.selectbox(
198
+ "Backend Framework",
199
+ ["Node.js/Express", "Django", "FastAPI"]
200
+ )
201
+ auth = st.selectbox(
202
+ "Authentication",
203
+ ["JWT", "OAuth2", "Session-based"]
204
+ )
205
 
206
+ # Additional Requirements
207
+ requirements = st.multiselect(
208
+ "Additional Requirements",
209
+ [
210
+ "REST API",
211
+ "GraphQL",
212
+ "Real-time updates",
213
+ "File upload",
214
+ "Email integration",
215
+ "Payment processing",
216
+ "Admin dashboard",
217
+ "Analytics",
218
+ "SEO optimization",
219
+ "Mobile responsiveness",
220
+ "Automated testing",
221
+ "CI/CD pipeline"
222
+ ]
223
  )
224
+
225
+ submitted = st.form_submit_button("Generate Solution")
226
+
227
+ if submitted:
228
+ with st.spinner("Generating comprehensive solution..."):
229
+ tech_stack = {
230
+ "frontend": frontend,
231
+ "backend": backend,
232
+ "database": database,
233
+ "authentication": auth
234
+ }
235
+
236
+ try:
237
+ result = st.session_state.rag_system.generate_code(
238
+ description,
239
+ tech_stack,
240
+ requirements
241
+ )
242
+
243
+ # Display results in organized tabs
244
+ tabs = st.tabs(["Frontend", "Backend", "Database", "Documentation"])
245
+
246
+ with tabs[0]:
247
+ st.code(result["frontend"], language="javascript")
248
+
249
+ with tabs[1]:
250
+ st.code(result["backend"], language="python")
251
+
252
+ with tabs[2]:
253
+ st.code(result["database"], language="sql")
254
+
255
+ with tabs[3]:
256
+ st.markdown(result["documentation"])
257
+
258
+ except Exception as e:
259
+ st.error(f"An error occurred: {str(e)}")
260
 
261
  if __name__ == "__main__":
262
+ create_streamlit_interface()