AlaouiMdaghriAhmed commited on
Commit
b3d3bec
·
1 Parent(s): 34fd237
README.md CHANGED
@@ -1,12 +1,53 @@
1
- ---
2
- title: Ecore Gen
3
- emoji: 👁
4
- colorFrom: pink
5
- colorTo: purple
6
- sdk: gradio
7
- sdk_version: 4.36.1
8
- app_file: app.py
9
- pinned: false
10
- ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Gradio App for Generating and Validating Ecore Files
2
+ This repository contains a Gradio-based web application that leverages open-source language models from HuggingChat API and OpenAI API. The app provides two tabs: one for using models from HuggingChat and the other for models from OpenAI. Both tabs allow users to generate an Ecore file from a natural language description and iteratively validate it.
3
+
4
+ ## Features
5
+ - Two Tabs for Model Selection:
6
+ - HuggingChat API: Uses open-source language models from HuggingChat.
7
+ - OpenAI API: Uses language models from OpenAI.
8
+ - Ecore File Generation: Converts natural language descriptions into Ecore files.
9
+ - Iterative Validation: Validates the generated Ecore files iteratively to ensure correctness.
10
+ ## Installation
11
+ 1. Clone the repository:
12
+
13
+ ```bash
14
+ git clone https://github.com/your-username/your-repo-name.git
15
+ cd your-repo-name
16
+ ```
17
+ 2. Install the required packages:
18
+
19
+ ```bash
20
+ pip install -r requirements.txt
21
+ ```
22
+ ## Usage
23
+
24
+ 1. Navigate to the project directory:
25
+
26
+ ```bash
27
+ cd your-repo-name
28
+ ```
29
+ 2. Run the application:
30
+
31
+ ```bash
32
+ python app.py
33
+ ```
34
+ 3. Open your web browser and go to the provided local address to interact with the app.
35
+
36
+ ## Folder Structure
37
+ - app.py: Main script to run the Gradio app.
38
+ - requirements.txt: List of required Python packages.
39
+ - README.md: Project documentation.
40
+
41
+ ## Contributing
42
+ Contributions are welcome! Please create a new branch for each feature or bug fix:
43
+
44
+ ```bash
45
+ git checkout -b feature/your-feature-name
46
+ ```
47
+ Submit a pull request with a detailed explanation of your changes.
48
+
49
+
50
+
51
+ ## Contact
52
+ For any questions or feedback, please open an issue or contact [[email protected]].
53
+
__pycache__/openai.cpython-39.pyc ADDED
Binary file (140 Bytes). View file
 
__pycache__/opp.cpython-39.pyc ADDED
Binary file (137 Bytes). View file
 
__pycache__/verify.cpython-39.pyc ADDED
Binary file (10.4 kB). View file
 
app.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from hugchat import hugchat
2
+ from hugchat.login import Login
3
+ from pyecore.resources import ResourceSet, URI
4
+ import gradio as gr
5
+ import logging
6
+ from pathlib import Path
7
+ from typing import List, Optional, Tuple
8
+
9
+ from dotenv import load_dotenv
10
+
11
+ load_dotenv()
12
+
13
+ import verify
14
+
15
+ from queue import Empty, Queue
16
+ from threading import Thread
17
+
18
+ import gradio as gr
19
+ from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
20
+ from langchain_community.chat_models import ChatOpenAI
21
+ from langchain.prompts import HumanMessagePromptTemplate
22
+ from langchain.schema import AIMessage, BaseMessage, HumanMessage, SystemMessage
23
+ # adapted from https://github.com/hwchase17/langchain/issues/2428#issuecomment-1512280045
24
+ from queue import Queue
25
+ from typing import Any
26
+
27
+ from langchain.callbacks.base import BaseCallbackHandler
28
+ from datasets import load_dataset
29
+
30
+ dataset = load_dataset("VeryMadSoul/NLD")
31
+
32
+
33
+ class QueueCallback(BaseCallbackHandler):
34
+ """Callback handler for streaming LLM responses to a queue."""
35
+
36
+ def __init__(self, queue: Queue):
37
+ self.queue = queue
38
+
39
+ def on_llm_new_token(self, token: str, **kwargs: Any) -> None:
40
+ self.queue.put(token)
41
+
42
+ def on_llm_end(self, *args, **kwargs: Any) -> None:
43
+ return self.queue.empty()
44
+
45
+ def apply_hf_settings_button(prompt, model_name) :
46
+ verify.chatbot.switch_llm(HF_MODELS_NAMES.index(model_name))
47
+ verify.chatbot.new_conversation(switch_to = True)
48
+ return "",[]
49
+
50
+ HF_MODELS_NAMES = [model.name for model in verify.chatbot.get_available_llm_models()]
51
+
52
+
53
+ DEFAULT_TEMPERATURE = 0.2
54
+
55
+ ChatHistory = List[str]
56
+
57
+ logging.basicConfig(
58
+ format="[%(asctime)s %(levelname)s]: %(message)s", level=logging.INFO
59
+ )
60
+ # load up our system prompt
61
+ default_system_prompt = '''You are a systems engineer, expert in model driven engineering and meta-modeling
62
+ Your OUTPUT should always be an ecore xmi in this format :
63
+
64
+ ```XML
65
+
66
+ YOUR CODE HERE
67
+
68
+ ```
69
+ '''
70
+ # for the human, we will just inject the text
71
+ human_message_prompt_template = HumanMessagePromptTemplate.from_template("{text}")
72
+
73
+
74
+ def on_message_button_click(
75
+ chat: Optional[ChatOpenAI],
76
+ message: str,
77
+ chatbot_messages: ChatHistory,
78
+ messages: List[BaseMessage],
79
+ ) -> Tuple[ChatOpenAI, str, ChatHistory, List[BaseMessage]]:
80
+ if chat is None:
81
+ # in the queue we will store our streamed tokens
82
+ queue = Queue()
83
+ # let's create our default chat
84
+ chat = ChatOpenAI(
85
+ model_name=GPT_MODELS_NAMES[0],
86
+ temperature=DEFAULT_TEMPERATURE,
87
+ streaming=True,
88
+ callbacks=([QueueCallback(queue)]),
89
+ )
90
+ else:
91
+ # hacky way to get the queue back
92
+ queue = chat.callbacks[0].queue
93
+
94
+ job_done = object()
95
+
96
+ logging.info(f"Asking question to GPT, messages={messages}")
97
+ # let's add the messages to our stuff
98
+ messages.append(HumanMessage(content=message))
99
+ chatbot_messages.append((message, ""))
100
+ # this is a little wrapper we need cuz we have to add the job_done
101
+ def task():
102
+ chat(messages)
103
+ queue.put(job_done)
104
+
105
+ # now let's start a thread and run the generation inside it
106
+ t = Thread(target=task)
107
+ t.start()
108
+ # this will hold the content as we generate
109
+ content = ""
110
+ # now, we read the next_token from queue and do what it has to be done
111
+ while True:
112
+ try:
113
+ next_token = queue.get(True, timeout=1)
114
+ if next_token is job_done:
115
+ break
116
+ content += next_token
117
+ chatbot_messages[-1] = (message, content)
118
+ yield chat, "", chatbot_messages, messages
119
+ except Empty:
120
+ continue
121
+ # finally we can add our reply to messsages
122
+ messages.append(AIMessage(content=content))
123
+ logging.debug(f"reply = {content}")
124
+ logging.info(f"Done!")
125
+ return chat, "", chatbot_messages, messages
126
+
127
+
128
+ def system_prompt_handler(value: str) -> str:
129
+ return value
130
+
131
+
132
+ def on_clear_button_click(system_prompt: str) -> Tuple[str, List, List]:
133
+ return "", [], [SystemMessage(content=system_prompt)]
134
+
135
+
136
+ def on_apply_settings_button_click(
137
+ system_prompt: str, model_name: str, temperature: float
138
+ ):
139
+ logging.info(
140
+ f"Applying settings: model_name={model_name}, temperature={temperature}"
141
+ )
142
+ chat = ChatOpenAI(
143
+ model_name=model_name,
144
+ temperature=temperature,
145
+ streaming=True,
146
+ callbacks=[QueueCallback(Queue())],
147
+ )
148
+ # don't forget to nuke our queue
149
+ chat.callbacks[0].queue.empty()
150
+ return chat, *on_clear_button_click(system_prompt)
151
+
152
+
153
+
154
+
155
+
156
+ def trigger_example(example):
157
+ chat, updated_history = generate_response(example)
158
+ return chat, updated_history
159
+
160
+ def generate_response(user_message, history):
161
+
162
+ #history.append((user_message,str(chatbot.chat(user_message))))
163
+ history, errors = verify.iterative_prompting(user_message,verify.description)
164
+ return "", history
165
+
166
+ def clear_chat():
167
+ return [], []
168
+
169
+ examples = [dataset['train'][i]['NLD'] for i in range(len(dataset['train']))]
170
+
171
+ custom_css = """
172
+ #logo-img {
173
+ border: none !important;
174
+ }
175
+ #chat-message {
176
+ font-size: 14px;
177
+ min-height: 300px;
178
+ }
179
+ """
180
+ GPT_MODELS_NAMES = ["gpt-3.5-turbo", "gpt-4",'gpt-4o']
181
+
182
+ with gr.Blocks(analytics_enabled=False, css=custom_css) as demo:
183
+
184
+
185
+ with gr.Tab("HF_API"):
186
+ with gr.Row():
187
+ with gr.Column(scale=1):
188
+ gr.Image("images\logo.png", elem_id="logo-img", show_label=False, show_share_button=False, show_download_button=False)
189
+ with gr.Column(scale=3):
190
+ gr.Markdown("""This Chatbot has been made to showcase our work on generating meta-model from textual descriptions.
191
+ <br/><br/>
192
+ The output of this conversation is going to be an ecore file that is validated by PyEcore [Pyecore (https://github.com/pyecore/pyecore)]
193
+ <br/>
194
+ Available Models : <br>
195
+ - Cohere4ai-command-r-plus<br>
196
+ - Llama-3-70B<br>
197
+
198
+ """
199
+ )
200
+
201
+ with gr.Row():
202
+ chatbot1 = gr.Chatbot(show_label=False, show_share_button=False, show_copy_button=True)
203
+
204
+ with gr.Row():
205
+ user_message = gr.Textbox(lines=1, placeholder="Ask anything ...", label="Input", show_label=False)
206
+
207
+
208
+ with gr.Row():
209
+ submit_button = gr.Button("Submit")
210
+ clear_button = gr.Button("Clear chat")
211
+
212
+
213
+
214
+
215
+ history = gr.State([])
216
+
217
+ user_message.submit(fn=generate_response, inputs=[user_message, chatbot1], outputs=[user_message, chatbot1], concurrency_limit=32)
218
+ submit_button.click(fn=generate_response, inputs=[user_message, chatbot1], outputs=[user_message, chatbot1], concurrency_limit=32)
219
+
220
+ clear_button.click(fn=clear_chat, inputs=None, outputs=[chatbot1, history], concurrency_limit=32)
221
+
222
+ with gr.Accordion("Settings", open=False):
223
+ model_name = gr.Dropdown(
224
+ choices=HF_MODELS_NAMES, value=HF_MODELS_NAMES[0], label="model"
225
+ )
226
+ settings_button = gr.Button("Apply")
227
+ settings_button.click(
228
+ apply_hf_settings_button,
229
+ [user_message,model_name],
230
+ [user_message, chatbot1],
231
+ )
232
+
233
+
234
+
235
+ with gr.Row():
236
+ gr.Examples(
237
+ examples=examples,
238
+ inputs=user_message,
239
+ cache_examples=False,
240
+ fn=trigger_example,
241
+ outputs=[chatbot],
242
+ examples_per_page=100
243
+ )
244
+ #user_message.submit(lambda x: gr.update(value=""), None, [user_message], queue=False)
245
+ #submit_button.click(lambda x: gr.update(value=""), None, [user_message], queue=False)
246
+ #clear_button.click(lambda x: gr.update(value=""), None, [user_message], queue=False)
247
+
248
+
249
+ with gr.Tab("OPENAI"):
250
+ system_prompt = gr.State(default_system_prompt)
251
+ # here we keep our state so multiple user can use the app at the same time!
252
+ messages = gr.State([SystemMessage(content=default_system_prompt)])
253
+ # same thing for the chat, we want one chat per use so callbacks are unique I guess
254
+ chat = gr.State(None)
255
+
256
+ with gr.Column(elem_id="col_container"):
257
+ with gr.Row():
258
+ with gr.Column(scale=1):
259
+ gr.Image("images\logo.png", elem_id="logo-img", show_label=False, show_share_button=False, show_download_button=False)
260
+ with gr.Column(scale=3):
261
+ gr.Markdown("""This Chatbot has been made to showcase our work on generating meta-model from textual descriptions.
262
+ <br/><br/>
263
+ The output of this conversation is going to be an ecore file that is validated by PyEcore [Pyecore (https://github.com/pyecore/pyecore)]
264
+ <br/>
265
+ Available Models : <br>
266
+ - GPT3-Turbo<br>
267
+ - GPT4-Turbo<br>
268
+ - GPT4-Omni
269
+
270
+ """
271
+ )
272
+
273
+
274
+ chatbot1 = gr.Chatbot()
275
+ with gr.Column():
276
+ message = gr.Textbox(label="chat input")
277
+ message.submit(
278
+ on_message_button_click,
279
+ [chat, message, chatbot1, messages],
280
+ [chat, message, chatbot1, messages],
281
+ queue=True,
282
+ )
283
+ message_button = gr.Button("Submit", variant="primary")
284
+ message_button.click(
285
+ on_message_button_click,
286
+ [chat, message, chatbot1, messages],
287
+ [chat, message, chatbot1, messages],
288
+ )
289
+ with gr.Row():
290
+ with gr.Column():
291
+ clear_button = gr.Button("Clear")
292
+ clear_button.click(
293
+ on_clear_button_click,
294
+ [system_prompt],
295
+ [message, chatbot1, messages],
296
+ queue=False,
297
+ )
298
+ with gr.Accordion("Settings", open=False):
299
+ model_name = gr.Dropdown(
300
+ choices=GPT_MODELS_NAMES, value=GPT_MODELS_NAMES[0], label="model"
301
+ )
302
+ temperature = gr.Slider(
303
+ minimum=0.0,
304
+ maximum=1.0,
305
+ value=0.7,
306
+ step=0.1,
307
+ label="temperature",
308
+ interactive=True,
309
+ )
310
+ apply_settings_button = gr.Button("Apply")
311
+ apply_settings_button.click(
312
+ on_apply_settings_button_click,
313
+ [system_prompt, model_name, temperature],
314
+ [chat, message, chatbot1, messages],
315
+ )
316
+ with gr.Row():
317
+ gr.Examples(
318
+ examples=examples,
319
+ inputs=message,
320
+ cache_examples=False,
321
+ fn=on_message_button_click,
322
+ outputs=[chat, message, chatbot1, messages],
323
+ examples_per_page=100
324
+ )
325
+
326
+
327
+ if __name__ == "__main__":
328
+ # demo.launch(debug=True)
329
+ try:
330
+ demo.queue(api_open=False, max_size=40).launch(show_api=False)
331
+ except Exception as e:
332
+ print(f"Error: {e}")
cookies/[email protected] ADDED
@@ -0,0 +1 @@
 
 
1
+ {"hf-chat": "c50ecd5a-49c6-4476-bbf6-79889e915ceb", "token": "QRBRiJammSDwTGqibPwKOClSgxOJnjubtRtrwjfAfWJxBGNNIKhitDezddYOGTClZSYoqsKSNbLAaLvsJuePsicMWYDRkFwkoiALdDWyWyPDiYiaeLgJlTkHCYVMpich"}
images/logo.png ADDED
json_dataset/train-f14e52a9-8beb-4a90-ac8a-b0cae5352428.json ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ {"model": "microsoft/Phi-3-mini-4k-instruct", "error": ["Start tag expected, '<' not found, line 1, column 1", "Start tag expected, '<' not found, line 1, column 1", "Start tag expected, '<' not found, line 1, column 2", "Start tag expected, '<' not found, line 7, column 2", "Start tag expected, '<' not found, line 6, column 2"], "datetime": "2024-06-17T14:15:44.872853"}
2
+ {"model": "mistralai/Mistral-7B-Instruct-v0.2", "error": ["Extra content at the end of the document, line 4, column 1", "Namespace prefix ecore on EPackage is not defined, line 1, column 81", "Namespace prefix ecore on EPackage is not defined, line 1, column 81", "Start tag expected, '<' not found, line 1, column 1", "Namespace prefix ecore on EPackage is not defined, line 1, column 81"], "datetime": "2024-06-17T14:18:43.999325"}
outs/output0.ecore ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <ecore:EPackage name="FiniteStateMachine" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ecore="http://www.eclipse.org/emf/2002/Ecore" xsi:schemaLocation="http://www.eclipse.org/emf/2002/Ecore http://www.eclipse.org/emf/2002/Ecore.xsd">
2
+
3
+ </ecore:EPackage>
4
+ ```
5
+
6
+ 2. Inside the `EPackage`, define the `EClass` representing the FSM states. Let's call it `State`.
7
+
8
+ ```xml
9
+ <eClassifiers xsi:type="ecore:EClass" name="State">
10
+ <!-- Add structural features if necessary -->
11
+ </eClassifiers>
12
+ ```
13
+
14
+ 3. Inside the same `EPackage`, define the `EClass` representing the FSM itself. Let's call it `FSM`.
15
+
16
+ ```xml
17
+ <eClassifiers xsi:type="ecore:EClass" name="FSM">
18
+ <eStructuralFeatures xsi:type="ecore:EReference" name="currentState" lowerBound="1" eType="#//State" containment="true"/>
19
+ <!-- Add other features as needed, such as transitions -->
20
+ </eClassifiers>
outs/output1.ecore ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <ecore:EPackage name="library" nsURI="http://example.com/library" nsPrefix="lib">
2
+
3
+ </ecore:EPackage>
4
+ ```
5
+
6
+ ### EClassifiers
7
+
8
+ Inside the `EPackage`, you can define `EClassifiers`, which represent classes, data types, or other types in the model. The two most common types of `EClassifiers` are `EClass` and `EDataType`.
9
+
10
+ #### EClass
11
+
12
+ An `EClass` represents a class in the model. It can contain `EStructuralFeatures`, which define the attributes and references of the class.
13
+
14
+ Example:
15
+
16
+ ```xml
17
+ <eClassifiers xsi:type="ecore:EClass" name="Book">
18
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="title" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
19
+ <eStructuralFeatures xsi:type="ecore:EReference" name="author" lowerBound="1" eType="#//Author" containment="true"/>
20
+ </eClassifiers>
21
+ ```
22
+
23
+ In this example, the `Book` class has a `title` attribute (of type `EString`) and an `author` reference (to the `Author` class).
24
+
25
+ #### EStructuralFeatures
26
+
27
+ `EStructuralFeatures` represent the attributes and references of an `EClass`. They can be of type `EAttribute` or `EReference`.
28
+
29
+ - `EAttribute`: Represents an attribute of the class, with a name and a data type (`eType`).
30
+ - `EReference`: Represents a reference to another `EClass`, with a name, a reference type (`eType`), and additional properties like `containment`, `lowerBound`, and `upperBound`.
31
+
32
+ #### EDataType
33
+
34
+ An `EDataType` represents a data type in the model, such as `EString`, `EInt`, or a user-defined data type.
35
+
36
+ Example:
37
+
38
+ ```xml
39
+ <eClassifiers xsi:type="ecore:EDataType" name="SSN" instanceClassName="java.lang.String">
40
+ <eAnnotations source="http://www.eclipse.org/emf/2002/GenModel">
41
+ <details key="documentation" value="A social security number"/>
42
+ </eAnnotations>
43
+ </eClassifiers>
44
+ ```
45
+
46
+ In this example, the `SSN` data type is defined as a string with additional documentation.
47
+
48
+ ### Annotations
49
+
50
+ Ecore supports annotations, which provide additional metadata or constraints for model elements. Annotations are represented by the `eAnnotations` element.
51
+
52
+ Example:
53
+
54
+ ```xml
55
+ <eAnnotations source="http://www.eclipse.org/emf/2002/GenModel">
56
+ <details key="documentation" value="A social security number"/>
57
+ </eAnnotations>
58
+ ```
59
+
60
+ ### Containers and Nested Packages
61
+
62
+ To nest packages inside each other, use the `eContainedPackages` element under the parent `EPackage`.
63
+
64
+ Example:
65
+
outs/output2.ecore ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <ecore:EPackage name="library" nsURI="http://example.com/library" nsPrefix="lib">
2
+
3
+ </ecore:EPackage>
4
+ ```
5
+
6
+ ### EClassifiers
7
+
8
+ Within the `EPackage`, you may define `EClassifiers`, representing classes, data types, or other types in the model. The primary types of `EClassifiers` include `EClass` and `EDataType`.
9
+
10
+ #### EClass
11
+
12
+ An `EClass` represents a class in the model and contains `EStructuralFeatures`, defining its attributes and references.
13
+
14
+ Example:
15
+
16
+ ```xml
17
+ <eClassifiers xsi:type="ecore:EClass" name="Book">
18
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="title" eType="ecore:EDataType #//EString"/>
19
+ <eStructuralFeatures xsi:type="ecore:EReference" name="author" lowerBound="1" eType="#//Author" containment="true"/>
20
+ </eClassifiers>
21
+ ```
22
+
23
+ Here, the `Book` class possesses a `title` attribute (of type `EString`) and an `author` reference (referencing the `Author` class).
24
+
25
+ #### EStructuralFeatures
26
+
27
+ `EStructuralFeatures` denote the attributes and references of an `EClass`. They come in two forms: `EAttribute` and `EReference`.
28
+
29
+ - `EAttribute`: Defines an attribute of the class, consisting of a name and a data type (`eType`).
30
+ - `EReference`: Represents a reference to another `EClass`, including a name, a reference type (`eType`), and optional properties like `containment`, `lowerBound`, and `upperBound`.
31
+
32
+ #### EDataType
33
+
34
+ An `EDataType` represents a data type in the model, such as `EString`, `EInt`, or custom data types.
35
+
36
+ Example:
37
+
38
+ ```xml
39
+ <eClassifiers xsi:type="ecore:EDataType" name="SSN" instanceClassName="java.lang.String">
40
+ <eAnnotations source="http://www.eclipse.org/emf/2002/GenModel">
41
+ <details key="documentation" value="A social security number"/>
42
+ </eAnnotations>
43
+ </eClassifiers>
44
+ ```
45
+
46
+ This example introduces a `SSN` data type, defined as a string with added documentation.
47
+
48
+ ### Annotations
49
+
50
+ Ecore allows annotations, providing additional metadata or constraints for model elements. Annotations are represented through the `eAnnotations` element.
51
+
52
+ Example:
53
+
54
+ ```xml
55
+ <eAnnotations source="http://www.eclipse.org/emf/2002/GenModel">
56
+ <details key="documentation" value="A social security number"/>
57
+ </eAnnotations>
58
+ ```
59
+
60
+ ### Containers and Nested Packages
61
+
62
+ To embed packages within each other, utilize the `eContainedPackages` element beneath the parent `EPackage`.
63
+
64
+ Example:
65
+
66
+ ```xml
67
+ <ecore:EPackage name="RootPackage" nsURI="root_package.ecore" nsPrefix="rp">
68
+ ...
69
+ <eContainedPackages>
70
+ <eReference target="./sub_package.ecore"/>
71
+ </eContainedPackages>
72
+ </ecore:EPackage>
outs/output3.ecore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ have corrected the recurring errors in your document regarding XML comments and invalid tags. Here's the updated conclusion section:
2
+
3
+ ## Conclusion
4
+
5
+ Ecore files offer a standardized approach to modeling using an XML-based syntax. Understanding the syntax and semantics of Ecore files enables developers to build accurate and consistent models that serve as strong foundations for various EMF-based tools and applications. Remember to avoid using XML comments (<!-- -->) directly in the syntax and ensure proper usage of Ecore constructs, such as EPackage, EClass, EStructuralFeatures, and EDataTypes, along with their respective attributes and relationships. Happy modeling
outs/output4.ecore ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <ecore:EPackage name="library" nsURI="http://example.com/library" nsPrefix="lib">
2
+
3
+ </ecore:EPackage>
4
+ ```
5
+
6
+ ### EClassifiers
7
+
8
+ Within the `EPackage`, define `EClassifiers`�classes, data types, or other types. Commonly used `EClassifiers` include `EClass` and `EDataType`.
9
+
10
+ #### EClass
11
+
12
+ An `EClass` defines a class with possible `EStructuralFeatures`:
13
+
14
+ - Attributes (`EAttribute`).
15
+ - References (`EReference`).
16
+
17
+ Example:
18
+
19
+ ```xml
20
+ <eClassifiers xsi:type="ecore:EClass" name="Book">
21
+ <eStructuralFeatures>
22
+ <eStructuralFeature xsi:type="ecore:EAttribute" name="title" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
23
+ <eStructuralFeature xsi:type="ecore:EReference" name="author" lowerBound="1" eType="#//Author" containment="true"/>
24
+ </eStructuralFeatures>
25
+ </eClassifiers>
26
+ ```
27
+
28
+ #### EDataType
29
+
30
+ Define custom `EDataTypes`:
31
+
32
+ ```xml
33
+ <eClassifiers xsi:type="ecore:EDataType" name="SSN" instanceClassName="java.lang.String">
34
+ <eAnnotations source="http://www.eclipse.org/emf/2002/GenModel">
35
+ <details key="documentation" value="A social security number"/>
36
+ </eAnnotations>
37
+ </eClassifiers>
38
+ ```
39
+
40
+ ### Annotations
41
+
42
+ Use `eAnnotations` for metadata and constraints:
43
+
44
+ ```xml
45
+ <eAnnotations source="http://www.eclipse.org/emf/2002/GenModel">
46
+ <details key="documentation" value="A social security number"/>
47
+ </eAnnotations>
48
+ ```
49
+
50
+ ### Comments and Documentation
51
+
52
+ XML comments (<!-- -->) aren't supported; use `eAnnotations` instead.
53
+
54
+ ## Semantics
55
+
56
+ Beyond syntax, Ecore files establish model behavior and constraints through inheritance, containment, multiplicities, and operations/constraints.
57
+
58
+ ### Inheritance
59
+
60
+ Ecore allows single inheritance via `eSuperTypes`:
61
+
62
+ ```xml
63
+ <eClassifiers xsi:type="ecore:EClass" name="FictionBook" eSuperTypes="#//Book">
64
+ ...
65
+ </eClassifiers>
66
+ ```
67
+
68
+ ### Containment
69
+
70
+ Containment relationships exist when a reference has `containment="true"`:
71
+
72
+ ```xml
73
+ <eStructuralFeature xsi:type="ecore:EReference" name="author" lowerBound="1" eType="#//Author" containment="true"/>
74
+ ```
75
+
76
+ ### Multiplicities
77
+
78
+ Multiplicities specify allowed numbers of features:
79
+
80
+ ```xml
81
+ <eStructuralFeature xsi:type="ecore:EReference" name="chapters" upperBound="-1" eType="#//Chapter" containment="true"/>
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ pyecore
2
+ gradio
3
+ hugchat
4
+ langchain
5
+ langchain_community
6
+ huggingface
7
+ huggingface-hub
verify.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from hugchat import hugchat
2
+ from hugchat.login import Login
3
+ from pyecore.resources import ResourceSet, URI
4
+ import os
5
+
6
+ from pathlib import Path
7
+ from datasets import load_dataset
8
+ import pandas as pd
9
+ from datasets import Dataset,DatasetDict, load_dataset
10
+ from huggingface_hub import CommitScheduler
11
+ from uuid import uuid4
12
+ import json
13
+ from datetime import datetime
14
+
15
+
16
+ import os
17
+ JSON_DATASET_DIR = Path("json_dataset")
18
+ JSON_DATASET_DIR.mkdir(parents=True, exist_ok=True)
19
+
20
+ JSON_DATASET_PATH = JSON_DATASET_DIR / f"train-{uuid4()}.json"
21
+
22
+ scheduler = CommitScheduler(
23
+ repo_id="VeryMadSoul/errors",
24
+ repo_type="dataset",
25
+ folder_path=JSON_DATASET_DIR,
26
+ path_in_repo="data",
27
+ )
28
+
29
+ def save_json(model: str, errors: list) -> None:
30
+ with scheduler.lock:
31
+ with JSON_DATASET_PATH.open("a") as f:
32
+ json.dump({"model": model, "error": errors, "datetime": datetime.now().isoformat()}, f)
33
+ f.write("\n")
34
+
35
+ # Log into huggingface and grant authorization to huggingchat
36
+ EMAIL = os.environ['HF_EMAIL']
37
+ PASSWD = os.environ['HF_PASSWORD']
38
+ cookie_path_dir = "./cookies/" # NOTE: trailing slash (/) is required to avoid errors
39
+ sign = Login(EMAIL, PASSWD)
40
+ cookies = sign.login(cookie_dir_path=cookie_path_dir, save_cookies=True)
41
+
42
+ # Create your ChatBot
43
+ chatbot = hugchat.ChatBot(cookies=cookies.get_dict(), system_prompt = '''You are a systems engineer, expert in model driven engineering and meta-modeling
44
+ Your OUTPUT should always follow this format :
45
+
46
+ ```xml
47
+
48
+ < YOUR CODE HERE >
49
+
50
+ ```
51
+ ''') # or cookie_path="usercookies/<email>.json"
52
+ chatbot.switch_llm(1)
53
+
54
+ # Create a new conversation
55
+ chatbot.new_conversation(switch_to = True) # switch to the new conversation
56
+
57
+ #create prompt
58
+ NLD= '''SimplePDL is an experimental language for specifying processes. The SPEM standard (Software Process Engineering Metamodel) proposed by the OMG inspired our work, but we also took ideas from the UMA metamodel (Unified Method Architecture) used in the EPF Eclipse plug-in (Eclipse Process Framework), dedicated to process modeling. SimplePDL is simplified to keep the presentation simple.
59
+ Its metamodel is given in the figure 1. It defines the process concept (Process) composed of a set of work definitions (WorkDefinition) representing the activities to be performed during the development. One workdefinition may depend upon another (WorkSequence). In such a case, an ordering constraint (linkType) on the second workdefinition is specified, using the enumeration WorkSequenceType. For example, linking two workdefinitions wd1 and wd2 by a precedence relation of kind finishToStart means that wd2 can be started only if wd1 is finished (and respectively for startToStart, startToFinish and finishToFinish). SimplePDL does also allow to explicitly represent resources (Resource) that are needed in order to perform one workdefinition (designer, computer, server...) and also time constraints (min_time and max_time on WorkDefinition and Process) to specify the minimum (resp. maximum) time allowed to perform the workdefinition or the whole process.'''
60
+ description='''# Writing Ecore Files
61
+
62
+ ## Introduction
63
+
64
+ Ecore is the core meta-model of the Eclipse Modeling Framework (EMF), which provides a foundation for building tools and applications based on models. Ecore files define the structure and constraints of a model using an XML-based syntax. This document explains how to write Ecore files, covering both the syntax and semantics.
65
+
66
+ ## Syntax
67
+
68
+ An Ecore file is an XML document that follows the Ecore XML Schema. The root element of an Ecore file is `EPackage`, which represents a package or namespace for the model.
69
+
70
+ ### EPackage
71
+
72
+ The `EPackage` element has the following attributes:
73
+
74
+ - `name`: The name of the package.
75
+ - `nsURI`: The namespace Uniform Resource Identifier (URI) for the package, which should be a globally unique identifier.
76
+ - `nsPrefix`: The preferred namespace prefix to be used for the package.
77
+
78
+ Example:
79
+
80
+ ```xml
81
+ <ecore:EPackage name="library" nsURI="http://example.com/library" nsPrefix="lib">
82
+
83
+ </ecore:EPackage>
84
+ ```
85
+
86
+ ### EClassifiers
87
+
88
+ Inside the `EPackage`, you can define `EClassifiers`, which represent classes, data types, or other types in the model. The two most common types of `EClassifiers` are `EClass` and `EDataType`.
89
+
90
+ #### EClass
91
+
92
+ An `EClass` represents a class in the model. It can contain `EStructuralFeatures`, which define the attributes and references of the class.
93
+
94
+ Example:
95
+
96
+ ```xml
97
+ <eClassifiers xsi:type="ecore:EClass" name="Book">
98
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="title" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
99
+ <eStructuralFeatures xsi:type="ecore:EReference" name="author" lowerBound="1" eType="#//Author" containment="true"/>
100
+ </eClassifiers>
101
+ ```
102
+
103
+ In this example, the `Book` class has a `title` attribute (of type `EString`) and an `author` reference (to the `Author` class).
104
+
105
+ #### EStructuralFeatures
106
+
107
+ `EStructuralFeatures` represent the attributes and references of an `EClass`. They can be of type `EAttribute` or `EReference`.
108
+
109
+ - `EAttribute`: Represents an attribute of the class, with a name and a data type (`eType`).
110
+ - `EReference`: Represents a reference to another `EClass`, with a name, a reference type (`eType`), and additional properties like `containment`, `lowerBound`, and `upperBound`.
111
+
112
+ #### EDataType
113
+
114
+ An `EDataType` represents a data type in the model, such as `EString`, `EInt`, or a user-defined data type.
115
+
116
+ Example:
117
+
118
+ ```xml
119
+ <eClassifiers xsi:type="ecore:EDataType" name="SSN" instanceClassName="java.lang.String">
120
+ <eAnnotations source="http://www.eclipse.org/emf/2002/GenModel">
121
+ <details key="documentation" value="A social security number"/>
122
+ </eAnnotations>
123
+ </eClassifiers>
124
+ ```
125
+
126
+ In this example, the `SSN` data type is defined as a string with additional documentation.
127
+
128
+ ### Annotations
129
+
130
+ Ecore supports annotations, which provide additional metadata or constraints for model elements. Annotations are represented by the `eAnnotations` element.
131
+
132
+ Example:
133
+
134
+ ```xml
135
+ <eAnnotations source="http://www.eclipse.org/emf/2002/GenModel">
136
+ <details key="documentation" value="A social security number"/>
137
+ </eAnnotations>
138
+ ```
139
+ ### Comments and Documentation
140
+ XML comments are not supported in XMI Format
141
+ USE EANNOTATIONS instead
142
+
143
+
144
+
145
+ ## Semantics
146
+
147
+ Beyond the syntax, Ecore files also define the semantics of the model, which determine the behavior and constraints of the model elements.
148
+
149
+ ### Inheritance
150
+
151
+ Ecore supports inheritance between classes. An `EClass` can inherit from one or more `EClasses` using the `eSuperTypes` element.
152
+
153
+ Example:
154
+
155
+ ```xml
156
+ <eClassifiers xsi:type="ecore:EClass" name="FictionBook" eSuperTypes="#//Book">
157
+ <eStructuralFeatures xsi:type="ecore:EAttribute" name="genre" eType="ecore:EDataType http://www.eclipse.org/emf/2002/Ecore#//EString"/>
158
+ </eClassifiers>
159
+ ```
160
+
161
+ In this example, the `FictionBook` class inherits from the `Book` class and adds a `genre` attribute.
162
+
163
+ ### Containment
164
+
165
+ Ecore supports containment relationships between classes, which determine ownership and lifecycle management. A containment reference is specified using the `containment="true"` attribute on an `EReference`.
166
+
167
+ Example:
168
+
169
+ ```xml
170
+ <eStructuralFeatures xsi:type="ecore:EReference" name="author" lowerBound="1" eType="#//Author" containment="true"/>
171
+ ```
172
+
173
+ In this example, the `author` reference of the `Book` class has containment set to `true`, meaning that the `Author` instance is owned by the `Book` instance.
174
+
175
+ ### Multiplicities
176
+
177
+ Ecore supports multiplicity constraints on attributes and references, which define the allowed number of values for a feature. Multiplicities are specified using the `lowerBound` and `upperBound` attributes on `EStructuralFeatures`.
178
+
179
+ Example:
180
+
181
+ ```xml
182
+ <eStructuralFeatures xsi:type="ecore:EReference" name="chapters" upperBound="-1" eType="#//Chapter" containment="true"/>
183
+ ```
184
+
185
+ In this example, the `chapters` reference of a `Book` class has an unbounded upper bound (`-1`), allowing any number of `Chapter` instances to be contained within the `Book`.
186
+
187
+ ### Operations and Constraints
188
+
189
+ Ecore also supports the definition of operations and constraints on model elements, although these are typically specified using additional tools or languages, such as the Object Constraint Language (OCL) or Java code.
190
+
191
+
192
+ ##Reaccuring errors :
193
+ Invalid tag name error is linked to the tag <!-- --> don't use it in the syntax
194
+
195
+ ## Conclusion
196
+
197
+ Ecore files provide a structured way to define models using an XML-based syntax. By understanding the syntax and semantics of Ecore files, developers can create robust and well-defined models that can be used as the foundation for various tools and applications within the Eclipse Modeling Framework.'''
198
+ #prompt= "Convert the following description into an ecore xmi representation:\n" + NLD + "\n Here's a technical document of how to write correct ecore file:\n" + description #WHen tryin to add the description
199
+
200
+
201
+ # Non stream response
202
+ #query_result0 = chatbot.chat(prompt)
203
+ #print(query_result0) # or query_result.text or query_result["text"]
204
+
205
+ '''
206
+ # Stream response
207
+ for resp in chatbot.query(
208
+ "Hello",
209
+ stream=True
210
+ ):
211
+ print(resp)
212
+
213
+ # Web search (new feature)
214
+ query_result = chatbot.query("Hi!", web_search=True)
215
+ print(query_result)
216
+ for source in query_result.web_search_sources:
217
+ print(source.link)
218
+ print(source.title)
219
+ print(source.hostname)
220
+ '''
221
+
222
+ # Create a new conversation
223
+ #chatbot.new_conversation(switch_to = True) # switch to the new conversation
224
+
225
+ # Get conversations on the server that are not from the current session (all your conversations in huggingchat)
226
+ #conversation_list = chatbot.get_remote_conversations(replace_conversation_list=True)
227
+ # Get conversation list(local)
228
+ #conversation_list = chatbot.get_conversation_list()
229
+
230
+ # Get the available models (not hardcore)
231
+ #models = chatbot.get_available_llm_models()
232
+
233
+ # Switch model with given index
234
+
235
+ #chatbot.switch_llm(2) # Switch to the second model
236
+
237
+ # Get information about the current conversation
238
+ #info = chatbot.get_conversation_info()
239
+ #print(info.id, info.title, info.model, info.system_prompt, info.history)
240
+
241
+ ### Assistant
242
+ #assistant = chatbot.search_assistant(assistant_name="ChatGpt") # assistant name list in https://huggingface.co/chat/assistants
243
+ #assistant_list = chatbot.get_assistant_list_by_page(page=0)
244
+ #chatbot.new_conversation(assistant=assistant, switch_to=True) # create a new conversation with assistant
245
+ def initial_prompt(NLD, description):
246
+ prompt= "Convert the following description into an ecore xmi representation:\n" + NLD + "\n Here's a technical document of how to write correct ecore file:\n" + description #WHen tryin to add the description
247
+
248
+ return chatbot.chat(prompt)
249
+
250
+ def fix_err(xmi, err):
251
+ prompt="Fix the following error: " +str(err)+"\n in the following xmi :\n" + xmi+ "\n Here's a technical document of how to write correct ecore file:\n" + description
252
+
253
+ return chatbot.chat(prompt)
254
+
255
+ def verify_xmi(output,output_file_name):
256
+ #here we're gonna verify our Model's output by using the either a tool or a developped solution XMI parser
257
+
258
+ #Return can be either bool or preferably the actual compilation error or xmi line error
259
+ output = str(output)
260
+ #Returning a bool won't be that helpful ..
261
+ with open("outs\output"+output_file_name+".ecore", "w") as file1:
262
+ # Writing data to a file
263
+ if "```xml" in output:
264
+ file1.writelines(output[output.find("```xml")+len("```xml\n"):output.rfind("```")])
265
+ else:
266
+ file1.writelines(output[output.find("```")+len("```\n"):output.rfind("```")])
267
+ try:
268
+ rset = ResourceSet()
269
+ resource = rset.get_resource(URI("outs\output"+output_file_name+".ecore"))
270
+
271
+ except Exception as e:
272
+ return e.args[0]
273
+ return 'no e'
274
+
275
+ def iterative_prompting(NLD, XMI,max_iter=3):
276
+
277
+ history= []
278
+
279
+ i=0
280
+
281
+
282
+ XMI=""
283
+ output = initial_prompt(NLD, description)
284
+ history.append((NLD,str(output)))
285
+ print(output)
286
+
287
+ correct_syntax= verify_xmi(output,str(i))
288
+ errors =[]
289
+ error = (correct_syntax == 'no e')
290
+ errors.append(correct_syntax)
291
+
292
+ while (not error) and i<=max_iter:
293
+ i+=1
294
+
295
+
296
+ #print('****************************************')
297
+ #print('Iteration ' + str(i))
298
+ #print('****************************************')
299
+
300
+
301
+ error = "\n This Xmi was incorrect. Please fix the errors." + " "+str(correct_syntax)
302
+
303
+ #print("**************************")
304
+ #print(correct_syntax)
305
+ #print("**************************")
306
+
307
+
308
+ output = fix_err(output , correct_syntax)
309
+ history.append((error,str(output)))
310
+ #print(output)
311
+ correct_syntax = verify_xmi(output,str(i))
312
+ #print(correct_syntax)
313
+ error = (correct_syntax == 'no e')
314
+ errors.append(correct_syntax)
315
+
316
+ save_json(chatbot.get_conversation_info().model, errors)
317
+
318
+ return history, errors