Mbonea commited on
Commit
8178d95
1 Parent(s): ad7e461

testing changes

Browse files
Files changed (2) hide show
  1. App/Chat/ChatRoutes.py +47 -0
  2. App/Chat/utils/PalmAPI.py +112 -0
App/Chat/ChatRoutes.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Request,Depends
2
+ from App.Users.Model import User
3
+ from App.Users.UserRoutes import get_token_owner
4
+ from App.Users.Schemas import UserSchema
5
+ from App.Transcription.Model import Transcriptions
6
+ from App.Transcription.Schemas import *
7
+ from App import bot
8
+ from .utils.PalmAPI import generate_summary,summarization
9
+ import aiohttp
10
+ import os
11
+
12
+ chat_router = APIRouter(tags=["chat"])
13
+
14
+
15
+ P_API_KEY = os.environ.get("API_KEY")
16
+ P_API_BASE = os.environ.get("P_API_BASE")
17
+ API_URL = f"{P_API_BASE}chat-bison-001:generateMessage?key={P_API_KEY}"
18
+
19
+
20
+ async def fetch_and_forward_request(request_body):
21
+ async with aiohttp.ClientSession() as session:
22
+ async with session.post(API_URL, data=request_body) as response:
23
+ response_text = await response.text()
24
+ return response_text, response.status
25
+
26
+
27
+ # @chat_router.post("/sql")
28
+ # async def generate_message(request_body: str):
29
+ # response_body, status_code = await fetch_and_forward_request(request_body)
30
+ # return response_body
31
+
32
+
33
+ @chat_router.post("/summarize/{task_id}")
34
+ async def generate_message( task_id: str,
35
+ user: UserSchema = Depends(get_token_owner)):
36
+ entry: Transcriptions = await Transcriptions.objects.filter(task_id=task_id).first()
37
+ result = BaseTranscription(**entry.__dict__)
38
+ text =''
39
+ for item in result.content:
40
+ text+=item['text']
41
+ docs=generate_summary(text)
42
+ summaries =[]
43
+ for doc in docs:
44
+ summary=await summarization(doc.page_content)
45
+ summaries.append(summary)
46
+ return summaries
47
+
App/Chat/utils/PalmAPI.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import aiohttp
2
+ import asyncio
3
+ import google.generativeai as palm
4
+ import os
5
+ PALM_API = ""
6
+ API_KEY=os.environ.get("PALM_API",PALM_API)
7
+ palm.configure(api_key=API_KEY)
8
+
9
+
10
+
11
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
12
+
13
+
14
+ def count_tokens(text):
15
+ return palm.count_message_tokens(prompt=text)['token_count']
16
+
17
+
18
+
19
+ async def summarization(text):
20
+ url = f"https://generativelanguage.googleapis.com/v1beta2/models/text-bison-001:generateText?key={API_KEY}"
21
+
22
+ headers = {
23
+ "Content-Type": "application/json",
24
+ }
25
+
26
+ data = {
27
+ "prompt": {
28
+ "text": f"### You are given the an audio transcript and its title as context. You are required to write a summary, list down the main takeaways, also cite the text when necessary.\n<input> \"There's actually a military proven technique to fall asleep in exactly two minutes after closing your eyes. It's mind-blowing. Here's how you can do it too. Now, this technique was developed in the military to allow soldiers to fall asleep at any time, any place, even on the battlefield when the environment is extremely uncomfortable and there's a lot of noise happening. Sleep for a soldier is crucial. Now, according to my research, this was developed mainly for fighter pilots who need 100% of their reflexes and focus, which we all know decreases with the lack of sleep. So here's the technique that they use, and it's quite simple. First, you need to calm your body and systematically relax and shut down each part of your body from head to toe, literally. Start by relaxing the muscles in your forehead. Relax your eyes, your cheeks, your jaw, and focus on your breathing. Now go down to your neck and your shoulders. Make sure your shoulders are not tensed up, drop them as low as you can, and keep your arms loose to your side, including your hands and fingers. Imagine this warm sensation going from your head all the way down to your fingertips. Now take a deep breath and slowly exhale, relaxing your chest, your stomach, down to your thighs, knees, legs, and feet. Again, imagine this warm sensation going down from your heart all the way to your toes. Now while you're doing this, it's really important to clear your mind of any stresses. To do this, think of two scenarios. One, you're lying in a canoe on a calm lake with nothing but a clear blue sky above you. Two, you're lying in a black velvet hammock in a pitch black room. At any time when you start thinking of anything else or you start getting distracted, repeat these words for 10 seconds. Don't think. Don't think. Don't think. So that's the technique. You're supposed to practice every night for six weeks. 96% of people who master this technique are actually able to fall asleep within two minutes of shutting their eyes. I find it super interesting. I did not invent this technique, but I'm definitely going to try it out. Let me know if you're on board as well.\"\n</input>\n<output>\nSummary: The military developed a technique to help soldiers fall asleep at any time, any place. This technique involves systematically relaxing and shutting down each part of the body from head to toe, while clearing the mind of any stresses.\n</output>\n\n\n\n {text}"
29
+ },
30
+ "temperature": 0.95,
31
+ "top_k": 100,
32
+ "top_p": 0.95,
33
+ "candidate_count": 1,
34
+ "max_output_tokens": 1024,
35
+ "stop_sequences": ["</output>"],
36
+ "safety_settings": [
37
+ {"category": "HARM_CATEGORY_DEROGATORY", "threshold": 4},
38
+ {"category": "HARM_CATEGORY_TOXICITY", "threshold": 4},
39
+ {"category": "HARM_CATEGORY_VIOLENCE", "threshold": 4},
40
+ {"category": "HARM_CATEGORY_SEXUAL", "threshold": 4},
41
+ {"category": "HARM_CATEGORY_MEDICAL", "threshold": 4},
42
+ {"category": "HARM_CATEGORY_DANGEROUS", "threshold": 4},
43
+ ],
44
+ }
45
+
46
+
47
+ async with aiohttp.ClientSession() as session:
48
+ async with session.post(url, json=data, headers=headers) as response:
49
+ if response.status == 200:
50
+ result = await response.json()
51
+ print(result)
52
+ temp = result["candidates"][0]["output"]
53
+ print(temp)
54
+ else:
55
+ print(f"Error: {response.status}\n{await response.text()}")
56
+
57
+
58
+
59
+ def generate_summary(data):
60
+ template = """ {data} """.format(data=data)
61
+ chunk_size = 30_000
62
+ inc = 250
63
+ max_tokens = 7000
64
+ min_tokens = 6000
65
+ max_token_doc = 0
66
+
67
+ # choose the appropriate chunk size
68
+ while True:
69
+ # initialize text splitter
70
+ text_splitter = RecursiveCharacterTextSplitter(
71
+ separators=["\n\n", "\n"],
72
+ chunk_size=chunk_size,
73
+ chunk_overlap=0,
74
+ )
75
+ docs = text_splitter.create_documents([data])
76
+ temp =[]
77
+ for doc in docs:
78
+ temp_tokens=count_tokens(doc.page_content)
79
+ temp.append(temp_tokens)
80
+ max_token_doc = max(temp)
81
+ docs_count=len(temp)
82
+ # print(docs[0].page_content)
83
+ if docs_count ==1:
84
+ break
85
+ if max_tokens < max_token_doc or max_token_doc < min_tokens:
86
+ if max_tokens < max_token_doc:
87
+ chunk_size -= inc
88
+ else:
89
+ chunk_size += inc
90
+ continue
91
+
92
+ else:
93
+ break
94
+ return docs
95
+
96
+
97
+ async def main():
98
+ docs=generate_summary(''' <input>
99
+ Transcript
100
+ Yo, Mabu, you really the only independent artist putting up numbers right now, bro They call me the independent variable for a reason gang. Oh, that's why I spent eight hours a day in school And I still put up more numbers than these fleas Like most of our rappers in Santa the streets only dealers who took was a plea I'm using the police, so this is a match that I'm a PD I cover my rhymes, I'm an innocent creep, keep my daily back when I sleep I'm rapping the words, but they write it for me Me, I'm all about keeping the peace, I'm me at least I get paid because a lot of these rhymes make up for free They call me the duck, I got the spreadsheet shot, but say, can I bring a friend? Never, never, never I guess she forgot the bad light, the two fives don't equal a ten Quick math, don't try it again, she's shaped like a turtle Or a hen, her makeup is fucked, she don't know how to blend, make her do worldle She did it her brains if she given her head, call her Virgil Cause the way she be blind shit got me dead She had a gut arc ten, I want it in a second circle She like Babu, I like purple, so I blew her back out when I left her on red Get it, cause blue and red equals purple So I blew her back out when I left her on red, don't let that go over your head One thought, two thought, three thought four They offered their knees on the floor, Keisha Becky, Sophie, so Texted me begging for mob, black in their bitches, she calling me bro If you're my dog then throw my bone Ruff, ruff, throw my booty, Keisha's in a flow To all my competition, take a grip, take a grip I invested money in myself and it paid, I can take a break too My boy is a household name</input>''' )
101
+
102
+ for doc in docs:
103
+ summary=await summarization(doc.page_content)
104
+ print(summary)
105
+
106
+
107
+
108
+
109
+
110
+
111
+ if __name__ == '__main__':
112
+ asyncio.run(main=main())