amish1706 commited on
Commit
1fe02e8
·
verified ·
1 Parent(s): dc2c9ca

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -0
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ import gradio as gr
4
+ import os
5
+ import shutil
6
+ import json
7
+ import openai
8
+
9
+ api_key = os.getenv("OPENAI-API-KEY")
10
+
11
+ # Load the OpenAI API key
12
+ openai.api_key = api_key
13
+
14
+ def ask_chatbot(query, chat_history, project_data):
15
+ # Convert project_data to a string format (optional: simplify or summarize if needed)
16
+ project_data_str = json.dumps(project_data, indent=2)
17
+
18
+ if len(chat_history) >= 5:
19
+ chat_history.pop(0)
20
+
21
+ query_with_history = ""
22
+ for question, answer in chat_history:
23
+ query_with_history += f"\nUser: {question}\nAssistant: {answer}"
24
+
25
+ query_with_history += f"\nUser: {query}"
26
+
27
+
28
+ # Define the messages
29
+ messages = [
30
+ {"role": "system", "content": "You are a virtual project management assistant. Analyzing the given project information for a website redesign project, you have to answer project managers' questions:"},
31
+ {"role": "system", "content": project_data_str},
32
+ {"role": "user", "content": query_with_history}
33
+ ]
34
+
35
+ # Call the OpenAI API
36
+ response = openai.ChatCompletion.create(
37
+ model="gpt-3.5-turbo",
38
+ messages=messages,
39
+ max_tokens=512
40
+ )
41
+
42
+ # Extract the response text
43
+ answer = response.choices[0].message['content'].strip()
44
+
45
+ return answer
46
+
47
+
48
+ def generate_response(message, history):
49
+ project_data = {}
50
+ if os.path.exists("/content/project_data.json"):
51
+ with open("/content/project_data.json", 'r') as f:
52
+ project_data = json.load(f)
53
+ return ask_chatbot(message, history, project_data)
54
+
55
+
56
+
57
+ def upload_file(data_file):
58
+ with open(data_file.name, "r") as f:
59
+ data = json.load(f)
60
+ gr.Info("Prooject file Uploaded. You can now query the document")
61
+ with open("/content/project_data.json", "w") as f:
62
+ json.dump(data, f)
63
+
64
+ with gr.Blocks() as demo:
65
+ with gr.Column():
66
+ u = gr.UploadButton("Upload a file", file_count="single")
67
+ u.upload(upload_file, u)
68
+ gr.ChatInterface(generate_response)
69
+
70
+ demo.launch()
71
+