shaheerawan3 commited on
Commit
668d0a2
·
verified ·
1 Parent(s): 3cef9a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +122 -188
app.py CHANGED
@@ -1,262 +1,196 @@
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()
 
1
  import streamlit as st
2
+ from langchain_community.embeddings import HuggingFaceEmbeddings
3
+ from langchain_community.vectorstores import Chroma
4
  from langchain.text_splitter import RecursiveCharacterTextSplitter
5
+ from langchain_community.llms import CTransformers
6
  from langchain.chains import RetrievalQA
7
  from langchain.prompts import PromptTemplate
 
8
  import os
9
  from pathlib import Path
 
10
  import logging
 
11
 
12
+ class LocalWebDevRAG:
13
+ def __init__(self):
 
 
 
 
 
14
  self.initialize_logging()
15
+ self.setup_embeddings()
16
  self.setup_llm()
17
+ self.initialize_vector_store()
18
+
19
  def initialize_logging(self):
20
+ logging.basicConfig(level=logging.INFO)
 
 
 
21
  self.logger = logging.getLogger(__name__)
22
 
23
+ def setup_embeddings(self):
24
+ self.embeddings = HuggingFaceEmbeddings(
25
+ model_name="all-MiniLM-L6-v2",
26
+ model_kwargs={'device': 'cpu'}
27
+ )
28
+
29
+ def setup_llm(self):
30
+ # Using CodeLlama local model
31
+ llm_config = {
32
+ 'model': 'codellama-7b-instruct.ggmlv3.Q4_K_M.bin',
33
+ 'model_type': 'llama',
34
+ 'max_new_tokens': 2048,
35
+ 'temperature': 0.7,
36
+ 'context_length': 2048,
37
+ }
38
+
39
+ self.llm = CTransformers(**llm_config)
40
+
41
+ self.qa_prompt = PromptTemplate(
42
+ template="""You are an expert web developer. Based on the context and request,
43
+ generate production-ready code.
44
+
45
+ Context: {context}
46
+ Question: {question}
47
+
48
+ Provide a detailed solution with explanations.""",
49
+ input_variables=["context", "question"]
50
+ )
51
+
52
  def initialize_vector_store(self):
 
53
  try:
54
+ # Create or load vector store
55
+ if not Path("chroma_db").exists():
56
+ self.create_new_vector_store()
57
+ else:
58
+ self.vector_store = Chroma(
59
+ persist_directory="chroma_db",
60
+ embedding_function=self.embeddings
61
  )
62
  self.logger.info("Loaded existing vector store")
63
+
64
+ self.qa_chain = RetrievalQA.from_chain_type(
65
+ llm=self.llm,
66
+ chain_type="stuff",
67
+ retriever=self.vector_store.as_retriever(),
68
+ chain_type_kwargs={"prompt": self.qa_prompt}
69
+ )
70
+
71
  except Exception as e:
72
  self.logger.error(f"Vector store initialization failed: {e}")
73
  raise
74
 
75
  def create_new_vector_store(self):
76
+ # Example code snippets and documentation
77
+ documents = [
78
+ "React component best practices...",
79
+ "API security implementations...",
80
+ "Database schema designs...",
81
+ # Add more code examples and documentation
82
+ ]
83
+
84
  text_splitter = RecursiveCharacterTextSplitter(
85
  chunk_size=1000,
86
  chunk_overlap=200
87
  )
88
+ texts = text_splitter.split_text('\n\n'.join(documents))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ self.vector_store = Chroma.from_texts(
91
+ texts,
92
+ self.embeddings,
93
+ persist_directory="chroma_db"
 
 
 
94
  )
95
+ self.logger.info("Created new vector store")
96
 
97
+ def generate_code(self, description, tech_stack, requirements):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  try:
 
99
  prompt = f"""
100
+ Create a web application with:
101
+ Description: {description}
102
+ Tech Stack: {tech_stack}
103
+ Requirements: {requirements}
 
 
 
104
 
105
+ Provide:
106
+ 1. Frontend components
107
+ 2. Backend API
108
  3. Database schema
109
+ 4. Setup instructions
 
110
  """
111
 
 
112
  response = self.qa_chain.run(prompt)
 
 
113
  return self.process_response(response)
114
 
115
  except Exception as e:
116
+ self.logger.error(f"Generation failed: {e}")
117
  raise
118
 
119
+ def process_response(self, response):
120
+ # Basic response processing
 
121
  return {
122
+ "frontend": response.split("Frontend:")[1].split("Backend:")[0] if "Frontend:" in response else "",
123
+ "backend": response.split("Backend:")[1].split("Database:")[0] if "Backend:" in response else "",
124
+ "database": response.split("Database:")[1].split("Setup:")[0] if "Database:" in response else "",
125
+ "setup": response.split("Setup:")[1] if "Setup:" in response else response
126
  }
127
 
128
+ def main():
129
+ st.set_page_config(page_title="Local Web Development AI", layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
 
131
+ st.title("🚀 Web Development AI Assistant")
132
+ st.write("Generate web applications using local AI - no API key required!")
133
 
134
+ if 'rag_system' not in st.session_state:
135
+ with st.spinner("Initializing AI system... (this may take a few minutes on first run)"):
136
+ st.session_state.rag_system = LocalWebDevRAG()
137
+
138
+ with st.form("project_specs"):
139
  description = st.text_area(
140
  "Project Description",
141
+ placeholder="Describe your web application..."
142
  )
143
 
 
144
  col1, col2 = st.columns(2)
145
  with col1:
146
  frontend = st.selectbox(
147
+ "Frontend",
148
+ ["React", "Vue", "Angular"]
149
  )
150
  database = st.selectbox(
151
  "Database",
152
+ ["MongoDB", "PostgreSQL", "MySQL"]
153
  )
154
+
155
  with col2:
156
  backend = st.selectbox(
157
+ "Backend",
158
+ ["Node.js", "Python/FastAPI", "Python/Django"]
159
  )
160
+ features = st.multiselect(
161
+ "Features",
162
+ ["Authentication", "REST API", "File Upload", "Real-time Updates"]
163
  )
164
+
165
+ submitted = st.form_submit_button("Generate Code")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
  if submitted:
168
+ try:
169
+ with st.spinner("Generating your application..."):
 
 
 
 
 
 
 
170
  result = st.session_state.rag_system.generate_code(
171
  description,
172
+ {
173
+ "frontend": frontend,
174
+ "backend": backend,
175
+ "database": database
176
+ },
177
+ features
178
  )
179
 
180
+ # Display results
181
+ tabs = st.tabs(["Frontend", "Backend", "Database", "Setup"])
182
 
183
  with tabs[0]:
184
+ st.code(result["frontend"])
 
185
  with tabs[1]:
186
+ st.code(result["backend"])
 
187
  with tabs[2]:
188
+ st.code(result["database"])
 
189
  with tabs[3]:
190
+ st.markdown(result["setup"])
191
+
192
+ except Exception as e:
193
+ st.error(f"An error occurred: {str(e)}")
194
 
195
  if __name__ == "__main__":
196
+ main()