Spaces:
Running
Running
Huy Nguyen
commited on
Commit
·
a22e37c
1
Parent(s):
7cab994
add missing endpoint
Browse files- env.py +2 -7
- flashcard_util.py +3 -21
- local.sh +2 -0
- main.py +47 -0
- untitled +1 -0
env.py
CHANGED
@@ -7,12 +7,7 @@ CX = getenv("CX")
|
|
7 |
IMSEARCH_API_KEY = getenv("IMSEARCH_API_KEY")
|
8 |
HOST_URL = getenv("HOST_URL")
|
9 |
|
10 |
-
print(
|
11 |
-
print("GOOGLE_API_KEY:", GOOGLE_API_KEY)
|
12 |
-
print("CX:", CX)
|
13 |
-
print("IMSEARCH_API_KEY:", IMSEARCH_API_KEY)
|
14 |
-
print("HOST_URL:", HOST_URL)
|
15 |
-
|
16 |
|
17 |
def get_llm_api_key():
|
18 |
-
return choice(LLM_API_KEYS)
|
|
|
7 |
IMSEARCH_API_KEY = getenv("IMSEARCH_API_KEY")
|
8 |
HOST_URL = getenv("HOST_URL")
|
9 |
|
10 |
+
print(LLM_API_KEYS)
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
def get_llm_api_key():
|
13 |
+
return choice(LLM_API_KEYS)
|
flashcard_util.py
CHANGED
@@ -8,7 +8,7 @@ from re import match, sub, findall, fullmatch
|
|
8 |
from re import split as re_split
|
9 |
from env import HOST_URL
|
10 |
from PIL import Image
|
11 |
-
from env import
|
12 |
|
13 |
def remove_numbering(text):
|
14 |
"""Removes list-like numberings (e.g., 1., 2. etc.) from a string.
|
@@ -26,7 +26,7 @@ async def tldr(content, l=lang.VI_VN):
|
|
26 |
async with httpx.AsyncClient() as client:
|
27 |
_r = await client.post(
|
28 |
url="https://api.awanllm.com/v1/chat/completions",
|
29 |
-
headers={'Content-Type': 'application/json', 'Authorization': f'Bearer {
|
30 |
data=json.dumps({
|
31 |
"model": "Meta-Llama-3-8B-Instruct",
|
32 |
"messages": [
|
@@ -41,24 +41,6 @@ async def tldr(content, l=lang.VI_VN):
|
|
41 |
# print(_summary)
|
42 |
return _summary['choices'][0]['message']['content'].split('\n',1)[-1].strip()
|
43 |
|
44 |
-
# import io
|
45 |
-
# import asyncio
|
46 |
-
# from functools import partial
|
47 |
-
# def optimize_image(data, _fn):
|
48 |
-
# with Image.open(io.BytesIO(data)) as img:
|
49 |
-
# img.save(f'{_fn}.webp', optimize=True)
|
50 |
-
|
51 |
-
# async def download_img(_url, _prefix=HOST_URL):
|
52 |
-
# _r = None
|
53 |
-
# async with httpx.AsyncClient() as client:
|
54 |
-
# _r = await client.get(url=_url, timeout=None)
|
55 |
-
|
56 |
-
# _fn = f'img_{str(hash(_url))}'
|
57 |
-
# if _r.status_code//100 == 2:
|
58 |
-
# _loop = asyncio.get_running_loop()
|
59 |
-
# _out = await _loop.run_in_executor(None, partial(optimize_image, _r.content, _fn))
|
60 |
-
|
61 |
-
# return f"{_prefix}/images/{_fn}.webp"
|
62 |
|
63 |
async def fetch_img_for_words(words: list[str], __url_prefix=None):
|
64 |
print("fetching images...")
|
@@ -71,7 +53,7 @@ async def get_definitions_from_words(words: list[str], summary: str = "", lang:
|
|
71 |
async with httpx.AsyncClient() as client:
|
72 |
_r = await client.post(
|
73 |
url="https://api.awanllm.com/v1/chat/completions",
|
74 |
-
headers={'Content-Type': 'application/json', 'Authorization': f'Bearer {
|
75 |
data=json.dumps({
|
76 |
"model": "Meta-Llama-3-8B-Instruct",
|
77 |
"messages": [
|
|
|
8 |
from re import split as re_split
|
9 |
from env import HOST_URL
|
10 |
from PIL import Image
|
11 |
+
from env import get_llm_api_key
|
12 |
|
13 |
def remove_numbering(text):
|
14 |
"""Removes list-like numberings (e.g., 1., 2. etc.) from a string.
|
|
|
26 |
async with httpx.AsyncClient() as client:
|
27 |
_r = await client.post(
|
28 |
url="https://api.awanllm.com/v1/chat/completions",
|
29 |
+
headers={'Content-Type': 'application/json', 'Authorization': f'Bearer {get_llm_api_key()}'},
|
30 |
data=json.dumps({
|
31 |
"model": "Meta-Llama-3-8B-Instruct",
|
32 |
"messages": [
|
|
|
41 |
# print(_summary)
|
42 |
return _summary['choices'][0]['message']['content'].split('\n',1)[-1].strip()
|
43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
|
45 |
async def fetch_img_for_words(words: list[str], __url_prefix=None):
|
46 |
print("fetching images...")
|
|
|
53 |
async with httpx.AsyncClient() as client:
|
54 |
_r = await client.post(
|
55 |
url="https://api.awanllm.com/v1/chat/completions",
|
56 |
+
headers={'Content-Type': 'application/json', 'Authorization': f'Bearer {get_llm_api_key()}'},
|
57 |
data=json.dumps({
|
58 |
"model": "Meta-Llama-3-8B-Instruct",
|
59 |
"messages": [
|
local.sh
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
redis-server --save "" &
|
2 |
+
uvicorn main:app --port 4200 --reload
|
main.py
CHANGED
@@ -788,6 +788,52 @@ async def get_cached_img_from_disk(request):
|
|
788 |
else:
|
789 |
raise HTTPException(404)
|
790 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
791 |
async def root(requests):
|
792 |
return PlainTextResponse("Success")
|
793 |
|
@@ -819,6 +865,7 @@ app = Starlette(debug=True,routes=[
|
|
819 |
Route('/mltest', __mltest, methods=['GET']),
|
820 |
Route('/validateSimilarity', validate_similarity, methods=['POST']),
|
821 |
Route('/llmGenerateText', llm_generate_text, methods=['POST']),
|
|
|
822 |
Route('/', root, methods=['GET']),
|
823 |
],
|
824 |
middleware=middleware)
|
|
|
788 |
else:
|
789 |
raise HTTPException(404)
|
790 |
|
791 |
+
async def generate_redemption(request):
|
792 |
+
req = await request.json()
|
793 |
+
paragraphs = req['pgphs']
|
794 |
+
|
795 |
+
ret_questions = []
|
796 |
+
|
797 |
+
ptasks = []
|
798 |
+
for paragraph in paragraphs:
|
799 |
+
ptasks.append(__query_ml_predict(QType.WH, paragraph["content"], paragraph["header"], 4096, num_qs=paragraph.get("count", 1)*5, l=req['lang']))
|
800 |
+
|
801 |
+
raw_questions: list[str] = await asyncio.gather(*ptasks)
|
802 |
+
for query in raw_questions:
|
803 |
+
if not query['success']:
|
804 |
+
continue
|
805 |
+
|
806 |
+
q = query['content']
|
807 |
+
|
808 |
+
raw_segments = [x.strip() for x in q.split('\n') if x.strip()]
|
809 |
+
filtered = []
|
810 |
+
seg_cnt = 0
|
811 |
+
seg_map = ['Q', 'A', 'B', 'C', 'D', '']
|
812 |
+
for r in raw_segments:
|
813 |
+
if r.startswith(seg_map[seg_cnt]):
|
814 |
+
if seg_cnt == 5:
|
815 |
+
if not ('A' in r or 'B' in r or 'C' in r or 'D' in r):
|
816 |
+
continue
|
817 |
+
filtered.append(r)
|
818 |
+
seg_cnt += 1
|
819 |
+
if seg_cnt == 6:
|
820 |
+
_r = filtered[5]
|
821 |
+
ans_index = 1 if 'A' in _r else 2 if 'B' in _r else 4 if 'D' in _r else 3
|
822 |
+
ans_key = filtered[ans_index][2:].strip()
|
823 |
+
|
824 |
+
if randint(0, 1) == 1:
|
825 |
+
ret_questions.append({'prompt': filtered[0], 'keys': [ans_key,]})
|
826 |
+
else:
|
827 |
+
prompt_format = "\n".join(filtered[0:5])
|
828 |
+
ret_questions.append({'prompt': prompt_format, 'keys': [seg_map[ans_index]]})
|
829 |
+
|
830 |
+
filtered.clear()
|
831 |
+
seg_cnt = 0
|
832 |
+
|
833 |
+
return JSONResponse({'questions': ret_questions})
|
834 |
+
|
835 |
+
|
836 |
+
|
837 |
async def root(requests):
|
838 |
return PlainTextResponse("Success")
|
839 |
|
|
|
865 |
Route('/mltest', __mltest, methods=['GET']),
|
866 |
Route('/validateSimilarity', validate_similarity, methods=['POST']),
|
867 |
Route('/llmGenerateText', llm_generate_text, methods=['POST']),
|
868 |
+
Route('/generateRedemption', generate_redemption, methods=['POST']),
|
869 |
Route('/', root, methods=['GET']),
|
870 |
],
|
871 |
middleware=middleware)
|
untitled
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
{"pgphs":[{"header":"# Ancient Inventions","h_cnt":1,"content":"Ancient civilizations, from Mesopotamia to China, were hotbeds of ingenuity. Though lacking the materials and knowledge of modern times, they developed remarkable tools and technologies that transformed their societies and continue to influence us today. Here's a glimpse into some key areas of innovation:\n- **Agriculture:** The plow, irrigation systems, and selective breeding techniques revolutionized food production, enabling settled societies and population growth. - **Engineering:** The development of complex structures like pyramids, aqueducts, and the Great Wall of China showcased remarkable engineering feats. - **Materials Science:** The creation of bronze, iron, and glass allowed for stronger tools, weapons, and beautiful artwork. - **Writing:** The invention of cuneiform, hieroglyphs, and other writing systems facilitated communication, record-keeping, and the transmission of knowledge. - **Medicine:** Ancient cultures practiced basic surgery, developed remedies from plants, and even performed rudimentary dentistry. - **Transportation:** The wheel, chariots, and ships revolutionized travel and trade, allowing for the exchange of goods and ideas across vast distances.\nThese are just a few examples. From the sundial to the compass, ancient inventions laid the foundation for scientific discovery and technological advancements that continue to shape our world.","count":3}],"lang":"English"}
|