Abdulrahman Almutlaq commited on
Commit
044b38d
1 Parent(s): 4b2509d
Files changed (5) hide show
  1. app.py +16 -0
  2. grad.py +214 -0
  3. helper.py +729 -0
  4. prompts.py +229 -0
  5. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from grad import random_response
3
+
4
+
5
+
6
+
7
+ demo = gr.ChatInterface(random_response, title = 'نموذج فزاع للذكاء الاصطناعي',
8
+ description="""
9
+ فزاع هو نموذج لغوي ضخم ومتقدم يتميز بقدرته على إنشاء وتحرير وتوليد الملفات التحليلية. تم تصميمه خصيصًا لدعم وتطوير الأعمال. باستخدام تقنيات الذكاء الاصطناعي المتقدمة، يوفر فزاع حلاً فعالًا وسريعًا للشركات والجهات التي تسعى لتحسين وثائقها وإجراءاتها الداخلية""",
10
+ examples=['Start Model',\
11
+ 'hotel management system',\
12
+ 'Adding Employee',\
13
+ 'View Employee information including nationality'],
14
+ undo_btn=None, clear_btn=None)
15
+
16
+ demo.launch(inline = False, blocked_paths = ['NCGR/grad', './helper', 'requirements.txt','prompts.py'])
grad.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import time
4
+ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
5
+ from langchain.chat_models import ChatOpenAI
6
+ from langchain.llms import OpenAI
7
+ import os
8
+ import json
9
+ import openai
10
+ import random
11
+ import asyncio
12
+ from langchain.prompts import (
13
+ ChatPromptTemplate,
14
+ HumanMessagePromptTemplate
15
+ )
16
+ from ast import literal_eval
17
+ from langchain.chat_models import ChatOpenAI
18
+ from langchain.schema import (
19
+ HumanMessage,
20
+ )
21
+
22
+ import json
23
+ from langchain.chat_models import ChatOpenAI
24
+ from langchain.llms import OpenAI
25
+ from langchain.chat_models import ChatAnthropic
26
+ from langchain.output_parsers import PydanticOutputParser
27
+ from pydantic import BaseModel, Field
28
+ from typing import List
29
+ import json
30
+ from ast import literal_eval
31
+ import os
32
+ import openai
33
+ import random
34
+ import time
35
+ import copy
36
+ import asyncio
37
+ from prompts import system_structure_template, system_epics_template, story_cards_template, schema_template, entities_template, update_schema_template, check_message_template, update_story_cards_template
38
+
39
+ import helper
40
+
41
+
42
+ myl = []
43
+ os.environ['OPENAI_API_KEY'] = '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'
44
+ openai.api_key = "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"
45
+ epics = []
46
+ latest_nums = []
47
+
48
+ # Deleting all the files after each update
49
+ for file in os.listdir():
50
+ if file.endswith('_gradio.json'):
51
+ helper.delete(file)
52
+
53
+
54
+ async def random_response(message, history, my_list=myl):
55
+
56
+ print(message)
57
+
58
+ if helper.Validating_Input(message): # Check if the question about gpt
59
+
60
+ return helper.apologise(random.randint(0,3))
61
+
62
+ if not helper.is_all_english_alpha_numeric_or_space(message): # Check if the non english text sent
63
+
64
+ return helper.apologise_lang(random.randint(0,3))
65
+
66
+
67
+ # ============================================================================================
68
+
69
+ if message.isnumeric():
70
+ latest_nums.append((int(message)+1))
71
+
72
+ if int(message)==1:
73
+ return helper.create_user_story()
74
+
75
+ elif int(message)==2:
76
+ latest_nums.append(-1)
77
+ return "Sorry, this option will be available in the next version!" + helper.choose()
78
+ else:
79
+ latest_nums.append(-1)
80
+ return 'return a valid number please'
81
+
82
+
83
+ if len(myl) == 0:
84
+
85
+ latest_nums.append(1)
86
+ myl.append(1)
87
+
88
+ return "Welcome to فزاع \n\n" + "Please write your systm discreption in order to build a system"
89
+
90
+ else:
91
+
92
+
93
+
94
+
95
+ if latest_nums[-1] not in [1,2,3]:
96
+ latest_nums.pop()
97
+ return 'return a valid number. ' + helper.choose()
98
+
99
+ if latest_nums[-1] == 1:
100
+
101
+ myl.append(1)
102
+
103
+ # First Prompt System Structure
104
+
105
+ start_time = time.time()
106
+
107
+ response = helper.first_prompt(system_name = message)
108
+
109
+ elapsed_time = time.time() - start_time
110
+ print(f"first_prompt {elapsed_time:.2f} seconds to run.")
111
+
112
+
113
+ # Second Prompt Epics
114
+ start_time = time.time()
115
+
116
+
117
+ epics = await helper.second_prompt(response, system_name = message)
118
+
119
+ elapsed_time = time.time() - start_time
120
+ print(f"epics {elapsed_time:.2f} seconds to run.")
121
+
122
+ # Third Prompt Entities
123
+
124
+ start_time = time.time()
125
+
126
+ entities = helper.third_prompt(epics)
127
+
128
+ elapsed_time = time.time() - start_time
129
+ print(f"entities {elapsed_time:.2f} seconds to run.")
130
+
131
+ # Fourth Prompt Data Schema
132
+
133
+ start_time = time.time()
134
+
135
+ all_schemas = await helper.fourth_prompt(entities, epics)
136
+
137
+ elapsed_time = time.time() - start_time
138
+ print(f"all_schemas {elapsed_time:.2f} seconds to run.")
139
+
140
+ # return markdown
141
+
142
+ output = helper.markdown('epics_gradio.json') + helper.choose()
143
+
144
+ latest_nums.append(-1)
145
+
146
+ return output
147
+
148
+
149
+
150
+ if latest_nums[-1] == 2:
151
+
152
+ # res = check('user story card', message).lower()
153
+
154
+ # print(res)
155
+
156
+ # if res == 'no':
157
+ # return apologise(random.randint(0,3))+"\n\n"+create_user_story()
158
+
159
+ start_time = time.time()
160
+
161
+ helper.affected_parts(user_request = message)
162
+
163
+ elapsed_time = time.time() - start_time
164
+ print(f"affected_parts {elapsed_time:.2f} seconds to run.")
165
+
166
+ output = ""
167
+
168
+ start_time = time.time()
169
+
170
+ new_card = helper.generate_story_cards(user_request = message)
171
+
172
+ elapsed_time = time.time() - start_time
173
+ print(f"generate_story_cards {elapsed_time:.2f} seconds to run.")
174
+
175
+ start_time = time.time()
176
+ output += helper.user_story_to_markdown(new_card) + "\n\n\n"
177
+
178
+ elapsed_time = time.time() - start_time
179
+ print(f"user_story_to_markdown {elapsed_time:.2f} seconds to run.")
180
+
181
+
182
+ start_time = time.time()
183
+ story_ids = helper.check_affected_story_ids()
184
+
185
+ elapsed_time = time.time() - start_time
186
+ print(f"check_affected_story_ids {elapsed_time:.2f} seconds to run.")
187
+
188
+ start_time = time.time()
189
+
190
+ if len(story_ids) != 0:
191
+
192
+ updated_cards = await helper.update_affected_story_cards(story_ids)
193
+
194
+ output += "=============================== The following is the affected user story card ==================================\n\n"
195
+
196
+ for card in updated_cards:
197
+
198
+ output += helper.user_story_to_markdown(card)
199
+
200
+
201
+ elapsed_time = time.time() - start_time
202
+ print(f"update_affected_story_cards {elapsed_time:.2f} seconds to run.")
203
+
204
+ output += helper.choose()
205
+
206
+ latest_nums.append(-1)
207
+
208
+ return output
209
+
210
+
211
+
212
+
213
+
214
+
helper.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import random
3
+ import time
4
+ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
5
+ from langchain.chat_models import ChatOpenAI
6
+ from langchain.llms import OpenAI
7
+ import os
8
+ import json
9
+ import openai
10
+ import random
11
+ import asyncio
12
+ from langchain.prompts import (
13
+ ChatPromptTemplate,
14
+ HumanMessagePromptTemplate
15
+ )
16
+ from ast import literal_eval
17
+ from langchain.chat_models import ChatOpenAI
18
+ from langchain.schema import (
19
+ HumanMessage,
20
+ )
21
+
22
+ import json
23
+ from langchain.chat_models import ChatOpenAI
24
+ from langchain.llms import OpenAI
25
+ from langchain.chat_models import ChatAnthropic
26
+ from langchain.output_parsers import PydanticOutputParser
27
+ from pydantic import BaseModel, Field
28
+ from typing import List
29
+ import json
30
+ from ast import literal_eval
31
+ import os
32
+ import openai
33
+ import random
34
+ import time
35
+ import copy
36
+ import asyncio
37
+ from prompts import system_structure_template, system_epics_template, story_cards_template, schema_template, entities_template, update_schema_template, check_message_template, update_story_cards_template
38
+
39
+
40
+
41
+
42
+ os.environ['OPENAI_API_KEY'] = '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'
43
+ openai.api_key = "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"
44
+
45
+
46
+ llm=ChatOpenAI(
47
+ temperature=.7,
48
+ model='gpt-4',
49
+ )
50
+
51
+
52
+ # SYSTEM ACTORS
53
+ class SystemActor(BaseModel):
54
+ actor: str = Field(description="name of the system actor")
55
+ desc: str = Field(description="role description of the system actor")
56
+ class SystemActors(BaseModel):
57
+ actors: List[SystemActor]
58
+
59
+ parser_actors = PydanticOutputParser(pydantic_object=SystemActors)
60
+
61
+
62
+
63
+ # ACTOR EPICS
64
+ class SystemEPIC(BaseModel):
65
+ epic: str = Field(description="system epic for the given actor")
66
+ features: List
67
+ class SystemEPICs(BaseModel):
68
+ epics: List[SystemEPIC]
69
+
70
+ parser_epics = PydanticOutputParser(pydantic_object=SystemEPICs)
71
+
72
+
73
+ class Entities(BaseModel):
74
+ entities: List[str] = Field(description="the entity name.")
75
+ entities_schema = PydanticOutputParser(pydantic_object=Entities)
76
+
77
+
78
+ class Attrib(BaseModel):
79
+ system_attrib_id: str = Field(description="the id of the system data model followed by the this property id (e.g., 54-3)")
80
+ system_attrib_name: str = Field(description="this property name.")
81
+ system_attrib_datatype: str = Field(description="this property datatype. It must only be among these values: text, number, date)")
82
+
83
+ class DataModel(BaseModel):
84
+ data_model_id: int = Field(description="an id of the corresponding data model (patient, room, booking, etc.)")
85
+ data_model_name: str = Field(description="the name of the system data model")
86
+ user_story_card_ids: List[int] = Field(description="a list of related user story card ids. Should be an empty list.")
87
+ data_model_attribs: List[Attrib]
88
+
89
+ parser_schema = PydanticOutputParser(pydantic_object=DataModel)
90
+
91
+
92
+
93
+ class Attrib(BaseModel):
94
+ system_attrib_id: str = Field(description="the id of the system data model followed by the this property id (e.g., 54-3)")
95
+ system_attrib_name: str = Field(description="this property name.")
96
+ system_attrib_datatype: str = Field(description="this property datatype. It must only be among these values: text, number, date.")
97
+
98
+ class DataModel(BaseModel):
99
+ data_model_id: int = Field(description="an id of the corresponding data model (patient, room, booking, etc.)")
100
+ data_model_name: str = Field(description="the name of the system data model")
101
+ user_story_card_ids: List[int] = Field(description="a list of related user story card ids. Should be an empty list.")
102
+ data_model_attribs: List[Attrib]
103
+
104
+ parser_schema = PydanticOutputParser(pydantic_object=DataModel)
105
+
106
+
107
+
108
+
109
+
110
+
111
+ class Message(BaseModel):
112
+ action_id: str = Field(description="Action unique ID")
113
+ action_case: str = Field(description="Explaination of the action case")
114
+ action_text: str = Field(description="The text body of the message to the user")
115
+ action_type: str = Field(description="Has to be one of the following: Email Message, SMS message, Alerting text") # Feature ID in data shema
116
+
117
+ class FlowStep(BaseModel):
118
+ step: int = Field(description="step number")
119
+ actor: str = Field(description="The actor performing the action e.g., User, System")
120
+ action: str = Field(description="The action description to be performed")
121
+
122
+ class DataField(BaseModel):
123
+ field_id: int = Field(description="the field id")
124
+ field_name: str = Field(description="the name of the field")
125
+ field_type: str = Field(description="the type of the field only from the following: text, number, date")
126
+ required: bool = Field(description="whether field is required or not")
127
+ default_value: str = Field(description="the default value of the field")
128
+
129
+ # STORY CARD
130
+ class StoryCard(BaseModel):
131
+ user_story_id: str = Field(description="Unique User Story ID") # Feature ID in data shema
132
+ user_story: str = Field(description="story title in the format of <as a user, I would be able to ..>")
133
+ affected_components: List[str] = Field(description="a list of affected components in the system by this features")
134
+ acceptance_criteria: List[str] = Field(description="a list of acceptance criteria")
135
+ preconditions: List[str] = Field(description="a list of preconditions with the corresponding acceptance criteria (if any)")
136
+ main_flow: List[FlowStep] = Field(description="Main Flow details the actions taken by the user and the system in a step-by-step manner. Make sure you differentiate the user and system steps.")
137
+ alternative_flow: List[FlowStep] = Field(description="Alternative Flow that covers the scenarios in which the main flow might fail the actions taken by the user and the system in a step-by-step manner. Make sure you differentiate the user and system steps.")
138
+ data_sections: List[DataField] = Field(description="A list contains Field Name, Field type, Required or not required or filed by the system and you can’t edit it, Default value, Note explains the filed input data type. You must use the provided schema to generate data section.")
139
+ messages: List[Message] = Field(description="A mandatory field that contains a list of system messages (both succesful and unsuccesfull flows) that result from the main flow.")
140
+ related_data_shema_ids: List[int] = Field(description="A list of IDs contains relevant Schema Entity IDs for each entity used in the story card, Only show the Entity IDs. Rely on the privded system schema only.")
141
+
142
+ parser_cards = PydanticOutputParser(pydantic_object=StoryCard)
143
+
144
+
145
+
146
+
147
+
148
+
149
+
150
+
151
+
152
+
153
+
154
+
155
+
156
+
157
+
158
+
159
+
160
+
161
+
162
+
163
+
164
+
165
+ def str_to_json(text):
166
+
167
+ updated_schemas = []
168
+
169
+ try:
170
+ print("GGGGGGGGGGGGG")
171
+ updated_schemas.append(parser_schema.parse(text).dict())
172
+ updated_schemas = check_schema(updated_schemas)
173
+ print("GGGGGGGGGGGGG")
174
+ except:
175
+
176
+ if '```' in text:
177
+
178
+ resp = text.split('```')[1] # Assume only one json object in the response
179
+
180
+ resp = resp.replace('json', ' ').strip() # Remove the word json that comes after ```
181
+
182
+
183
+ if resp[0] == '[' and resp[-1] == ']': # If it has brackets, i.e. multiple instances
184
+
185
+ for obj in literal_eval(resp): # For each instance
186
+
187
+ updated_schemas.append(eval(str(obj))) # Add schema to updated schemas
188
+
189
+ else: # If it does not have brackets, i.e. multiple instances
190
+
191
+ obj = literal_eval(resp)
192
+
193
+ updated_schemas.append(eval(str(obj))) # Add schema to updated schemas
194
+
195
+
196
+ updated_schemas = check_schema(updated_schemas)
197
+
198
+
199
+ else:
200
+ print('unable to parse...')
201
+
202
+ return updated_schemas
203
+
204
+
205
+
206
+ def update_data_schema(schemas, card, file_path):
207
+
208
+ for s in schemas:
209
+ print(f'processing {s["name"]}')
210
+ if s['schema']['data_model_id'] in card['related_data_shema_ids']:
211
+ if card['user_story_id'] not in s['schema']['user_story_card_ids']:
212
+ print(f"adding id to {s['name']}")
213
+ s['schema']['user_story_card_ids'].append(card['user_story_id'])
214
+
215
+ with open(file_path, 'w') as json_file:
216
+ json.dump(schemas, json_file)
217
+
218
+
219
+ def ensure_max_three_actors(actors_list):
220
+ print("hi inside three actor")
221
+ return actors_list[:3]
222
+
223
+
224
+
225
+ def ensure_max_three_entities(data):
226
+ if 'entities' in data:
227
+ data['entities'] = data['entities'][:3]
228
+ return data
229
+
230
+
231
+ def updating_cards(card, card_path, list_cards_path, list_of_cards=None):
232
+
233
+ if card is None:
234
+ print("card is non case")
235
+ with open(list_cards_path, 'w') as json_file:
236
+ json.dump(list_of_cards, json_file)
237
+
238
+ else:
239
+ print(card, card_path, list_cards_path, list_of_cards)
240
+
241
+ with open(card_path, 'w') as json_file:
242
+ json.dump(card, json_file)
243
+
244
+
245
+ if os.path.exists(list_cards_path):
246
+
247
+ with open(list_cards_path, 'r') as json_file:
248
+ list_cards = json.load(json_file)
249
+ list_cards.append(card)
250
+
251
+ with open(list_cards_path, 'w') as json_file:
252
+ json.dump(list_cards, json_file)
253
+
254
+ else:
255
+ with open(list_cards_path, 'w') as json_file:
256
+ json.dump([card], json_file)
257
+
258
+
259
+
260
+
261
+ def check_schema(updated_schemas):
262
+
263
+
264
+
265
+ if type(updated_schemas)==dict:
266
+
267
+ u_shem = {}
268
+
269
+ if 'name' not in updated_schemas.keys():
270
+
271
+ u_shem['name'] = updated_schemas['data_model_name']
272
+
273
+ u_shem['schema'] = copy.deepcopy(updated_schemas)
274
+
275
+ return u_shem
276
+
277
+ elif type(updated_schemas)==list:
278
+
279
+ u_shem = []
280
+
281
+ for updated_schema in updated_schemas:
282
+
283
+ temp_shem = {}
284
+
285
+ if 'name' not in updated_schema.keys():
286
+
287
+ temp_shem['name'] = updated_schema['data_model_name']
288
+
289
+ temp_shem['schema'] = copy.deepcopy(updated_schema)
290
+
291
+ u_shem.append(temp_shem)
292
+
293
+ else:
294
+ u_shem.append(updated_schema)
295
+
296
+
297
+ return u_shem
298
+
299
+
300
+
301
+
302
+
303
+ return updated_schemas
304
+
305
+ def logs(log,filePath):
306
+
307
+ if os.path.exists(filePath):
308
+ with open(filePath, 'r') as json_file:
309
+ logs = json.load(json_file)
310
+ logs.append(log)
311
+
312
+ with open(filePath, 'w') as json_file:
313
+ json.dump(logs, json_file)
314
+
315
+ else:
316
+ with open(filePath, 'w') as json_file:
317
+ json.dump([log], json_file)
318
+
319
+
320
+ def delete(json_file):
321
+ if os.path.exists(json_file):
322
+ os.remove(json_file)
323
+ print(f"The file {json_file} has been deleted.")
324
+ else:
325
+ print("The file does not exist.")
326
+
327
+
328
+ def check_None(the_list):
329
+ while None in the_list:
330
+ the_list.remove(None)
331
+ return the_list
332
+
333
+
334
+ def delete(json_file):
335
+ if os.path.exists(json_file):
336
+ os.remove(json_file)
337
+ print(f"The file {json_file} has been deleted.")
338
+ else:
339
+ print("The file does not exist.")
340
+
341
+ def is_all_english_alpha_numeric_or_space(text):
342
+ allowed_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 \".,:'!?+="
343
+ return all(char in allowed_chars for char in text)
344
+
345
+
346
+ def Validating_Input(text):
347
+ """
348
+ Check if the text contains "GPT" as a prefix in any substring, regardless of case.
349
+ Also, checks for the presence of "OpenAI" or "Open AI".
350
+
351
+ Parameters:
352
+ - text (str): The text to search within.
353
+
354
+ Returns:
355
+ - bool: True if the "GPT" or "OpenAI" conditions are met, False otherwise.
356
+ """
357
+
358
+ text_lower = text.lower()
359
+
360
+ print("HI FROM VALIDATING INPUT =========")
361
+ # Check if "GPT" is a prefix in any substring
362
+ if "gpt" in text_lower:
363
+ return True
364
+
365
+ # Check for the "OpenAI" condition
366
+ if "openai" in text_lower or "open ai" in text_lower:
367
+ return True
368
+
369
+ if "llm" in text_lower or "llms" in text_lower:
370
+ return True
371
+
372
+ print("HI FROM VALIDATING INPUT RETURNNING FALSE =========")
373
+ return False
374
+
375
+ def check_message(user_message):
376
+
377
+ llm=ChatOpenAI(
378
+ temperature=.7,
379
+ model='gpt-4',
380
+ )
381
+
382
+ prompt = check_message_template.format_prompt(
383
+ message=user_message,
384
+ )
385
+
386
+ response = llm(prompt.to_messages())
387
+
388
+
389
+ return response.content.lower()
390
+
391
+ def apologise(step):
392
+ if step ==0:
393
+ return "Your request is unclear. Please provide additional information or try using different terms.\n\n"
394
+ if step ==1:
395
+ return "Oops! Your input is a bit ambiguous. Can you please provide more clarity or details?\n\n"
396
+ if step ==2:
397
+ return "We're not sure what you meant by that. Could you rephrase or be more specific?\n\n"
398
+ if step ==3:
399
+ return "Sorry, we didn't quite get that. Can you clarify or provide more context?"
400
+
401
+ def apologise_lang(step):
402
+ if step ==0:
403
+ return "Apologies, but at this moment, we only support English for 'فزاع'. We appreciate your understanding.\n\n"
404
+ if step ==1:
405
+ return "Thank you for your interest in 'فزاع'. Currently, we are offering support exclusively in English.\n\n"
406
+ if step ==2:
407
+ return "Please note that 'فزاع' is presently supported in English only. We're working to expand our language offerings in the future.\n\n"
408
+ if step ==3:
409
+ return "We value our diverse user base, but as of now, our support for 'فزاع' is limited to English. Thanks for your patience.\n\n"
410
+
411
+
412
+ def first_prompt(system_name):
413
+ prompt = system_structure_template.format_prompt(
414
+ system_name= system_name,
415
+ format_instructions= parser_actors.get_format_instructions()
416
+ )
417
+
418
+ response = llm(prompt.to_messages())
419
+ return response
420
+
421
+
422
+ async def aget_epics(actor_obj, system_name):
423
+
424
+ print(f'processing actor {actor_obj["actor"]}')
425
+
426
+ prompt = system_epics_template.format_prompt(
427
+ system_name= system_name,
428
+ format_instructions= parser_epics.get_format_instructions(),
429
+ system_actor = actor_obj['actor'],
430
+ actor_description = actor_obj['desc']
431
+ )
432
+ response = await llm.apredict(prompt.to_string())
433
+ aepics = parser_epics.parse(response).dict()
434
+ aepics['system_name'] = system_name
435
+ aepics['system_actor'] = actor_obj['actor']
436
+ aepics['actor_description'] = actor_obj['desc']
437
+
438
+ return aepics
439
+
440
+
441
+ async def second_prompt(response, system_name):
442
+ actors = parser_actors.parse(response.content).dict()['actors']
443
+ actors=ensure_max_three_actors(actors)
444
+ epics = await asyncio.gather(*[aget_epics(actor,system_name) for actor in actors])
445
+
446
+ with open('epics_gradio.json', 'w') as json_file:
447
+ json.dump(epics, json_file)
448
+
449
+ return epics
450
+
451
+ def third_prompt(epics):
452
+ prompt = entities_template.format_prompt(
453
+ system_context = str(epics),
454
+ format_instructions= entities_schema.get_format_instructions(),
455
+ )
456
+
457
+ response = llm(prompt.to_messages())
458
+
459
+ entities = entities_schema.parse(response.content).dict()
460
+ entities = ensure_max_three_entities(entities)
461
+ with open('entities_gradio.json', 'w') as json_file:
462
+ json.dump(entities, json_file)
463
+
464
+
465
+ return entities['entities']
466
+
467
+
468
+
469
+
470
+ async def fetch_schemas(entity,epics ):
471
+ try:
472
+ print(f" Generating {entity}")
473
+ prompt = schema_template.format_prompt(
474
+ system_entity= entity,
475
+ system_context = str(epics),
476
+ format_instructions= parser_schema.get_format_instructions(),
477
+ )
478
+ response = await llm.apredict_messages(messages=prompt.to_messages())
479
+ schema = parser_schema.parse(response.content).dict()
480
+
481
+
482
+ return check_schema(schema)
483
+ except Exception as e:
484
+ print(f"Error processing"+str(e))
485
+ return None
486
+
487
+
488
+ async def fourth_prompt(entities,epics):
489
+
490
+ all_schemas = []
491
+
492
+ all_schemas = await asyncio.gather(*[fetch_schemas(entity,epics) for entity in entities])
493
+
494
+ # all_schemas = check_None(all_schemas)
495
+
496
+ for ind,s in enumerate(all_schemas):
497
+ s['schema']['data_model_id'] = (ind+1)
498
+
499
+ with open('schemas_gradio.json', 'w') as json_file:
500
+ json.dump(all_schemas, json_file)
501
+
502
+ logs(all_schemas,'schemas_logs.json')
503
+
504
+ return all_schemas
505
+
506
+
507
+
508
+ def json_to_markdown_table(data):
509
+ md_table = "| System Name | System Actor | Actor Description | Epic | Features |\n"
510
+ md_table += "|------------|--------------|--------------------|------|----------|\n"
511
+
512
+ for entry in data:
513
+ system_name = entry['system_name']
514
+ system_actor = entry['system_actor']
515
+ actor_description = entry['actor_description']
516
+
517
+ for epic in entry['epics']:
518
+ epic_name = epic['epic']
519
+ features = ', '.join(epic['features'])
520
+ md_table += f"| {system_name} | {system_actor} | {actor_description} | {epic_name} | {features} |\n"
521
+
522
+ return md_table
523
+
524
+ def markdown(file_name):
525
+ with open(file_name, 'r') as json_file:
526
+ json_data = json.load(json_file)
527
+
528
+ return json_to_markdown_table(json_data)
529
+
530
+
531
+ def create_user_story(first = False):
532
+ if not first:
533
+ return "\n\n\n Please write a short description for a new user story card\n\n\n"
534
+ return "\n\n\n Please write a short description for a user story card\n\n\n"
535
+
536
+
537
+ def affected_parts(user_request):
538
+
539
+ with open('schemas_gradio.json', 'r') as json_file:
540
+ schemas = json.load(json_file)
541
+
542
+ with open('epics_gradio.json', 'r') as json_file:
543
+ epics = json.load(json_file)
544
+
545
+
546
+ prompt = update_schema_template.format_prompt(
547
+ schema= str(schemas),
548
+ system_context = str(epics),
549
+ new_usecase = user_request,
550
+ format_instructions= parser_schema.get_format_instructions(),
551
+ )
552
+ response = llm(prompt.to_messages())
553
+
554
+ updated_schemas = str_to_json(response.content)
555
+
556
+ unlucky = []
557
+
558
+ updated_schemas = check_schema(updated_schemas)
559
+
560
+ for u in updated_schemas:
561
+
562
+ check_var = True
563
+
564
+ for s in schemas:
565
+ print(s,u)
566
+ if s['name'] == u['name']:
567
+ s['schema'] = u['schema']
568
+ check_var = False
569
+
570
+ if check_var:
571
+ unlucky.append(u)
572
+
573
+
574
+ for u in unlucky:
575
+ schemas.append(u)
576
+
577
+
578
+
579
+ with open('schemas_updated_part_gradio.json', 'w') as json_file:
580
+ json.dump(updated_schemas, json_file)
581
+
582
+ logs(updated_schemas,"schemas_updated_part_logs.json")
583
+
584
+ with open('schemas_gradio.json', 'w') as json_file:
585
+ json.dump(schemas, json_file)
586
+
587
+ logs(schemas,'schemas_logs.json')
588
+
589
+
590
+ def generate_story_cards(user_request):
591
+ with open('schemas_gradio.json', 'r') as json_file:
592
+ schemas = json.load(json_file)
593
+
594
+ with open('epics_gradio.json', 'r') as json_file:
595
+ epics = json.load(json_file)
596
+
597
+ prompt = story_cards_template.format_prompt(
598
+ format_instructions= parser_cards.get_format_instructions(),
599
+ schema = str(schemas),
600
+ system_epic = str(epics),
601
+ epic_feature = user_request # use the same as above
602
+ )
603
+ response = llm(prompt.to_messages())
604
+
605
+ card = parser_cards.parse(response.content).dict()
606
+
607
+ updating_cards(card, 'card_gradio.json', 'cards_gradio.json')
608
+
609
+ logs(card,'cards_logs.json')
610
+
611
+ update_data_schema(schemas, card, 'schemas_gradio.json')
612
+
613
+ logs(schemas,'schemas_logs.json')
614
+
615
+
616
+ return card
617
+
618
+
619
+ def check_affected_story_ids(schemas_affected_part_path = 'schemas_updated_part_gradio.json'):
620
+
621
+ with open(schemas_affected_part_path, 'r') as json_file:
622
+ schemas_affected_part = json.load(json_file)
623
+
624
+
625
+ story_ids = []
626
+
627
+ for item in schemas_affected_part:
628
+ for userStory_id in item['schema']['user_story_card_ids']:
629
+ if userStory_id not in story_ids:
630
+ story_ids.append(userStory_id)
631
+
632
+ logs(json.dumps([{'Story_ids': story_ids}]).replace('\"',''),"Story_ids_logs.json")
633
+
634
+ return story_ids
635
+
636
+
637
+ async def fetch_cards(cards, card, schemas, ix, story_ids):
638
+ print(f"Card details {card}")
639
+
640
+ try:
641
+ if card['user_story_id'] not in story_ids:
642
+ print(f'skipping ..')
643
+ return
644
+ prompt = update_story_cards_template.format_prompt(
645
+ format_instructions= parser_cards.get_format_instructions(),
646
+ schema = str(schemas),
647
+ story_card = str(card),
648
+ )
649
+ response = await llm.apredict_messages(messages=prompt.to_messages())
650
+ try:
651
+ new_card = parser_cards.parse(response.content).dict()
652
+ except Exception as e:
653
+ print(e)
654
+ new_card = json.loads(response.content)
655
+ print(new_card)
656
+
657
+ # override old card
658
+ cards[ix] = new_card
659
+
660
+
661
+ print("Affected User Story: \n\n", new_card)
662
+
663
+ return new_card
664
+ except Exception as e:
665
+ print(f"Error processing"+str(e))
666
+ return None
667
+
668
+ async def update_affected_story_cards(story_ids):
669
+
670
+ with open('schemas_gradio.json', 'r') as json_file:
671
+ schemas = json.load(json_file)
672
+
673
+ with open('cards_gradio.json', 'r') as json_file:
674
+ cards = json.load(json_file)
675
+
676
+ updated_cards = []
677
+
678
+ updated_cards = await asyncio.gather(*[fetch_cards(cards, card, schemas, ix, story_ids) for ix, card in enumerate(cards)])
679
+
680
+ updated_cards = check_None(updated_cards)
681
+
682
+ logs(cards,'affected_Cards_logs.json')
683
+ updating_cards(card = None, card_path = None, list_cards_path = 'cards.json', list_of_cards=cards)
684
+ return updated_cards
685
+
686
+
687
+
688
+ def user_story_to_markdown(story):
689
+ markdown = ""
690
+
691
+ # Title and ID
692
+ markdown += f"## User Story {story['user_story_id']}\n\n"
693
+
694
+ # Table headers and data
695
+ markdown += "| Attribute | Information |\n"
696
+ markdown += "| --------- | ----------- |\n"
697
+ markdown += f"| User Story | {story['user_story']} |\n"
698
+ markdown += f"| Affected Components | {', '.join(story['affected_components'])} |\n"
699
+ markdown += f"| Acceptance Criteria | {'<br>'.join(story['acceptance_criteria'])} |\n"
700
+ markdown += f"| Preconditions | {'<br>'.join(story['preconditions'])} |\n"
701
+
702
+ main_flow = '<br>'.join([f"{step['step']}. **{step['actor']}** - {step['action']}" for step in story['main_flow']])
703
+ markdown += f"| Main Flow | {main_flow} |\n"
704
+
705
+ alt_flow = '<br>'.join([f"{step['step']}. **{step['actor']}** - {step['action']}" for step in story['alternative_flow']])
706
+ markdown += f"| Alternative Flow | {alt_flow} |\n"
707
+
708
+ data_sections = '<br>'.join([f"**{section['field_name']}** (Type: {section['field_type']}, Required: {'Yes' if section['required'] else 'No'}, Default: {section['default_value']})" for section in story['data_sections']])
709
+ markdown += f"| Data Sections | {data_sections} |\n"
710
+
711
+ messages = '<br>'.join([f"**{msg['action_case']}** - {msg['action_text']} ({msg['action_type']})" for msg in story['messages']])
712
+ markdown += f"| Messages | {messages} |\n"
713
+
714
+ markdown += f"| Related Data Schema IDs | {', '.join(map(str, story['related_data_shema_ids']))} |\n"
715
+
716
+ return markdown
717
+
718
+
719
+ def choose():
720
+ return "\n\n\n\nPlease Choose one of the following options:\n\n 1- Adding user story to your existing system.\n\n 2- Update existing user story.\n\n\n"
721
+
722
+
723
+
724
+ for file in os.listdir():
725
+ if file.endswith('_gradio.json'):
726
+ delete(file)
727
+
728
+
729
+
prompts.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from langchain.prompts import ChatPromptTemplate
2
+
3
+ SYS_STRUCT = '''You are a software requirements engineer with years of experience working at a big tech company.
4
+ Your aim is to craft a well-written and clear software requirements documentation for the provided systems and use cases.
5
+
6
+ '''
7
+ # and respond only in Arabic
8
+
9
+ HUMAN_STRUCT = '''Can you generate the following component for a {system_name}.
10
+ - System actors
11
+
12
+ # FORAMT INSTRUCTIONS
13
+ {format_instructions}'''
14
+
15
+
16
+ # - System epics for each Actor
17
+ # - System feature for each epic
18
+
19
+ system_structure_template = ChatPromptTemplate.from_messages([
20
+ ("system", SYS_STRUCT),
21
+ ("human", HUMAN_STRUCT),
22
+ ])
23
+
24
+
25
+ SYS_EPICS = '''You are a software requirements engineer with years of experience working at a big tech company.
26
+ Your aim is to craft a well-written and clear software requirements documentation for the provided systems and use cases.
27
+ '''
28
+
29
+ HUMAN_EPICS = '''Generate the system epics and features for the following actor make sure you create the core needed actors only.
30
+ System Name: {system_name}
31
+ System Actor: {system_actor}
32
+ Actor Description: {actor_description}
33
+
34
+ # FORAMT INSTRUCTIONS
35
+ {format_instructions}
36
+ '''
37
+
38
+ system_epics_template = ChatPromptTemplate.from_messages([
39
+ ("system", SYS_EPICS),
40
+ ("human", HUMAN_EPICS),
41
+ ])
42
+
43
+
44
+ SYS_CARDS = '''You are a software requirements engineer with years of experience working at a big tech company.
45
+ Your aim in this exciting project is to craft a well-written and clear software requirements document. You must be very detailed and thorough.
46
+ '''
47
+
48
+ HUMAN_CARDS = '''Generate a detailed user story card for the following context. You must pay a close attention to the data available in the Schema section.
49
+
50
+ # General Instructions:
51
+ - If you used an email notification make sure you mention the email in the message.
52
+
53
+ # Schema:
54
+ {schema}
55
+
56
+ # System Epic:
57
+ {system_epic}
58
+
59
+ # Epic Feature:
60
+ {epic_feature}
61
+
62
+ # FORAMT INSTRUCTIONS
63
+ {format_instructions}
64
+
65
+ Take a deep breath and begin!
66
+ '''
67
+
68
+ story_cards_template = ChatPromptTemplate.from_messages([
69
+ ("system", SYS_CARDS),
70
+ ("human", HUMAN_CARDS),
71
+ ])
72
+
73
+
74
+ # =======================================================================================================================================
75
+ # Generateing Entities prompt
76
+ # =======================================================================================================================================
77
+
78
+ SYS_ENTITIES = '''Please provide up to four crucial actors and entities for the given system's high-level data models. Exclude any configuration-related entities.
79
+ '''
80
+
81
+ HUMAN_ENTITIES = '''Generate the high-level data models (4 maximum) of the given system (i.e., actors and entities).
82
+ Make sure you only mention the most important ones.
83
+ Avoid mentioning the config related entities.
84
+ Be very concise you have to sort it from the most important one to the least important.
85
+
86
+ # System Context:
87
+ {system_context}
88
+
89
+ # FORAMT INSTRUCTIONS
90
+ {format_instructions}
91
+ '''
92
+
93
+ entities_template = ChatPromptTemplate.from_messages([
94
+ ("system", SYS_ENTITIES),
95
+ ("human", HUMAN_ENTITIES),
96
+ ])
97
+
98
+ # =======================================================================================================================================
99
+ # End of Entities prompt
100
+ # =======================================================================================================================================
101
+
102
+
103
+
104
+
105
+
106
+
107
+ SYS_CARDS = '''You are a software requirements engineer with years of experience working at a big tech company.
108
+ Your aim in this exciting project is to craft a well-written and clear software requirements document. You must be very detailed and thorough.
109
+ '''
110
+
111
+ HUMAN_CARDS = '''Generate a detailed data model card given the provided entity and context. Use spaces instead of dashes on the attribute name.
112
+ Please rely on the system context (provided in a json format) to derive the data and attributes.
113
+ You will also return the result in a JSON format explained below.
114
+
115
+ # Examples of properties:
116
+ Example properties for a system actor:
117
+ First Name, Last Name, Date of Birth, [.. continue as you see fit from the context]
118
+ Example properties for a physical entity (i.e., room) properties:
119
+ Width, Location, [.. continue as you see fit from the context]
120
+
121
+
122
+ # System Information
123
+ - System Entity: {system_entity}
124
+ - System Context in a JSON format:
125
+ {system_context}
126
+
127
+ # FORAMT INSTRUCTIONS
128
+ {format_instructions}
129
+ '''
130
+
131
+ schema_template = ChatPromptTemplate.from_messages([
132
+ ("system", SYS_CARDS),
133
+ ("human", HUMAN_CARDS),
134
+ ])
135
+
136
+
137
+ SYS_CARDS = '''You are a software requirements engineer with years of experience working at a big tech company.
138
+ Your aim in this exciting project is to craft a well-written and clear software requirements document. You must be very detailed and thorough.
139
+ '''
140
+
141
+ HUMAN_CARDS = '''The user has new feature request. Given the old data schema shown below, edit it and print out the updated data schema (which may contain either modified fields or entirly new fields). Be conservative.
142
+ Please rely on the system context (provided in a json format).
143
+ You will also return the result in a JSON format explained below.
144
+ You must follow the format instructions very closely.
145
+
146
+ # Schema:
147
+ {schema}
148
+
149
+ # System Context:
150
+ {system_context}
151
+
152
+ # New Use Case:
153
+ {new_usecase}
154
+
155
+ # FORAMT INSTRUCTIONS
156
+ {format_instructions}
157
+
158
+ Be very conservative and only edit existing schema if necessary.
159
+ Only return the entity object containing the modifications or updates, not the entire schema.
160
+ '''
161
+
162
+ update_schema_template = ChatPromptTemplate.from_messages([
163
+ ("system", SYS_CARDS),
164
+ ("human", HUMAN_CARDS),
165
+ ])
166
+
167
+
168
+ SYS_CARDS = '''You are a software requirements engineer with years of experience working at a big tech company.
169
+ Your aim in this exciting project is to craft a well-written and clear software requirements document. You must be very detailed and thorough.
170
+ '''
171
+
172
+ HUMAN_CARDS = '''Generate an updated user story card provided the new schema shown below. You must pay a close attention to the data available in the Schema section.
173
+ Be very concise to show all the editable or viewable data available in the data Schema in the data section within the user story card.
174
+ # Story Card:
175
+ {story_card}
176
+
177
+ # Updated Schema:
178
+ {schema}
179
+
180
+ # FORAMT INSTRUCTIONS
181
+ {format_instructions}
182
+
183
+ Take a deep breath and begin!
184
+ '''
185
+
186
+ update_story_cards_template = ChatPromptTemplate.from_messages([
187
+ ("system", SYS_CARDS),
188
+ ("human", HUMAN_CARDS),
189
+ ])
190
+
191
+
192
+ # Build a data schema for the given system context shown previously, with the following sections
193
+
194
+ # Each object will hold the following information
195
+
196
+ # Object Name
197
+ # Object Unique ID numbers only
198
+
199
+ # Each Object will hold as many Attribute as needed with the following information
200
+
201
+ # Attribute Unique ID (Start with Object Unique ID then dashed Attribute ID)
202
+ # Attribute name only in Arabic.
203
+ # Attribute Data type with the following option (Number or text or date or number and text ) only in Arabic.
204
+
205
+ # Make sure you build an Object for each actor mentioned previously
206
+ # You can use spaces instead of dashes on the attribute name
207
+
208
+ # Show the data on the markdown table
209
+
210
+ # Don’t mention the key type
211
+
212
+ SYS_STRUCT = '''Please answer with yes or no.
213
+
214
+ Is the following message a possible {var}, if it is answer with yes please.
215
+
216
+ Yet if it is a part of a chat like 'hello', 'thank you' or other non-possible system name please respond with no.
217
+ '''
218
+ # and respond only in Arabic
219
+
220
+ HUMAN_STRUCT = '''{message}'''
221
+
222
+
223
+ # - System epics for each Actor
224
+ # - System feature for each epic
225
+
226
+ check_message_template = ChatPromptTemplate.from_messages([
227
+ ("system", SYS_STRUCT),
228
+ ("human", HUMAN_STRUCT),
229
+ ])
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio==3.44.4
2
+ langchain==0.0.300
3
+ openai==0.28.0
4
+ prompts==0.0.1
5
+ pydantic==1.10.8