acecalisto3 commited on
Commit
7590eeb
·
verified ·
1 Parent(s): a9c852c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -131
app.py CHANGED
@@ -1,133 +1,99 @@
1
  import os
2
- from typing import Dict, List, Optional
3
- from dataclasses import dataclass, field
4
- from transformers import (
5
- AutoModelForSequenceClassification,
6
- AutoTokenizer,
7
- DataCollatorWithPadding,
8
- HfArgumentParser,
9
- Trainer,
10
- TrainingArguments,
11
- )
12
-
13
- from transformers.models import AutoConfig
14
-
15
- @dataclass
16
- class ModelArguments:
17
- model_name: str = field(
18
- default="gpt2",
19
- metadata={"help": "The name of the pretrained model to use for text generation."}
20
- )
21
- max_tokens: int = field(
22
- default=50,
23
- metadata={"help": "The maximum number of tokens to generate in the response."}
24
- )
25
-
26
- class MockOpenAI:
27
- """
28
- A mock implementation of OpenAI's API using Hugging Face's pipeline for text generation.
29
-
30
- :param api_key: Your Hugging Face API key, required for authentication.
31
- :param base_url: The base URL for the Hugging Face API, defaults to the production URL.
32
- :param model_name: The name of the pretrained model to use for text generation, defaults to 'gpt2'.
33
- :param max_tokens: The maximum number of tokens to generate in the response, defaults to 50.
34
- """
35
- def __init__(
36
- self,
37
- api_key: Optional[str] = None,
38
- base_url: Optional[str] = None,
39
- model_name: Optional[str] = "gpt2",
40
- max_tokens: int = 50,
41
- ):
42
- self.api_key = api_key or os.environ.get("HUGGING_FACE_API_KEY")
43
- self.base_url = base_url or "https://api-inference.huggingface.co/models"
44
- self.model_name = model_name
45
- self.max_tokens = max_tokens
46
- self.config = AutoConfig.from_pretrained(self.model_name)
47
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
48
- self.model = AutoModelForSequenceClassification.from_pretrained(self.model_name, config=self.config)
49
- self.data_collator = DataCollatorWithPadding(self.tokenizer)
50
- self.trainer = Trainer(
51
- model=self.model,
52
- args=TrainingArguments(
53
- output_dir="./",
54
- num_train_epochs=1,
55
- learning_rate=1e-5,
56
- per_device_train_batch_size=16,
57
- per_device_eval_batch_size=16,
58
- evaluation_strategy="epoch",
59
- # Remove this line:
60
- # use_seedable_sampler=True,
61
- ),
62
- )
63
-
64
- class Chat:
65
- if 'toolbox' not in st.session_state:
66
- st.session_state['toolbox'] = {}
67
-
68
- def __init__(self, mock_openai: 'MockOpenAI'):
69
- self.mock_openai = mock_openai
70
-
71
- class Completions:
72
- def __init__(self, mock_openai: 'MockOpenAI'):
73
- self.mock_openai = mock_openai
74
-
75
- def create(
76
- self,
77
- messages: List[Dict[str, str]],
78
- model: Optional[str] = None,
79
- max_tokens: int = 50,
80
- **kwargs,
81
- ):
82
- """
83
- Generate a text completion based on the given messages.
84
-
85
- :param messages: List of message objects, each containing 'role' and 'content'.
86
- :param model: The name of the pretrained model to use for text generation, defaults to 'gpt2'.
87
- :param max_tokens: The maximum number of tokens to generate in the response, defaults to 50.
88
- :param kwargs: Additional keyword arguments to pass to the pipeline function.
89
- :return: A dictionary containing the generated text.
90
- """
91
- if not self.mock_openai.config.is_decoder:
92
- raise ValueError("This model is not a decoder.")
93
-
94
- model_name = model or self.mock_openai.model_name
95
- prompt = " ".join([msg["content"] for msg in messages])
96
-
97
- inputs = self.mock_openai.tokenizer(prompt, padding="max_length", truncation=True)
98
- outputs = self.mock_openai.trainer.predict(inputs.to_tensor(pad_to_multiple_of=self.mock_openai.config.max_length))
99
- result = self.mock_openai.tokenizer.decode(outputs[0], skip_special_tokens=True)
100
-
101
- if max_tokens is not None and len(result) > max_tokens:
102
- result = result[:max_tokens]
103
-
104
- return result
105
-
106
- @property
107
- def chat(self):
108
- """
109
- Get the Chat class instance with the pretrained model for text generation.
110
-
111
- :return: The Chat class instance.
112
- """
113
- return self.Chat(self)
114
-
115
- # Example usage
116
  if __name__ == "__main__":
117
- parser = HfArgumentParser((ModelArguments,))
118
- model_args = parser.parse_args_into_dataclasses()[0]
119
- client = MockOpenAI(model_name=model_args.model_name, max_tokens=model_args.max_tokens)
120
- chat_completion = client.chat.Completions().create(
121
- messages=[
122
- {
123
- "role": "system",
124
- "content": "You are a helpful assistant.",
125
- },
126
- {
127
- "role": "user",
128
- "content": "What is deep learning?",
129
- }
130
- ]
131
- )
132
-
133
- print(chat_completion)
 
1
  import os
2
+ import sys
3
+ import time
4
+
5
+ import huggingface_hub
6
+
7
+ from huggingface_hub.commands import HfFolder
8
+
9
+ import transformers
10
+
11
+ from transformers import pipeline
12
+
13
+ import gradio as gr
14
+
15
+ import tempfile
16
+
17
+ from huggingface_hub import HfFolder
18
+
19
+ def main():
20
+ # Get the user's idea
21
+ idea = input("What is your idea for an application? ")
22
+
23
+ # Generate the code for the application
24
+ code = gemmacode.generate(idea)
25
+
26
+ # Test the code
27
+ try:
28
+ transformers.pipeline("text-generation")(code)
29
+ except Exception as e:
30
+ print("The code failed to run:", e)
31
+ return
32
+
33
+ # Ensure the functionality of the application
34
+ try:
35
+ gr.Interface(fn=transformers.pipeline("text-generation"), inputs=gr.Textbox(), outputs=gr.Textbox()).launch()
36
+ except Exception as e:
37
+ print("The application failed to run:", e)
38
+ return
39
+
40
+ # Provide an embedded webapp demo of the user's idea implementation
41
+ try:
42
+ hf_folder = HfFolder(path=tempfile.mkdtemp())
43
+ hf_folder.save(code)
44
+ hf_folder.push_to_hub(repo_id="acecalisto3/gemmacode-demo", commit_message="Initial commit")
45
+ print(f"The demo is available at: https://huggingface.co/acecalisto3/gemmacode-demo")
46
+ except Exception as e:
47
+ print("The demo failed to launch:", e)
48
+ return
49
+
50
+ # Offer the option to rebuild or deploy
51
+ while True:
52
+ choice = input("Do you want to rebuild or deploy the application? (r/d/q) ")
53
+ if choice == "r":
54
+ # Rebuild the code
55
+ code = gemmacode.generate(idea)
56
+
57
+ # Test the code
58
+ try:
59
+ transformers.pipeline("text-generation")(code)
60
+ except Exception as e:
61
+ print("The code failed to run:", e)
62
+ return
63
+
64
+ # Ensure the functionality of the application
65
+ try:
66
+ gr.Interface(fn=transformers.pipeline("text-generation"), inputs=gr.Textbox(), outputs=gr.Textbox()).launch()
67
+ except Exception as e:
68
+ print("The application failed to run:", e)
69
+ return
70
+
71
+ # Provide an embedded webapp demo of the user's idea implementation
72
+ try:
73
+ hf_folder = HfFolder(path=tempfile.mkdtemp())
74
+ hf_folder.save(code)
75
+ hf_folder.push_to_hub(repo_id="acecalisto3/gemmacode-demo", commit_message="Initial commit")
76
+ print(f"The demo is available at: https://huggingface.co/acecalisto3/gemmacode-demo")
77
+ except Exception as e:
78
+ print("The demo failed to launch:", e)
79
+ return
80
+ elif choice == "d":
81
+ # Deploy the application
82
+ try:
83
+ api_token = os.environ["HF_TOKEN"]
84
+ hub = huggingface_hub.HfApi(api_token=api_token)
85
+ hub.create_repo(name="my-app", organization="my-org")
86
+ hf_folder = HfFolder(path=tempfile.mkdtemp())
87
+ hf_folder.save(code)
88
+ hf_folder.push_to_hub(repo_id="my-org/my-app", commit_message="Initial commit")
89
+ print("The application has been deployed to: https://huggingface.co/my-org/my-app")
90
+ except Exception as e:
91
+ print("The application failed to deploy:", e)
92
+ return
93
+ elif choice == "q":
94
+ break
95
+ else:
96
+ print("Invalid choice")
97
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  if __name__ == "__main__":
99
+ main()