Spaces:
Sleeping
Sleeping
| # import json | |
| # from groq import Groq | |
| # import os | |
| # from dotenv import load_dotenv | |
| # import random | |
| # from utils import get_random, get_mongo_collection | |
| # load_dotenv() | |
| # some = get_random() | |
| # GROQ_API_KEY = os.getenv(f"GROQ_API_KEY{some}") | |
| # def count_doshas(user_id): | |
| # collection = get_mongo_collection() | |
| # cursor = collection.find({"templateName":"Kapha,Pitta,Vata"},{"userId":user_id}).sort("createdAt", -1).limit(1) | |
| # mapping = {'1':'Vata','2':'Pitta','3':'Kapha'} | |
| # counts = {"Vata": 0, "Pitta": 0, "Kapha": 0} | |
| # for item in cursor: | |
| # # print(item) | |
| # for lst in item["answers"]: | |
| # # print(mapping[lst['answer'][:1]]) | |
| # counts[mapping[lst['answer'][:1]]] += 1 | |
| # return counts | |
| # def assign_personality(counts): | |
| # v = counts["Vata"] | |
| # p = counts["Pitta"] | |
| # k = counts["Kapha"] | |
| # # Single dominant dosha | |
| # if v >= 7: return "Vata" | |
| # if p >= 7: return "Pitta" | |
| # if k >= 7: return "Kapha" | |
| # # Dual dosha | |
| # if v >= 5 and p >= 5: return "Vata-Pitta" | |
| # if p >= 5 and k >= 5: return "Pitta-Kapha" | |
| # if v >= 5 and k >= 5: return "Vata-Kapha" | |
| # # Tridoshic | |
| # if v >= 3 and p >= 3 and k >= 3: return "Vata-Pitta-Kapha" | |
| # return "Unclear" | |
| # # ------------------------------------- | |
| # # TRAITS DICTIONARY | |
| # # ------------------------------------- | |
| # TRAITS = { | |
| # "Vata": """ | |
| # Vata | |
| # Vata types are quick and agile in their minds with often changing | |
| # interests and inclinations. They are talkative, informed and | |
| # intellectual and can understand many different points of view their minds easily | |
| # waver and can wander out of control. While they may have some knowledge of many | |
| # different subjects, the tend to lack in depth knowledge about one subject specifically. | |
| # They ack determinism and self confidence and often have a negative perception of themselves. | |
| # Vata types suffer most from fear, which is their first reaction to anything new or strange. They like to worry easily get afflicted by anxiety, and usually lack stability. They get saced out and may be absent-minded. Their memory and short-term and erratic. They suffer quickly from overwork and over-exercise and tend to overextend themselves in whatever they do. | |
| # They are good at creative pursuits. They can be highly sociable and like to mix with people of all types. But, when there is too much vata, they tend to become loners and hypersensitive to contact. This is generally because they have too much to say and do not know how to relate it. | |
| # They are the most adaptable to change. | |
| # If there is too much vata, there is a lot of instability and agitation in the mind which results in exccesive worrying and makes problems appear larger than they are. They are prone to premature action and inappropriate action. | |
| # High vata manifests as fear, alienation, and possible nervous breakdowns. They can also suffer from insomnia, tremors, palpitations and rapid shifts of mood. | |
| # """, | |
| # "Pitta": """ | |
| # Pitta | |
| # Pitta types are intelligent, perceptive and discriminating. They have sharp minds and are able to see the world in a clear and systematic manner. However, they can also be opinionated, judgmental and self -righteous. | |
| # They are prone to anger and tend to be aggressive and domineering. They are not afraid of conflict and can be more aggressive when the situation presents itself. They have probing minds and can be good at research. They also have good debating skills. | |
| # They have a hard time seeing someone else’s point of view and may lack compassion. They prefer hierarchy and authority over consensus. They are highly determined people. | |
| # They usually have food self-control but they can be self-absorbed and anti-social. | |
| # High pitta causes aggressiveness and violence. | |
| # """, | |
| # "Kapha": """ | |
| # Kapha | |
| # Kaphas are naturally emotional in temperament and have tremendous love, devotion and loyalty. Negatively, they can have great desire, and may be possessive and greedy. They are romantic, sentimental, and cry easily. | |
| # They are slower in learning than others but they retain what they learn well. They are better at finishing things than they are at starting something new. They are natural followers and like to work in association or within large teams. | |
| # They are stable but can sometimes stagnate. They don’t like change and find it very difficult to change even when they want to. They are friendly to people they know but have difficulty in relating to foreigners. | |
| # Kapha types are least likely to express anti-social behavior but they are preoccupied with what others think about them. | |
| # High kaha cuses metal dullness and poor perception and they tend to suffer from a lack of motivation. | |
| # They tend to want to own and control everything and have a high degree of possessiveness | |
| # They are prone to over-sleeping overindulging. | |
| # """, | |
| # "Vata-Pitta": """ | |
| # Vata – Pitta (VP) | |
| # VP types have the volatility of air and fire combined. Fear and anger mix within them in unpredictable way. If something doesn’t make them fearful, it makes them angry. | |
| # They often look for someone who they can unload their negative emotions on. | |
| # They find it difficult to withstand criticism. | |
| # They are generally highly intelligent and require a lifestyle that can accommodate their volatility. | |
| # They will thrive in an environment that supports them and creates a safe space for them to express their volatility. | |
| # """, | |
| # "Pitta-Kapha": """ | |
| # Pitta – Kapha (PK) | |
| # Pitta kapha types are psychologically strong in general and don’t seek help easily. | |
| # They lack flexibility and adaptability. | |
| # They prefer to be dominating and controlling. | |
| # They tend to be conservative and possessive. This leads them to eventual frustration because they cannot control everything around them. | |
| # They require new activities, new challenges, and new ways to show their creativity. | |
| # """, | |
| # "Vata-Kapha": """ | |
| # Vata – Kapha (VK) | |
| # VK types lack energy, motivation and passion. They sometimes simply do not have the fire to get things started. | |
| # They are often hypersensitive, and passive-dependent. | |
| # They lack the energy to put plans into action. | |
| # They will go out of their way to agree with what you have said. | |
| # They have chameleon-style personalities where they can appear to be what people want them to be. They will often also blame themselves for others’ mistakes. | |
| # They can be highly adaptable and humble. | |
| # They tend to be naïve and need to be more realistic about other people and their motivations. | |
| # """, | |
| # "Vata-Pitta-Kapha": """ | |
| # Vata – Pitta – Kapha (VPK) | |
| # This is very rare that each of the doshas exist in equal amounts. | |
| # Their condition psychologically can be constantly changing and unpredictable. | |
| # Their psychological state is often a reflection of their circumstances rather than their personality. | |
| # """ | |
| # } | |
| # def get_traits_for_type(personality_type): | |
| # return TRAITS.get(personality_type, "No traits found for this type.") | |
| # # ------------------------------------- | |
| # # GROQ: GENERATE PSYCHOLOGY REPORT | |
| # # ------------------------------------- | |
| # client = Groq(api_key=GROQ_API_KEY) | |
| # def generate_psychology_report(personality_type, traits_text, dosha_counts): | |
| # prompt = f""" | |
| # You are an expert Ayurvedic psychologist. | |
| # Write a **deeply personal psychological report directly addressing the person as "you"**. | |
| # This should NOT sound like an academic explanation — it should feel like an | |
| # insightful evaluation about them. | |
| # ### REQUIRED STYLE: | |
| # - Address the reader as **"you"** throughout | |
| # - Tone: warm, empathetic, reflective, personal | |
| # - Use gentle interpretations (“you often…”, “you tend to…”, “you sometimes struggle…”) | |
| # - Explore emotional patterns, thought styles, reactions, strengths, blindspots | |
| # **Formatting Instructions:** | |
| # - The output MUST be in **Markdown**. | |
| # - Use `#` for the Main Title (e.g., # Personality Report Report). | |
| # - Use `##` for Section Headers (e.g., ## Core Personality). | |
| # - Use bullet points `- ` for lists. | |
| # - Use **bold** text for key strengths or warnings. | |
| # - Do not wrap the output in a code block (like ```markdown). Just return the raw markdown. | |
| # ### Input Data | |
| # Personality Type: **{personality_type}** | |
| # Dosha Counts: {dosha_counts} | |
| # Relevant Ayurvedic Traits: | |
| # -------------------------- | |
| # {traits_text} | |
| # Begin the personal Markdown report now. | |
| # """ | |
| # completion = client.chat.completions.create( | |
| # model="openai/gpt-oss-20b", | |
| # temperature=1.35, | |
| # max_tokens=3500, | |
| # messages=[ | |
| # {"role": "system", "content": "You write personal Ayurvedic psychological reports"}, | |
| # {"role": "user", "content": prompt} | |
| # ] | |
| # ) | |
| # return completion.choices[0].message.content | |
| # # ------------------------------------- | |
| # # SAVE MARKDOWN | |
| # # ------------------------------------- | |
| # def save_report(markdown_text, filename="psychology_report.md"): | |
| # with open(filename, "w", encoding="utf-8") as f: | |
| # f.write(markdown_text) | |
| # print(f"Markdown report saved as: {filename}") | |
| # # ------------------------------------- | |
| # # MAIN | |
| # # ------------------------------------- | |
| # if __name__ == "__main__": | |
| # answers = load_answers("vpk_user_answers.json") | |
| # dosha_counts = count_doshas(answers) | |
| # # print(dosha_counts) | |
| # personality_type = assign_personality(dosha_counts) | |
| # # print(personality_type) | |
| # traits_text = get_traits_for_type(personality_type) | |
| # # print(traits_text) | |
| # report_md = generate_psychology_report(personality_type, traits_text, dosha_counts) | |
| # # save_report(report_md) | |
| # # print("\nGenerated Report:\n") | |
| # #print(report_md) | |
| import json | |
| import os | |
| import random | |
| from typing import Dict, Any | |
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| from groq import Groq | |
| from dotenv import load_dotenv | |
| import requests | |
| from bson import ObjectId | |
| from utils import get_random, get_mongo_collection | |
| load_dotenv() | |
| app = FastAPI(title="KPV asessment API") | |
| some = get_random() | |
| GROQ_API_KEY = os.getenv(f"GROQ_API_KEY{some}") | |
| client = Groq(api_key=GROQ_API_KEY) | |
| class ReportRequest(BaseModel): | |
| user_id: str | |
| username: str | |
| class ReportResponse(BaseModel): | |
| user_id: str | |
| personality_type: str | |
| dosha_counts: Dict[str, int] | |
| report_markdown: str | |
| def count_doshas(userid): | |
| collection = get_mongo_collection() | |
| cursor = collection.find({"templateName": "Kapha,Pitta,Vata","userId": userid}).sort("createdAt", -1).limit(1) | |
| mapping = {'1': 'Vata', '2': 'Pitta', '3': 'Kapha'} | |
| counts = {"Vata": 0, "Pitta": 0, "Kapha": 0} | |
| found_data = False | |
| for item in cursor: | |
| found_data = True | |
| if "answers" in item: | |
| for lst in item["answers"]: | |
| if 'answer' in lst and lst['answer']: | |
| key = lst['answer'][:1] | |
| if key in mapping: | |
| counts[mapping[key]] += 1 | |
| if not found_data: | |
| return None | |
| return counts | |
| def assign_personality(counts): | |
| v = counts["Vata"] | |
| p = counts["Pitta"] | |
| k = counts["Kapha"] | |
| if v >= 7: return "Vata" | |
| if p >= 7: return "Pitta" | |
| if k >= 7: return "Kapha" | |
| if v >= 5 and p >= 5: return "Vata-Pitta" | |
| if p >= 5 and k >= 5: return "Pitta-Kapha" | |
| if v >= 5 and k >= 5: return "Vata-Kapha" | |
| if v >= 3 and p >= 3 and k >= 3: return "Vata-Pitta-Kapha" | |
| return "Unclear" | |
| TRAITS = { | |
| "Vata": """ | |
| Vata | |
| Vata types are quick and agile in their minds with often changing | |
| interests and inclinations. They are talkative, informed and | |
| intellectual and can understand many different points of view their minds easily | |
| waver and can wander out of control. While they may have some knowledge of many | |
| different subjects, the tend to lack in depth knowledge about one subject specifically. | |
| They ack determinism and self confidence and often have a negative perception of themselves. | |
| Vata types suffer most from fear, which is their first reaction to anything new or strange. They like to worry easily get afflicted by anxiety, and usually lack stability. They get saced out and may be absent-minded. Their memory and short-term and erratic. They suffer quickly from overwork and over-exercise and tend to overextend themselves in whatever they do. | |
| They are good at creative pursuits. They can be highly sociable and like to mix with people of all types. But, when there is too much vata, they tend to become loners and hypersensitive to contact. This is generally because they have too much to say and do not know how to relate it. | |
| They are the most adaptable to change. | |
| If there is too much vata, there is a lot of instability and agitation in the mind which results in exccesive worrying and makes problems appear larger than they are. They are prone to premature action and inappropriate action. | |
| High vata manifests as fear, alienation, and possible nervous breakdowns. They can also suffer from insomnia, tremors, palpitations and rapid shifts of mood. | |
| """, | |
| "Pitta": """ | |
| Pitta | |
| Pitta types are intelligent, perceptive and discriminating. They have sharp minds and are able to see the world in a clear and systematic manner. However, they can also be opinionated, judgmental and self -righteous. | |
| They are prone to anger and tend to be aggressive and domineering. They are not afraid of conflict and can be more aggressive when the situation presents itself. They have probing minds and can be good at research. They also have good debating skills. | |
| They have a hard time seeing someone else’s point of view and may lack compassion. They prefer hierarchy and authority over consensus. They are highly determined people. | |
| They usually have food self-control but they can be self-absorbed and anti-social. | |
| High pitta causes aggressiveness and violence. | |
| """, | |
| "Kapha": """ | |
| Kapha | |
| Kaphas are naturally emotional in temperament and have tremendous love, devotion and loyalty. Negatively, they can have great desire, and may be possessive and greedy. They are romantic, sentimental, and cry easily. | |
| They are slower in learning than others but they retain what they learn well. They are better at finishing things than they are at starting something new. They are natural followers and like to work in association or within large teams. | |
| They are stable but can sometimes stagnate. They don’t like change and find it very difficult to change even when they want to. They are friendly to people they know but have difficulty in relating to foreigners. | |
| Kapha types are least likely to express anti-social behavior but they are preoccupied with what others think about them. | |
| High kaha cuses metal dullness and poor perception and they tend to suffer from a lack of motivation. | |
| They tend to want to own and control everything and have a high degree of possessiveness | |
| They are prone to over-sleeping overindulging. | |
| """, | |
| "Vata-Pitta": """ | |
| Vata – Pitta (VP) | |
| VP types have the volatility of air and fire combined. Fear and anger mix within them in unpredictable way. If something doesn’t make them fearful, it makes them angry. | |
| They often look for someone who they can unload their negative emotions on. | |
| They find it difficult to withstand criticism. | |
| They are generally highly intelligent and require a lifestyle that can accommodate their volatility. | |
| They will thrive in an environment that supports them and creates a safe space for them to express their volatility. | |
| """, | |
| "Pitta-Kapha": """ | |
| Pitta – Kapha (PK) | |
| Pitta kapha types are psychologically strong in general and don’t seek help easily. | |
| They lack flexibility and adaptability. | |
| They prefer to be dominating and controlling. | |
| They tend to be conservative and possessive. This leads them to eventual frustration because they cannot control everything around them. | |
| They require new activities, new challenges, and new ways to show their creativity. | |
| """, | |
| "Vata-Kapha": """ | |
| Vata – Kapha (VK) | |
| VK types lack energy, motivation and passion. They sometimes simply do not have the fire to get things started. | |
| They are often hypersensitive, and passive-dependent. | |
| They lack the energy to put plans into action. | |
| They will go out of their way to agree with what you have said. | |
| They have chameleon-style personalities where they can appear to be what people want them to be. They will often also blame themselves for others’ mistakes. | |
| They can be highly adaptable and humble. | |
| They tend to be naïve and need to be more realistic about other people and their motivations. | |
| """, | |
| "Vata-Pitta-Kapha": """ | |
| Vata – Pitta – Kapha (VPK) | |
| This is very rare that each of the doshas exist in equal amounts. | |
| Their condition psychologically can be constantly changing and unpredictable. | |
| Their psychological state is often a reflection of their circumstances rather than their personality. | |
| """ | |
| } | |
| def get_traits_for_type(personality_type): | |
| return TRAITS.get(personality_type, "No traits found for this type.") | |
| def generate_psychology_report(personality_type, traits_text, dosha_counts, request: ReportRequest): | |
| prompt = f""" | |
| You are an expert Ayurvedic psychologist. | |
| Write a **deeply personal psychological report directly addressing the person as "you"**. | |
| You can start with greetings and name of the person: {request.username} | |
| This should NOT sound like an academic explanation — it should feel like an | |
| insightful evaluation about them. | |
| ### REQUIRED STYLE: | |
| - Address the reader as **"you"** throughout | |
| - Tone: warm, empathetic, reflective, personal | |
| - Use gentle interpretations (“you often…”, “you tend to…”, “you sometimes struggle…”) | |
| - Explore emotional patterns, thought styles, reactions, strengths, blindspots | |
| **Formatting Instructions:** | |
| - The output MUST be in **Markdown**. | |
| - Use `#` for the Main Title (e.g., # Personality Report Report). | |
| - Use `##` for Section Headers (e.g., ## Core Personality). | |
| - Use bullet points `- ` for lists. | |
| - Use **bold** text for key strengths or warnings. | |
| - Do not wrap the output in a code block (like ```markdown). Just return the raw markdown. | |
| ### Input Data | |
| Personality Type: **{personality_type}** | |
| Dosha Counts: {dosha_counts} | |
| Relevant Ayurvedic Traits: | |
| -------------------------- | |
| {traits_text} | |
| Begin the personal Markdown report now. | |
| """ | |
| completion = client.chat.completions.create( | |
| model="openai/gpt-oss-20b", # Ensure this model ID is correct for your Groq access | |
| temperature=0.5, | |
| max_tokens=4000, | |
| messages=[ | |
| {"role": "system", "content": "You write personal Ayurvedic psychological reports"}, | |
| {"role": "user", "content": prompt} | |
| ] | |
| ) | |
| return completion.choices[0].message.content | |
| def home(): | |
| return {"status": "Ayurvedic Report Service is Running"} | |
| async def cron_test(): | |
| return "Hello Cron Tester" | |
| def create_report(request: ReportRequest): | |
| try: | |
| dosha_counts = count_doshas(request.user_id) | |
| if dosha_counts is None: | |
| raise HTTPException(status_code=404, detail="User data or survey answers not found") | |
| personality_type = assign_personality(dosha_counts) | |
| traits_text = get_traits_for_type(personality_type) | |
| report_md = generate_psychology_report(personality_type, traits_text, dosha_counts,request) | |
| return ReportResponse( | |
| user_id=request.user_id, | |
| personality_type=personality_type, | |
| dosha_counts=dosha_counts, | |
| report_markdown=report_md | |
| ) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| # To run locally: | |
| # uvicorn main:app --reload |