Spaces:
Sleeping
Sleeping
ariansyahdedy
commited on
Commit
·
1157bd1
1
Parent(s):
f169c98
Without database
Browse files- app/core/config.py +0 -22
- app/crud/user.py +0 -30
- app/db/database.py +0 -46
- app/endpoints/v1/users.py +0 -48
- app/main.py +3 -4
- llamma-duo/generate_dataset.py +80 -0
app/core/config.py
DELETED
@@ -1,22 +0,0 @@
|
|
1 |
-
|
2 |
-
# app/core/config.py
|
3 |
-
import os
|
4 |
-
from pydantic_settings import BaseSettings
|
5 |
-
# from dotenv import load_dotenv
|
6 |
-
|
7 |
-
# load_dotenv()
|
8 |
-
|
9 |
-
class Settings(BaseSettings):
|
10 |
-
MONGO_DETAILS: str = os.getenv("mongodb_uri")
|
11 |
-
MongoDB_NAME: str = "llm_wa_hf"
|
12 |
-
COLLECTION_NAMES: list = ["users", "transactions"]
|
13 |
-
ACCESS_TOKEN:str = os.getenv("ACCESS_TOKEN")
|
14 |
-
API_URL: str = os.getenv("API_URL")
|
15 |
-
MEDIA_UPLOAD_URL: str = os.getenv("MEDIA_UPLOAD_URL")
|
16 |
-
SECRET_KEY: str = os.getenv("SECRET_KEY")
|
17 |
-
ALGORITHM: str = "HS256"
|
18 |
-
ACCESS_TOKEN_EXPIRE_MINUTES: int = 100
|
19 |
-
|
20 |
-
settings = Settings()
|
21 |
-
|
22 |
-
print(f"SECRET_KEY: {settings.SECRET_KEY}") # Add this line to verify the SECRET_KEY
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/crud/user.py
DELETED
@@ -1,30 +0,0 @@
|
|
1 |
-
from app.db.database import db
|
2 |
-
from app.schemas.user import UserCreate
|
3 |
-
from bson.objectid import ObjectId
|
4 |
-
|
5 |
-
async def create_user(user: UserCreate):
|
6 |
-
result = await db.users.insert_one(user.dict())
|
7 |
-
return str(result.inserted_id)
|
8 |
-
|
9 |
-
async def get_user_by_id(user_id: str):
|
10 |
-
user = await db.users.find_one({"_id": ObjectId(user_id)})
|
11 |
-
if user:
|
12 |
-
user["id"] = str(user.pop("_id"))
|
13 |
-
return user
|
14 |
-
|
15 |
-
async def update_user_credits(user_id: str, amount: float):
|
16 |
-
user = await db.users.find_one({"_id": ObjectId(user_id)})
|
17 |
-
if not user:
|
18 |
-
return None
|
19 |
-
|
20 |
-
new_remaining_credits = user["remaining_credits"] + amount
|
21 |
-
payment_status = new_remaining_credits > 0
|
22 |
-
|
23 |
-
await db.users.update_one(
|
24 |
-
{"_id": ObjectId(user_id)},
|
25 |
-
{"$set": {"remaining_credits": new_remaining_credits, "payment_status": payment_status}}
|
26 |
-
)
|
27 |
-
|
28 |
-
user["remaining_credits"] = new_remaining_credits
|
29 |
-
user["payment_status"] = payment_status
|
30 |
-
return user
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/db/database.py
DELETED
@@ -1,46 +0,0 @@
|
|
1 |
-
# app/core/database.py
|
2 |
-
from motor.motor_asyncio import AsyncIOMotorClient
|
3 |
-
from app.core.config import settings
|
4 |
-
from pymongo import IndexModel, ASCENDING
|
5 |
-
import os
|
6 |
-
from dotenv import load_dotenv
|
7 |
-
|
8 |
-
load_dotenv()
|
9 |
-
|
10 |
-
|
11 |
-
client = AsyncIOMotorClient(settings.MONGO_DETAILS)
|
12 |
-
db = client[settings.MongoDB_NAME]
|
13 |
-
|
14 |
-
def get_database(db_name:str):
|
15 |
-
return client[db_name]
|
16 |
-
|
17 |
-
async def create_collection(db_name:str, collection_name:str):
|
18 |
-
database = get_database(db_name)
|
19 |
-
existing_collections = await database.list_collection_names()
|
20 |
-
if collection_name not in existing_collections:
|
21 |
-
await database.create_collection(collection_name)
|
22 |
-
else:
|
23 |
-
print(f"Collection '{collection_name}' already exists in database '{db_name}'")
|
24 |
-
|
25 |
-
|
26 |
-
async def list_collection_names(db_name: str):
|
27 |
-
database = get_database(db_name)
|
28 |
-
collection_names = await database.list_collection_names()
|
29 |
-
return collection_names
|
30 |
-
|
31 |
-
async def init_db():
|
32 |
-
print(f"Initializing database '{settings.MongoDB_NAME}'")
|
33 |
-
for collection_name in settings.COLLECTION_NAMES:
|
34 |
-
await create_collection(settings.MongoDB_NAME, collection_name)
|
35 |
-
|
36 |
-
collections = await list_collection_names(settings.MongoDB_NAME)
|
37 |
-
|
38 |
-
await create_indexes()
|
39 |
-
print(f"Collections in '{settings.MongoDB_NAME}': {collections}")
|
40 |
-
|
41 |
-
# Indexes for users and transactions
|
42 |
-
async def create_indexes():
|
43 |
-
user_index = IndexModel([("email", ASCENDING)], unique=True)
|
44 |
-
transaction_index = IndexModel([("user_id", ASCENDING), ("timestamp", ASCENDING)])
|
45 |
-
await db.users.create_indexes([user_index])
|
46 |
-
await db.transactions.create_indexes([transaction_index])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/endpoints/v1/users.py
DELETED
@@ -1,48 +0,0 @@
|
|
1 |
-
from fastapi import APIRouter, HTTPException, Depends
|
2 |
-
from app.schemas.user import UserCreate, UserResponse, TransactionResponse
|
3 |
-
from app.crud.user import create_user, get_user_by_id, update_user_credits
|
4 |
-
from app.crud.transaction import record_transaction, get_user_transactions
|
5 |
-
|
6 |
-
router = APIRouter()
|
7 |
-
|
8 |
-
@router.post("/", response_model=UserResponse)
|
9 |
-
async def create_new_user(user: UserCreate):
|
10 |
-
user_id = await create_user(user)
|
11 |
-
user_response = await get_user_by_id(user_id)
|
12 |
-
return user_response
|
13 |
-
|
14 |
-
@router.get("/{user_id}", response_model=UserResponse)
|
15 |
-
async def get_user(user_id: str):
|
16 |
-
user = await get_user_by_id(user_id)
|
17 |
-
if not user:
|
18 |
-
raise HTTPException(status_code=404, detail="User not found")
|
19 |
-
return user
|
20 |
-
|
21 |
-
@router.post("/{user_id}/top-up", response_model=TransactionResponse)
|
22 |
-
async def top_up_credits(user_id: str, amount: float):
|
23 |
-
if amount <= 0:
|
24 |
-
raise HTTPException(status_code=400, detail="Amount must be greater than 0")
|
25 |
-
|
26 |
-
transaction = await record_transaction(user_id, amount, "Top-up credits")
|
27 |
-
user = await update_user_credits(user_id, amount)
|
28 |
-
if not user:
|
29 |
-
raise HTTPException(status_code=404, detail="User not found")
|
30 |
-
return transaction
|
31 |
-
|
32 |
-
@router.post("/{user_id}/deduct", response_model=TransactionResponse)
|
33 |
-
async def deduct_credits(user_id: str, amount: float):
|
34 |
-
if amount <= 0:
|
35 |
-
raise HTTPException(status_code=400, detail="Amount must be greater than 0")
|
36 |
-
|
37 |
-
transaction = await record_transaction(user_id, -amount, "Deduct credits")
|
38 |
-
user = await update_user_credits(user_id, -amount)
|
39 |
-
if not user:
|
40 |
-
raise HTTPException(status_code=404, detail="User not found")
|
41 |
-
return transaction
|
42 |
-
|
43 |
-
@router.get("/{user_id}/transactions", response_model=list[TransactionResponse])
|
44 |
-
async def list_transactions(user_id: str):
|
45 |
-
transactions = await get_user_transactions(user_id)
|
46 |
-
if not transactions:
|
47 |
-
raise HTTPException(status_code=404, detail="No transactions found")
|
48 |
-
return transactions
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app/main.py
CHANGED
@@ -13,8 +13,7 @@ import logging
|
|
13 |
from datetime import datetime
|
14 |
import time
|
15 |
from contextlib import asynccontextmanager
|
16 |
-
from app.db.database import create_indexes, init_db
|
17 |
-
from app.endpoints.v1 import users
|
18 |
from app.services.webhook_handler import verify_webhook
|
19 |
from app.handlers.message_handler import MessageHandler
|
20 |
from app.handlers.webhook_handler import WebhookHandler
|
@@ -55,7 +54,7 @@ async def lifespan(app: FastAPI):
|
|
55 |
|
56 |
|
57 |
try:
|
58 |
-
await init_db()
|
59 |
|
60 |
logger.info("Connected to the MongoDB database!")
|
61 |
|
@@ -77,7 +76,7 @@ app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
|
77 |
|
78 |
|
79 |
|
80 |
-
app.include_router(users.router, prefix="/users", tags=["Users"])
|
81 |
|
82 |
|
83 |
# Prometheus metrics
|
|
|
13 |
from datetime import datetime
|
14 |
import time
|
15 |
from contextlib import asynccontextmanager
|
16 |
+
# from app.db.database import create_indexes, init_db
|
|
|
17 |
from app.services.webhook_handler import verify_webhook
|
18 |
from app.handlers.message_handler import MessageHandler
|
19 |
from app.handlers.webhook_handler import WebhookHandler
|
|
|
54 |
|
55 |
|
56 |
try:
|
57 |
+
# await init_db()
|
58 |
|
59 |
logger.info("Connected to the MongoDB database!")
|
60 |
|
|
|
76 |
|
77 |
|
78 |
|
79 |
+
# app.include_router(users.router, prefix="/users", tags=["Users"])
|
80 |
|
81 |
|
82 |
# Prometheus metrics
|
llamma-duo/generate_dataset.py
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import google.generativeai as genai
|
2 |
+
|
3 |
+
import google.generativeai as genai
|
4 |
+
|
5 |
+
genai.configure(api_key="AIzaSyAJxmpiEGSDGAPHiJDbIuclq6EUaQCpPyg")
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
# Initialize the model
|
10 |
+
model = genai.GenerativeModel("gemini-1.5-pro-002")
|
11 |
+
|
12 |
+
prompt = """
|
13 |
+
Hasilkan serangkaian pasangan (instruksi, respons) yang serupa dalam konteks dan struktur dengan contoh yang disediakan di bawah ini. Setiap pasangan harus terdiri dari instruksi singkat yang diikuti oleh respons yang terperinci dan sesuai. Instruksi harus mengajukan tugas atau pertanyaan yang jelas, sementara respons harus memberikan jawaban atau solusi komprehensif yang dapat dipahami oleh seseorang dengan pemahaman dasar tentang subjek tersebut.
|
14 |
+
|
15 |
+
Contoh pasangan:
|
16 |
+
|
17 |
+
Instruksi: Jelaskan perbedaan antara saham biasa (common stock) dan saham preferen (preferred stock) dalam investasi pasar modal. Apa keunggulan dan kelemahan masing-masing jenis saham ini bagi investor?
|
18 |
+
Respons: Saham biasa dan saham preferen memiliki karakteristik yang berbeda dalam investasi.
|
19 |
+
|
20 |
+
Saham Biasa (Common Stock):
|
21 |
+
- Memberikan hak suara dalam rapat pemegang saham
|
22 |
+
- Potensi keuntungan lebih tinggi melalui apresiasi harga saham
|
23 |
+
- Dividen tidak dijamin dan bervariasi tergantung kinerja perusahaan
|
24 |
+
- Risiko kerugian lebih besar jika perusahaan mengalami kebangkrutan
|
25 |
+
|
26 |
+
Saham Preferen (Preferred Stock):
|
27 |
+
- Tidak memiliki hak suara dalam rapat pemegang saham
|
28 |
+
- Membayar dividen tetap dan terjamin sebelum pembagian dividen saham biasa
|
29 |
+
- Prioritas pembayaran lebih tinggi saat likuidasi perusahaan
|
30 |
+
- Fluktuasi harga saham biasanya lebih rendah dibandingkan saham biasa
|
31 |
+
- Cocok untuk investor yang mencari pendapatan tetap dengan risiko lebih rendah
|
32 |
+
|
33 |
+
Perbedaan utama terletak pada hak suara, struktur dividen, dan prioritas pembayaran dalam struktur permodalan perusahaan.
|
34 |
+
|
35 |
+
Tugas Anda adalah menghasilkan lebih banyak pasangan yang mempertahankan tingkat kejelasan dan detail ini. Topiknya adalah Keuangan dan Investasi. Pastikan respons informatif dan akurat, sesuai untuk konteks pendidikan.
|
36 |
+
|
37 |
+
Simpan pasangan yang dihasilkan dalam format JSON, dengan setiap pasangan sebagai objek dalam sebuah array. Setiap objek harus memiliki dua pasangan key-value: "instruksi" dan "respons". Misalnya:
|
38 |
+
|
39 |
+
[{"instruksi": teks, "respons": teks}, {"instruksi": teks, "respons": teks}, ...]
|
40 |
+
|
41 |
+
Pastikan untuk mempertahankan konsistensi dalam format dan memastikan pasangan yang dihasilkan beragam dan mencakup berbagai subjek dalam bidang keuangan.
|
42 |
+
"""
|
43 |
+
|
44 |
+
response = model.generate_content(prompt)
|
45 |
+
|
46 |
+
text_result = response.text
|
47 |
+
print(f"Text result: {text_result}")
|
48 |
+
|
49 |
+
from IPython.display import Markdown
|
50 |
+
import textwrap
|
51 |
+
|
52 |
+
def to_markdown(text):
|
53 |
+
text = text.replace('•', ' *')
|
54 |
+
return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))
|
55 |
+
|
56 |
+
to_markdown(text_result)
|
57 |
+
|
58 |
+
import json
|
59 |
+
|
60 |
+
def _find_json_snippet(raw_snippet):
|
61 |
+
"""
|
62 |
+
_find_json_snippet tries to find JSON snippets in a given raw_snippet string
|
63 |
+
"""
|
64 |
+
json_parsed_string = None
|
65 |
+
|
66 |
+
json_start_index = raw_snippet.find('[')
|
67 |
+
json_end_index = raw_snippet.rfind(']')
|
68 |
+
|
69 |
+
if json_start_index >= 0 and json_end_index >= 0:
|
70 |
+
json_snippet = raw_snippet[json_start_index:json_end_index+1]
|
71 |
+
try:
|
72 |
+
json_parsed_string = json.loads(json_snippet, strict=False)
|
73 |
+
except:
|
74 |
+
raise ValueError('......failed to parse string into JSON format')
|
75 |
+
else:
|
76 |
+
raise ValueError('......No JSON code snippet found in string.')
|
77 |
+
|
78 |
+
return json_parsed_string
|
79 |
+
|
80 |
+
print(f"JSON result: {_find_json_snippet(text_result)}")
|