Spaces:
Sleeping
Sleeping
Commit ·
55dd1f8
0
Parent(s):
first commit
Browse filesFiles changed (14)
- .gitignoreAdded+12
- config.pyAdded+69
- example.jsonAdded+7
- journal.txtAdded+18
- metadata.ipynbAdded
- overall_problemdesc.jsonAdded
- overall_specific_problempair.jsonAdded
- requirements.txtAdded+148
- structured_output_updated.jsonAdded
- test.ipynbAdded
- test.jsonAdded
- tp_final.ipynbAdded
- tp_final.pyAdded+447
- utils.pyAdded+68
123456789101112# Python cache__pycache__/
# Virtual Environmentcalibre-env/
# Chroma DB databaseschroma_db_*/
# Other common Python files to ignore.env*.pyc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869from utils import get_file_dataimport os
# user_journal = get_file_data("journal.txt")# example = get_file_data("example.json")
# direcindirecprompt = f'''# I'll be giving you a journal entry written by a user. Your task is to extract out problems being faced by the user in the following format:# {{# "Overall Problem 1": ["Specific reason1 - reason why it was created", "Specific reason2 - reason why it was created"],# "Overall Problem 2": ["Specific reason1 - reason why it was created"],# }}# I'll give you an example how this overall - specific problem pair looks like. Here you'll see that the heading (single word is the overall problem), then we have the reasons why it was created# here is the overall - specific problem pair: {example}# Obviusly a single overall problem can have multiple specific reasons why it was created. Put it in the exact format as shown above.# Also, multiple overall problems can share a common specific reason why it was created. In that case, just repeat the specific reason under all of them.# Here is the user text you have to analyse: {user_journal}# Output strictly in the format given to you no extra symbols or words or anything
'''
# if os.path.getsize("overall_specific_problempair.json") != 0:# user_problem = get_file_data("overall_specific_problempair.json")# # print("File is empty")
# directdesc = f''' # So i am giving you the iverall problems that are being faced by the user. Here it is: {user_problem.keys()} # Now I want you to generate a 2-3 line summary/description for each of the problems. It shuold indicate what effect it has on the user's body and mind. # So basically I want to perform a cosine similarity between this description that you give and a task dataset that has multiple tasks and they have their own descriptions of what they are able to cure # So, If you write a good description for each overall problem, then I can match it with the task dataset descriptions to find the best matching tasks for the user. # Here are examples of what is present int the task dataset descriptions: # "Nadi Shodhana (Alternate Nostril Breathing)": {{ # "Stress": [ # "Balances left/right brain hemispheres for nervous system equilibrium", # "Reduces cortisol by 27% through symmetrical breathing patterns", # "Creates instant mental clarity during decision fatigue" # ], # "Emotions": [ # "Harmonizes emotional extremes by balancing solar/moon energies", # "Resets emotional reactivity through prefrontal cortex activation", # "Integrates logical and intuitive aspects of awareness" # ], # }} # "Bakasana (Crow Pose)": {{ # "Focus": [ # "Develops laser-like concentration to prevent falling", # "Trains mind-body coordination in challenging position", # "Builds mental discipline through fear management" # ], # "Strength": [ # "Develops core and wrist strength simultaneously", # "Tones abdominal muscles through active engagement", # "Builds functional arm strength for daily activities" # ], # }} # So, you see there is a certain way the descriptions are written for the task and hence you need to generate the descriptions for the overall problems in a similar way so that cosine similarity precisely extracts onyl those tasks which are highly relevant to the overall problems being faced by the user. # Also, follow the following format strictly: # {{ # "Overall Problem 1": ["Description"] # "Overall Problem 2": ["Description"] # }}
# Remember to output not anything else what is said, also don't use veyr veyr complicated words. You can use some technical words but keep it simple and precise otherwise if those words are present in the task dataset then cosine similaity will be very less. # also, replace "Overall Problem 1" with the problem name for which description is being written # '''1234567{ "Axienty":["User is feeling that their might be no one to understand or console him","user recieved a mail from a boss or professor saying “We need to talk"], "Sleepness":["User is having trouble falling asleep at night","User said that couldn't sleep till 4 am and then had an interview in the early morning"], "Procrastination":["User mentioned that they keep scrolling social media instead of completing deadline tasks"], "Depression":["User mentioned stopped feeling excited about hobbies, sports, games, or hanging out."] }123456789101112131415161718So i joined an American company. It was a beautiful experience when i was finally able to work exact office hours and where we were treated like adults and not kids.No shouting, no yelling during meeting. Politely giving us our tasks, and taking an update only after deadline. Even if deadline is missed, instead of arguing, they tried to find out why did it happen and what they can do to help reach it the next time. All the help was provided without ever having any issue with each other. Colleagues are great and helpful.Every morning i was eager to work and woke up with enthusiasmBut this lasted only until they decided to introduce a mediatory between us.AN INDIAN MANAGERWe all knew how indian tendency is regarrding work culture, and our fears came true.The manager now wanted to control all the things we did. On top of that he started doubting us whether we are slacking off work. So he asked us to timetrack all our activities while at home. Started delegating his own work to us which wasnt even in the job profile. Soon the politics started when he decided to involve top management even in low level discussion so that his views are enforced. On top of that all his mistakes that delay work are quitely not recorded on anything.Messaging us at odd times after office hours and expecting us to work late at night is very 'casual' and signs of dedicated employee. The attitude of 'toh kya hua' is affecting very negatively.I did not for a second ever imagined that such a wonderful experience of working in a great company could be destroyed by 1 person. The work culture that i left with previous company has now caught up to me again.This is one of the biggest reason i am trying to leave India and find a job elsewhere , where even if pay is low i'll be able to live peacefully.Four years. Three unicorn startups. Multiple cities. And yet, here I am, sitting at my desk, wondering why this part of corporate life feels like navigating a maze blindfolded. Let me vent—because maybe I’m not alone?“Hindi hai, bro? Cool, let’s switch.” Imagine walking into a meeting that starts with a polite “How’s your day?” in English, only for the next 30 minutes to dissolve into rapid-fire Hindi. Jokes fly, ideas bounce, and you’re just…nodding. Not because you agree, but because you’re lost. You’re South Indian, Northeast, or from a region where Hindi isn’t your mother tongue. You’ve tried learning it—really!—but fluency? The slang? The casual wit that makes everyone laugh? It’s like trying to catch smoke with your hands.The worst part? The bonding. Chai breaks, lunch tables, even Slack threads—suddenly, you’re the outsider in your own office. Colleagues bond over shared references, memes, and inside jokes you can’t decode. You smile awkwardly, laugh a beat too late. It’s not malice; it’s just…habit. But when promotions hinge on “culture fit,” how do you fit into a culture that feels linguistically gated?2. “No Smoke? No Drink? No Seat at the Table.” Here’s the other “unofficial rulebook”: smoke breaks = networking gold. Every hour, the balcony fills with folks puffing away, discussing projects, venting about managers, or just…chatting. You don’t smoke? Congrats on the healthy lungs! Now enjoy staring at your screen while career-critical conversations happen without you.And office parties? If you’re not clinking glasses, you’re a ghost. “Why aren’t you drinking?!” becomes the anthem of the night. Decline politely, and suddenly, you’re the “boring one.” The FOMO isn’t about the alcohol—it’s about the camaraderie that evaporates when you’re not “one of them.”So…Is It Just Me? I’m not judging anyone’s choices. Smoke if you want. Drink if you like. Speak whatever language feels like home. But when exclusion becomes the collateral damage of these habits, it’s exhausting. You start questioning: Is my career growth tied to my ability to chain-smoke or crack jokes in Hindi?To anyone else sitting silently in meetings, faking laughs, or skipping parties to avoid the peer pressure—I see you. This isn’t about “snowflake syndrome.” It’s about workplaces feeling like high school cliques, where your worth hinges on things that have nothing to do with your skills.I feel sick knowing how these cronies abuse the shit out of us, rob us from our money. CEO Narayan Murthy wants us to work for 70 hours per week but the dude himself can't see anything fucking straight, cross-eyed loser. We should just work for 10 hours per week max and call it a day. This 9-5 is making us depressed. We also need to stop breeding like cockroaches because at least, unlike humans, cockroaches can walk over themselves, but humans can't. I blame the system and schools such as City International School which looks like a fucking warehouse which you have to pay 89k rupees for annually, where's the infrastructure man? Nigerian schools have better infrastructure and better toilets which don't stink of piss. Also, school boards such as ICSE are to blame for this slave mentality. Also, when are we going to employ a 1 child policy? We should be having a king culture rather than a fucking slave culture which is glorified in this shit country. No wonder people are crippled nowadays. They are perpetually stressed. The average Indian man goes bald by 30 and grow a tummy like the laughing Buddha. Tax the rich CEOs and not the common man, why don't we Indians unionize and fight for our goddamn rights huh?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148aiohappyeyeballs==2.6.1aiohttp==3.13.2aiosignal==1.4.0annotated-doc==0.0.4annotated-types==0.7.0annoy==1.17.3anyio==4.12.0asttokens==3.0.1attrs==25.4.0certifi==2025.11.12charset-normalizer==3.4.4click==8.3.1coloredlogs==15.0.1comm==0.2.3dataclasses-json==0.6.7debugpy==1.8.17decorator==5.2.1distlib==0.4.0distro==1.9.0dnspython==2.8.0dotenv==0.9.9executing==2.2.1faiss-cpu==1.13.1fastapi==0.124.2fastembed==0.6.0filelock==3.20.0filetype==1.2.0flatbuffers==25.9.23frozenlist==1.8.0fsspec==2025.12.0greenlet==3.3.0groq==0.37.1h11==0.16.0hf-xet==1.2.0httpcore==1.0.9httpx==0.28.1httpx-sse==0.4.3huggingface-hub==0.36.0humanfriendly==10.0idna==3.11ipykernel==7.1.0ipython==9.8.0ipython_pygments_lexers==1.1.1jedi==0.19.2Jinja2==3.1.6joblib==1.5.2jsonlines==4.0.0jsonpatch==1.33jsonpointer==3.0.0jsonschema==4.25.1jsonschema-specifications==2025.9.1jupyter_client==8.6.3jupyter_core==5.9.1langchain==1.1.2langchain-classic==1.0.0langchain-community==0.4.1langchain-core==1.1.1langchain-groq==1.1.0langchain-nomic==1.0.1langchain-nvidia-ai-endpoints==1.0.0langchain-text-splitters==1.0.0langgraph==1.0.4langgraph-checkpoint==3.0.1langgraph-prebuilt==1.0.5langgraph-sdk==0.2.14langsmith==0.4.56lark==1.3.1loguru==0.7.3markdown-it-py==4.0.0MarkupSafe==3.0.3marshmallow==3.26.1matplotlib-inline==0.2.1mdurl==0.1.2mmh3==5.2.0mpmath==1.3.0multidict==6.7.0mypy_extensions==1.1.0nest-asyncio==1.6.0nomic==3.9.0numpy==2.3.5onnxruntime==1.23.2orjson==3.11.5ormsgpack==1.12.0packaging==25.0pandas==2.3.3parso==0.8.5perplexityai==0.22.0pexpect==4.9.0pillow==11.3.0platformdirs==4.5.1prompt_toolkit==3.0.52propcache==0.4.1protobuf==6.33.2psutil==7.1.3ptyprocess==0.7.0pure_eval==0.2.3py_rust_stemmers==0.1.5pyarrow==22.0.0pydantic==2.12.5pydantic-settings==2.12.0pydantic_core==2.41.5Pygments==2.19.2PyJWT==2.10.1pymongo==4.15.5python-dateutil==2.9.0.post0python-dotenv==1.2.1pytz==2025.2PyYAML==6.0.3pyzmq==27.1.0referencing==0.37.0regex==2025.11.3requests==2.32.5requests-toolbelt==1.0.0rich==14.2.0rpds-py==0.30.0scikit-learn==1.8.0scipy==1.16.3shellingham==1.5.4simpleeval==1.0.3six==1.17.0sniffio==1.3.1SQLAlchemy==2.0.44stack-data==0.6.3starlette==0.50.0sympy==1.14.0tenacity==9.1.2threadpoolctl==3.6.0tiktoken==0.12.0tokenizers==0.22.1tornado==6.5.2tqdm==4.67.1traitlets==5.14.3typer==0.20.0typing-inspect==0.9.0typing-inspection==0.4.2typing_extensions==4.15.0tzdata==2025.2u==1.0.4urllib3==2.6.0uuid_utils==0.12.0uvicorn==0.38.0virtualenv==20.35.4virtualenvwrapper-win==1.2.7watchdog==6.0.0wcwidth==0.2.14xxhash==3.6.0yarl==1.22.0zstandard==0.25.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447# from itertools import islice# import itertools# import json# import re# from groq import Groq# from config import direcindirecprompt# from utils import groq_calls,write_to_file, get_file_data, get_mongo_collection# from sklearn.feature_extraction.text import TfidfVectorizer# from sklearn.metrics.pairwise import cosine_similarity# import numpy as np# from datetime import datetime
# '''# The architecture is like this
# '''# collection = get_mongo_collection()
# def main():# # user_journal = get_file_data("journal.txt")# # example = get_file_data("example.json")
# # prompt= direcindirecprompt# direcindirecgroq_response = groq_calls(direcindirecprompt)# # parsed_json = json.loads(direcindirecgroq_response)# # print(parsed_json)# # write_to_file("overall_specific_problempair.json",direcindirecgroq_response)
# guideprompt = f'''# So, I am giving a set of direct-indirect problem pair, here it is: {direcindirecgroq_response}# Now, these are some of the issues the user is facing in his daily life. Assume that you're a very skilled psychologist and help solve the problems faced# by the users in their daily life by recommending them a set of guidelines of what they could follow or practice in their daily life to keep themselves calm# These guidelines should not be very long, some short recommendations which can be followed even when the person is seated on his chair in office# or any where else. Basically the guidelines should be accessible/doable any time.# Give 1-2 guidelines for each of the problem that the user is facing as in the problem pair procided to you
# Here are some examples of how guidelines could look like# -Take short breaks for deep breathing, walk in the present, and journal three things you're grateful for daily to shift perspective.# -Dedicate even 10 minutes to a hobby or enjoyable activity to recharge. # -Reduce news consumption and screen time, especially before bed, to avoid overwhelm.
# Above are some examples only, but remember whatever you suggest should be relevant to the problems the user is facing# Final output should be in JSON format only# final output should start and end like this# {{# problem1:["Set dedicated focus blocks (e.g., 90‑min) and log only the block end to satisfy reporting.","Use a private tracker to note progress, then share a concise daily summary with the manager."]# }} # '''
# guidegroq_response = groq_calls(guideprompt)# # with open("test.json", "w") as f:# # f.write(guidegroq_response)
# with open("structured_output_updated.json","r") as f:# task_dataset = json.load(f)
# result = {}# # task_dataset = test# yogabranches = list(task_dataset["Yoga"]["branches"].keys())# for branch in yogabranches: # if branch == "Asana":# postures = list(task_dataset["Yoga"]["branches"][branch].keys())# # print(postures)# result[f"{branch}s"] = {}# for posture in postures:# lst = list(task_dataset["Yoga"]["branches"][branch][posture].keys())# for pose in lst:# # # poses.append(task_dataset["Yoga"]["branches"][branch][posture][pose])# # print(task_dataset["Yoga"]["branches"][branch][posture][pose])# sliced_items = list(task_dataset["Yoga"]["branches"][branch][posture][pose].values())[:2]# result[f"{branch}s"][pose] = list(itertools.chain.from_iterable(sliced_items))# else:# postures = list(task_dataset["Yoga"]["branches"][branch].keys())# # print(postures)# result[f"{branch}s"] = {}# for posture in postures:# lst = list(task_dataset["Yoga"]["branches"][branch][posture].values())[:2]# result[f"{branch}s"][posture] = list(itertools.chain.from_iterable(lst))
# # with open("overall_specific_problempair.json","r",encoding = "utf-8") as f:# # user_problem = json.load(f) # user_problem = json.loads(direcindirecgroq_response)
# cosineprompt = f'''# So i am giving you the iverall problems that are being faced by the user. Here it is: {user_problem.keys()}# Now I want you to generate a 2-3 line summary/description for each of the problems. It shuold indicate what effect it has on the user's body and mind.# So basically I want to perform a cosine similarity between this description that you give and a task dataset that has multiple tasks and they have their own descriptions of what they are able to cure# So, If you write a good description for each overall problem, then I can match it with the task dataset descriptions to find the best matching tasks for the user.# Here are examples of what is present in the task dataset descriptions:# "Nadi Shodhana (Alternate Nostril Breathing)": {{# "Stress": [# "Balances left/right brain hemispheres for nervous system equilibrium",# "Reduces cortisol by 27% through symmetrical breathing patterns",# "Creates instant mental clarity during decision fatigue"# ],# "Emotions": [# "Harmonizes emotional extremes by balancing solar/moon energies",# "Resets emotional reactivity through prefrontal cortex activation",# "Integrates logical and intuitive aspects of awareness"# ],# }}# "Bakasana (Crow Pose)": {{# "Focus": [# "Develops laser-like concentration to prevent falling",# "Trains mind-body coordination in challenging position",# "Builds mental discipline through fear management"# ],# "Strength": [# "Develops core and wrist strength simultaneously",# "Tones abdominal muscles through active engagement",# "Builds functional arm strength for daily activities"# ],# }}# So, you see there is a certain way the descriptions are written for the task and hence you need to generate the descriptions for the overall problems in a similar way so that cosine similarity precisely extracts onyl those tasks which are highly relevant to the overall problems being faced by the user.# Also, follow the following format strictly:# {{# "Overall Problem 1": ["Description"]# "Overall Problem 2": ["Description"]# }}
# Remember to output not anything else what is said, also don't use very complicated words. You can use some technical words but keep it simple and precise otherwise if those words are present in the task dataset then cosine similaity will be very less.# also, replace "Overall Problem 1" with the problem name for which description is being written# ''' # cosinegroq_response = groq_calls(cosineprompt)# # with open("test.json","w") as f:# # f.write(cosinegroq_response)# parsed_json = json.loads(cosinegroq_response)# # write_to_file("overall_problemdesc.json",cosinegroq_response)
# user_problem = parsed_json# user_problem_text = " ".join(sum(user_problem.values(), [])) # tasks = {}# for branch in result.keys():# for pose in result[branch].keys():# documents = []# # print(result[branch][pose])# desc = ", ".join(result[branch][pose])# # print(desc)# documents.append(desc)# documents.append(user_problem_text) # # documents[0] ='Micromanagement scrutiny, raising heart rate and restlessness. leading to tight muscles and frequent headaches. Language barriers and frustration, making communication difficult. Shallow breathing and lowering confidence and increasing social anxiety. Social exclusion triggers. It reduces heart rate variability and raises cortisol, leaving the body stressed. Burnout produces persistent fatigue, headaches, and muscle aches. Focus and decision‑making suffer, while sleep quality drops and inflammation markers rise. Discrimination induces emotional distress and self‑doubt, making the mind hypervigilant and anxious. stressing the body.'# vectorizer = TfidfVectorizer(stop_words='english')# tfidf_matrix = vectorizer.fit_transform(documents)# similarities = cosine_similarity(tfidf_matrix[-1], tfidf_matrix[:-1]).flatten()# tasks[f"{branch}({pose})"]= similarities# # print(f"{branch} --> ", f"{pose} --> ", similarities) # print(documents)# sorted_tasks = dict(sorted(tasks.items(), key=lambda item: item[1], reverse=True))# print(list(sorted_tasks.items())[:5])
# username = "sameer" #in production extract the username
# if collection is not None:# chat_document = {# "user_id": username,# "timestamp": datetime.now(),# "problemdesc": direcindirecgroq_response,# "guidelines":guidegroq_response,# "tasks": list(sorted_tasks.keys())[:5]
# } # try:# collection.insert_one(chat_document)# print("Saved to DB")# except Exception as e:# print(f"Failed to save to DB: {e}")
# if __name__ == "__main__":# main()
from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom typing import Optional, List, Dict, Anyfrom itertools import isliceimport itertoolsimport jsonimport refrom datetime import datetime
# ML and Math importsfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.metrics.pairwise import cosine_similarityimport numpy as np
# Custom modules (assuming these exist in your project structure)from groq import Groq# from config import direcindirecpromptfrom utils import groq_calls, write_to_file, get_file_data, get_mongo_collectionimport uvicorn
# Initialize FastAPI appapp = FastAPI(title="Vidur Yoga Recommendation API")
# Initialize DB connection globally (or within dependency)try: collection = get_mongo_collection()except Exception as e: print(f"Warning: Database connection failed on startup: {e}") collection = None
# --- Pydantic Models for Request/Response ---class AnalysisRequest(BaseModel): username: str = "sameer" # Default as per your code user_journal: str # Add other fields here if you need to pass user_journal dynamically later
class AnalysisResponse(BaseModel): status: str username: str guidelines: Dict[str, Any] recommended_tasks: List[str] timestamp: datetime
@app.post("/analyze-tasks", response_model=AnalysisResponse)def generate_analysis(request: AnalysisRequest): """ Executes the analysis pipeline: 1. Identifies direct/indirect problems via Groq. 2. Generates guidelines via Groq. 3. Matches problems to Yoga tasks using TF-IDF/Cosine Similarity. 4. Saves to MongoDB. """ example = get_file_data("example.json") direcindirecprompt = f''' I'll be giving you a journal entry written by a user. Your task is to extract out problems being faced by the user in the following format: {{ "Overall Problem 1": ["Specific reason1 - reason why it was created", "Specific reason2 - reason why it was created"], "Overall Problem 2": ["Specific reason1 - reason why it was created"], }} I'll give you an example how this overall - specific problem pair looks like. Here you'll see that the heading (single word is the overall problem), then we have the reasons why it was created here is the overall - specific problem pair: {example} Obviusly a single overall problem can have multiple specific reasons why it was created. Put it in the exact format as shown above. Also, multiple overall problems can share a common specific reason why it was created. In that case, just repeat the specific reason under all of them. Here is the user text you have to analyse: {request.user_journal} Output strictly in the format given to you no extra symbols or words or anything '''
# 1. Direct/Indirect Problem Identification try: # Assuming direcindirecprompt is imported from config direcindirecgroq_response = groq_calls(direcindirecprompt) # If the response acts as a JSON source, we try to parse it to ensure validity # parsed_check = json.loads(direcindirecgroq_response) except Exception as e: raise HTTPException(status_code=502, detail=f"Groq API Error (Problem Identification): {str(e)}")
# 2. Guidelines Generation try: guideprompt = f''' So, I am giving a set of direct-indirect problem pair, here it is: {direcindirecgroq_response} Now, these are some of the issues the user is facing in his daily life. Assume that you're a very skilled psychologist and help solve the problems faced by the users in their daily life by recommending them a set of guidelines of what they could follow or practice in their daily life to keep themselves calm These guidelines should not be very long, some short recommendations which can be followed even when the person is seated on his chair in office or any where else. Basically the guidelines should be accessible/doable any time. Give 1-2 guidelines for each of the problem that the user is facing as in the problem pair procided to you
Here are some examples of how guidelines could look like -Take short breaks for deep breathing, walk in the present, and journal three things you're grateful for daily to shift perspective. -Dedicate even 10 minutes to a hobby or enjoyable activity to recharge. -Reduce news consumption and screen time, especially before bed, to avoid overwhelm.
Above are some examples only, but remember whatever you suggest should be relevant to the problems the user is facing Final output should be in JSON format only final output should start and end like this {{ "problem1": ["Set dedicated focus blocks...", "Use a private tracker..."] }} ''' guidegroq_response = groq_calls(guideprompt) except Exception as e: raise HTTPException(status_code=502, detail=f"Groq API Error (Guideline Generation): {str(e)}")
# 3. Load Task Dataset try: with open("structured_output_updated.json", "r") as f: task_dataset = json.load(f) except FileNotFoundError: raise HTTPException(status_code=500, detail="Server Error: 'structured_output_updated.json' file not found.") except json.JSONDecodeError: raise HTTPException(status_code=500, detail="Server Error: Failed to decode task dataset JSON.")
# 4. Process Yoga Branches (Business Logic) try: result = {} yogabranches = list(task_dataset["Yoga"]["branches"].keys()) for branch in yogabranches: if branch == "Asana": postures = list(task_dataset["Yoga"]["branches"][branch].keys()) result[f"{branch}s"] = {} for posture in postures: # Depending on structure, sometimes keys are poses lst = list(task_dataset["Yoga"]["branches"][branch][posture].keys()) for pose in lst: sliced_items = list(task_dataset["Yoga"]["branches"][branch][posture][pose].values())[:2] result[f"{branch}s"][pose] = list(itertools.chain.from_iterable(sliced_items)) else: postures = list(task_dataset["Yoga"]["branches"][branch].keys()) result[f"{branch}s"] = {} for posture in postures: lst = list(task_dataset["Yoga"]["branches"][branch][posture].values())[:2] result[f"{branch}s"][posture] = list(itertools.chain.from_iterable(lst)) except KeyError as e: raise HTTPException(status_code=500, detail=f"Data Processing Error: Key {str(e)} missing in dataset.") except Exception as e: raise HTTPException(status_code=500, detail=f"Data Processing Error: {str(e)}")
# 5. Cosine Similarity Preparation try: # We parse the response from Step 1 to get keys for the next prompt user_problem_raw = json.loads(direcindirecgroq_response) cosineprompt = f''' So i am giving you the iverall problems that are being faced by the user. Here it is: {user_problem_raw.keys()} Now I want you to generate a 2-3 line summary/description for each of the problems. It shuold indicate what effect it has on the user's body and mind. So basically I want to perform a cosine similarity between this description that you give and a task dataset that has multiple tasks and they have their own descriptions of what they are able to cure So, If you write a good description for each overall problem, then I can match it with the task dataset descriptions to find the best matching tasks for the user. Here are examples of what is present in the task dataset descriptions: "Nadi Shodhana (Alternate Nostril Breathing)": {{ "Stress": [ "Balances left/right brain hemispheres for nervous system equilibrium", "Reduces cortisol by 27% through symmetrical breathing patterns", "Creates instant mental clarity during decision fatigue" ], "Emotions": [ "Harmonizes emotional extremes by balancing solar/moon energies", "Resets emotional reactivity through prefrontal cortex activation", "Integrates logical and intuitive aspects of awareness" ], }} "Bakasana (Crow Pose)": {{ "Focus": [ "Develops laser-like concentration to prevent falling", "Trains mind-body coordination in challenging position", "Builds mental discipline through fear management" ], "Strength": [ "Develops core and wrist strength simultaneously", "Tones abdominal muscles through active engagement", "Builds functional arm strength for daily activities" ], }} So, you see there is a certain way the descriptions are written for the task and hence you need to generate the descriptions for the overall problems in a similar way so that cosine similarity precisely extracts onyl those tasks which are highly relevant to the overall problems being faced by the user. Also, follow the following format strictly: {{ "Overall Problem 1": ["Description"] "Overall Problem 2": ["Description"] }}
Remember to output not anything else what is said, also don't use very complicated words. You can use some technical words but keep it simple and precise otherwise if those words are present in the task dataset then cosine similaity will be very less. also, replace "Overall Problem 1" with the problem name for which description is being written ''' cosinegroq_response = groq_calls(cosineprompt) parsed_cosine_json = json.loads(cosinegroq_response) user_problem = parsed_cosine_json user_problem_text = " ".join(sum(user_problem.values(), [])) except json.JSONDecodeError: raise HTTPException(status_code=500, detail="Failed to parse JSON from Groq response (Cosine Prompt).") except Exception as e: raise HTTPException(status_code=500, detail=f"Error preparing Cosine Similarity data: {str(e)}")
# 6. Calculate Cosine Similarity try: tasks = {} for branch in result.keys(): for pose in result[branch].keys(): documents = [] desc = ", ".join(result[branch][pose]) documents.append(desc) documents.append(user_problem_text) vectorizer = TfidfVectorizer(stop_words='english') tfidf_matrix = vectorizer.fit_transform(documents) # Compare the last doc (user problem) with the first doc (task desc) similarities = cosine_similarity(tfidf_matrix[-1], tfidf_matrix[:-1]).flatten() tasks[f"{branch}({pose})"] = similarities[0] # Take the float value # Sort and take top 5 sorted_tasks = dict(sorted(tasks.items(), key=lambda item: item[1], reverse=True)) top_tasks = list(sorted_tasks.keys())[:5] except Exception as e: raise HTTPException(status_code=500, detail=f"Math/Vectorization Error: {str(e)}")
# 7. Database Insertion chat_document = None try: # Try to parse guidelines string to JSON object for cleaner DB storage/Response try: guidelines_obj = json.loads(guidegroq_response) except: guidelines_obj = {"raw_text": guidegroq_response}
chat_document = { "user_id": request.username, "timestamp": datetime.now(), "problemdesc": direcindirecgroq_response, # Storing raw response string as per original code "guidelines": guidegroq_response, # Storing raw response string as per original code "tasks": top_tasks }
if collection is not None: collection.insert_one(chat_document) print("Saved to DB") else: print("Skipped DB save (Collection not available)") except Exception as e: # We log the DB error but might not want to fail the whole request if the calculation succeeded print(f"Failed to save to DB: {e}") # Note: Depending on requirements, you might want to raise HTTPException here or just proceed.
# 8. Return Response return AnalysisResponse( status="success", username=request.username, guidelines=guidelines_obj, recommended_tasks=top_tasks, timestamp=chat_document["timestamp"] if chat_document else datetime.now() )
if __name__ == "__main__": # Run the app with uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import osimport jsonimport itertoolsfrom groq import Groqfrom dotenv import load_dotenvfrom pymongo import MongoClientimport certifiload_dotenv()GROQ_API_KEY = os.getenv("GROQ_API_KEY")
def get_mongo_collection(): CONNECTION_STRING = os.getenv("CONNECTION_STRING") DB_NAME = os.getenv("DB_NAME") COLLECTION_NAME = os.getenv("COLLECTION_NAME") try: # Connect with certifi to avoid SSL errors client = MongoClient(CONNECTION_STRING, tlsCAFile=certifi.where()) db = client[DB_NAME] return db[COLLECTION_NAME] except Exception as e: print(f"Error connecting to Mongo: {e}") return None
def get_file_data(filepath): if(filepath.endswith(".json")): with open(filepath,"r") as f: data = json.load(f) return data else: with open(filepath,"r") as f: data = f.read() return data
def groq_calls(prompt): client = Groq(api_key=GROQ_API_KEY)
groq_card = client.chat.completions.create( # 401629 messages=[ { "role": "user", "content": f"{prompt}", }, { "role":"system", "content":"You are a psychologist. Output JSON" } ], model="openai/gpt-oss-20b", response_format={"type": "json_object"} )
# print(groq_card.choices[0].message.content) return groq_card.choices[0].message.content
def write_to_file(output_filename,groq_response): # output_filename = "overall_specific_problempair.json" parsed_json = json.loads(groq_response) with open(output_filename, 'a', encoding='utf-8') as f: json.dump(parsed_json, f)
.gitignoreAdded+12
config.pyAdded+69
example.jsonAdded+7
journal.txtAdded+18
metadata.ipynbAdded
overall_problemdesc.jsonAdded
overall_specific_problempair.jsonAdded
requirements.txtAdded+148
structured_output_updated.jsonAdded
test.ipynbAdded
test.jsonAdded
tp_final.ipynbAdded
tp_final.pyAdded+447
utils.pyAdded+68