subashpoudel commited on
Commit
c83a73c
·
1 Parent(s): af895b2

Added .env

Browse files
Files changed (3) hide show
  1. .gitignore +1 -1
  2. main.py +0 -228
  3. test.py +0 -52
.gitignore CHANGED
@@ -1,2 +1,2 @@
 
1
  myenv
2
- extracted_data.csv
 
1
+ .env
2
  myenv
 
main.py DELETED
@@ -1,228 +0,0 @@
1
- from fastapi import FastAPI , UploadFile , File , Form
2
- from fastapi.responses import JSONResponse
3
- from pydantic import BaseModel
4
- from src.genai.brainstroming_agent.agent import brainstroming_graph
5
- import pandas as pd
6
- from typing import Optional , List
7
- from src.genai.context_analysis_agent.agent import IntroductionChatbot
8
- from src.genai.business_interaction_agent.agent import BusinessInteractionChatbot
9
- from src.genai.context_analysis_agent.utils.utils import save_to_db
10
- import ast
11
- from src.genai.orchestration_agent.agent import orchestration_chat
12
- from src.genai.orchestration_agent.utils.utils import caption_image , show_analytics
13
- from src.genai.brainstroming_agent.utils.utils import encode_image_to_base64 , generate_final_story, generate_image
14
- from src.genai.idea_to_budget_agent.agent import budget_calculator
15
- from src.genai.ideation_agent.agent import ideation_graph
16
- from langgraph.errors import GraphRecursionError
17
- from src.genai.human_refined_ideation.agent import human_refined_idea
18
- from dummy_state import stored_data, long_term_memory
19
- import json
20
-
21
- # Store brainstorming results per thread_id
22
-
23
- app = FastAPI()
24
- context_analysis_graph = IntroductionChatbot()
25
- business_interaction_graph = BusinessInteractionChatbot()
26
- idea_graph = ideation_graph()
27
- brainstrom_graph = brainstroming_graph()
28
- human_refine_graph = human_refined_idea()
29
- # orchestrate_graph = orchestration_chat()
30
-
31
-
32
- class OrchestrationRequest(BaseModel):
33
- message: str
34
- image_base64 : Optional[list] = []
35
-
36
- @app.post("/orchestration")
37
- def orchestration_endpoint(request:OrchestrationRequest):
38
- print('Image:',request.image_base64)
39
- result = orchestration_chat(request.message , request.image_base64)
40
- if result.image_caption != '':
41
- stored_data['image_caption']=result.image_caption
42
- if result.video_idea !='' or result.video_idea != 'null':
43
- stored_data['refined_ideation']= result.video_idea
44
- if result.video_story!='' or result.video_story!='null':
45
- stored_data['final_story']= result.video_story
46
- print('Idea:',stored_data['refined_ideation'])
47
- print('Story:', stored_data['final_story'])
48
-
49
- return {'tool_response': result.tool ,
50
- 'message_response': result.query_response,
51
- 'image_caption':result.image_caption,
52
- 'video_idea': result.video_idea,
53
- 'video_story': result.video_story}
54
-
55
- class UserMessage(BaseModel):
56
- message: str
57
- @app.post("/context-analysis")
58
- def context_analysis(msg: UserMessage):
59
- response = context_analysis_graph.chat(msg.message)
60
- if context_analysis_graph.is_complete(response):
61
- details = context_analysis_graph.extract_details()
62
- if type(details) != dict:
63
- details = details.model_dump()
64
- print('Business_details:',details)
65
- if isinstance(details, str):
66
- details= ast.literal_eval(details)
67
- print('Details Type:',type(details))
68
- # save_to_db(details)
69
- stored_data['business_details'] = details
70
- context_analysis_graph.reset()
71
- return {"response": response, "business_details": details, "complete": True}
72
- return {"response": response, "complete": False}
73
-
74
- @app.post("/show-analytics")
75
- def show_analytics_endpoint():
76
- response = show_analytics(stored_data['business_details'])
77
- return {'response': response}
78
-
79
-
80
- @app.post("/business-interaction")
81
- def business_interaction(interaction: str):
82
- response,business_details = business_interaction_graph.chat(interaction , stored_data['business_details'])
83
- stored_data['business_details']=business_details
84
- return {'response': response}
85
-
86
- class IdeationRequest(BaseModel):
87
- topic : List[str]
88
-
89
- @app.post("/ideation")
90
- def ideation_endpoint():
91
- config={"recursion_limit":15, "configurable": {"thread_id": "ideation_thread123"}}
92
- try:
93
- result = idea_graph.invoke(
94
- {
95
- 'business_details': [stored_data['business_details']],
96
- 'image_caption': [stored_data['image_caption'] if 'image_caption' in stored_data else ""]
97
- },
98
- config=config,
99
- )
100
- stored_data['final_ideation'] = result['improver_response'][-1]
101
- stored_data['final_ideation']=ast.literal_eval(stored_data['final_ideation'])
102
-
103
- return {'response':ast.literal_eval(result['improver_response'][-1])}
104
- except GraphRecursionError:
105
- result = idea_graph.get_state({"configurable": {"thread_id": "ideation_thread123"}})
106
- return {'response': ast.literal_eval(result[0])}
107
-
108
- class RefineIdeationRequest(BaseModel):
109
- query: str
110
- thread_id: Optional[str]="refine_ideas_thread"
111
-
112
-
113
- @app.post("/human-idea-refining")
114
- def human_idea_refine_endpoint(request:RefineIdeationRequest):
115
- stored_data['human_ideation_interactions'].append({"role": "user", "content": request.query})
116
- response = human_refine_graph.invoke(
117
- {
118
- 'query': stored_data['human_ideation_interactions'],
119
- 'business_details': stored_data["business_details"],
120
- 'final_ideation': stored_data.get('final_ideation',["","","",""]),
121
- },config={"configurable": {"thread_id": request.thread_id}}
122
- )
123
- stored_data['human_ideation_interactions'].append({"role": "assistant", "content": response['result']})
124
- stored_data['refined_ideation'] = stored_data['human_ideation_interactions'][-1]['content']
125
- return {'response' : stored_data['human_ideation_interactions'][-1]['content'] }
126
-
127
-
128
-
129
- @app.post("/budget-mapping")
130
- def budget_mapping_endpoint():
131
- result = budget_calculator(stored_data["business_details"],stored_data['final_ideation'])
132
- return {'response':result}
133
-
134
-
135
- class BrainstormRequest(BaseModel):
136
- preferred_topics: Optional[list] = []
137
- image_base64_list: Optional[list] = []
138
- thread_id: Optional[str]="default-session"
139
-
140
- @app.post("/brainstorm")
141
- def brainstroming_endpoint(
142
- request: BrainstormRequest, # 🔥 Full JSON body here
143
- ):
144
- idea = (
145
- [stored_data['refined_ideation']]
146
- if stored_data.get('refined_ideation')
147
- else [str(stored_data['final_ideation'])]
148
- if stored_data.get('final_ideation')
149
- else ['''I don't have any idea right now. Create your own **very creative** and **out of the box** video idea and generate the story for now.'''])
150
-
151
- result = brainstrom_graph.invoke({
152
- # 'idea': [stored_data.get('refined_ideation', 'final_ideation', )],
153
- 'idea': idea,
154
- 'images': request.image_base64_list,
155
- 'latest_preferred_topics': request.preferred_topics,
156
- 'business_details': stored_data['business_details']
157
- },
158
- config={"configurable": {"thread_id": request.thread_id}})
159
-
160
- stored_data['brainstroming_response'] = result
161
-
162
- return {'response':{
163
- "story": result['stories'][-1],
164
- "brainstorming_topics": result['brainstroming_topics'][-1]
165
- }}
166
-
167
-
168
-
169
- @app.post("/generate-final-story")
170
- def generate_final_story_endpoint():
171
- final_story = generate_final_story(
172
- stored_data.get("brainstroming_response") or stored_data.get("business_details")
173
- )
174
- stored_data['final_story']=final_story
175
- return {
176
- 'response': final_story
177
- }
178
-
179
- # stored_data['final_story']= '''A cinematic journey follows a street magician\'s
180
- # metamorphosis from a mere trickster to a powerful performer, as he transforms his act with newfound physical strength, effortlessly executing death-defying stunts, and inspiring a captivated crowd to take action, all set against a
181
- # backdrop of urban grandeur and pulsing energy.'''
182
-
183
-
184
- @app.post("/generate-image")
185
- def generate_image_endpoint():
186
- image = generate_image(str(stored_data.get('final_story','''I don't have any story right now. Just use the business details for now.'''))
187
- ,str(stored_data.get('business_details'))
188
- ,str(stored_data.get('refined_ideation','''I don't have any idea right now. Just use the business details for now.''')))
189
- stored_data['generated_image']=image
190
- return {
191
- 'response':image
192
- }
193
-
194
-
195
-
196
-
197
-
198
-
199
-
200
-
201
-
202
-
203
-
204
-
205
-
206
-
207
-
208
-
209
-
210
-
211
-
212
-
213
-
214
-
215
-
216
-
217
-
218
-
219
-
220
-
221
-
222
-
223
-
224
-
225
-
226
-
227
-
228
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
test.py DELETED
@@ -1,52 +0,0 @@
1
- import faiss
2
- import ast
3
- import pandas as pd
4
- import numpy as np
5
- from src.genai.utils.models_loader import ST
6
- import json
7
-
8
- def retrieve_tool(business_details):
9
- '''
10
- Always invoke this tool.
11
- Retrieve influencer's data by semantic search of **business details**.
12
- '''
13
- # === Load CSV ===
14
- csv_path = 'extracted_data.csv'
15
- df = pd.read_csv(csv_path)
16
-
17
- # === Parse stored embeddings ===
18
- df['embeddings'] = df['embeddings'].apply(lambda x: ast.literal_eval(x) if isinstance(x, str) else x)
19
- embeddings = np.vstack(df['embeddings'].values).astype('float32')
20
-
21
- # === Build FAISS index ===
22
- dimension = embeddings.shape[1]
23
- index = faiss.IndexFlatL2(dimension)
24
- index.add(embeddings)
25
-
26
- # === Encode the query and search ===
27
- query_embedding = ST.encode(str(business_details)).reshape(1, -1).astype('float32')
28
- top_k = 15
29
- distances, indices = index.search(query_embedding, top_k)
30
-
31
- # === Format results ===
32
- results = []
33
- for i, idx in enumerate(indices[0]):
34
- res = {
35
- 'username': df.iloc[idx]['username'],
36
- 'likesCount': int(df.iloc[idx]['likesCount']),
37
- 'commentCount': int(df.iloc[idx]['commentCount'])
38
- }
39
- results.append(res)
40
-
41
- return results
42
-
43
- details = {
44
- "business_type": "fitness and gym",
45
- "platform": "Instagram, TikTok",
46
- "target_audience": "young Nepali adults (ages 18–40) who are health-conscious and active on social media",
47
- "business_goals": "to expand gym branches across all major cities of Nepal and build a strong fitness community",
48
- "offerings": "personal training, group fitness classes, modern workout equipment, nutrition guidance, and wellness programs",
49
- "Challenges_faced": "attracting loyal members, standing out in a competitive market, and promoting consistent engagement"
50
- }
51
-
52
- print(retrieve_tool(details))