Spaces:
Running
Running
Download utils.py from SamVidur/Journal_task_planner: direct link, hf CLI and curl.
- Browser
- Download file 2.19 kB
-
https://huggingface.co/spaces/SamVidur/Journal_task_planner/resolve/main/utils.py
- Command line
-
hf download hf://spaces/SamVidur/Journal_task_planner/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/SamVidur/Journal_task_planner/resolve/main/utils.py
2.19 kB
| import os | |
| import json | |
| import itertools | |
| from groq import Groq | |
| from dotenv import load_dotenv | |
| from pymongo import MongoClient | |
| import certifi | |
| import random | |
| load_dotenv() | |
| def get_random(): | |
| lst = ["R1","R2","R3","S1","RD1"] | |
| i = random.randint(0,4) | |
| return lst[i] | |
| def get_groq_api_key(): | |
| """Pick one of the rotating GROQ keys. Called per-request so the choice | |
| is not frozen at import time for the life of the worker.""" | |
| some = get_random() | |
| key = os.getenv(f"GROQ_API_KEY{some}") | |
| if not key: | |
| raise RuntimeError(f"Environment variable GROQ_API_KEY{some} is not set") | |
| return 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=get_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) | |