Patrick079 commited on
Commit
26af61c
·
verified ·
1 Parent(s): 41a648c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -58
app.py CHANGED
@@ -1,64 +1,108 @@
 
1
  import gradio as gr
 
2
  from huggingface_hub import InferenceClient
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  ],
 
 
60
  )
61
 
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
+ import random
2
  import gradio as gr
3
+ import ollama
4
  from huggingface_hub import InferenceClient
5
+ import os
6
+ import httpx
7
 
8
+ #clienttt = httpx.Client(base_url="http://localhost:11434")
9
+ #ollama._clienttt = clienttt
10
+ #ollama.pull("llama2")
11
+
12
+ def chat_short_story(length, genre, theme, tone, writing_style):
13
+ """
14
+ Generates a creative short story using a Hugging Face model.
15
+ Parameters:
16
+ length (int): The approximate word count for the story.
17
+ genre (str): The genre of the story (e.g., fantasy, mystery).
18
+ theme (str): The central theme of the story.
19
+ tone (str): The tone of the story (e.g., humorous, serious).
20
+ writing_style (str): The writing style (e.g., poetic, conversational).
21
+ Returns:
22
+ str: The generated short story, or an error message if unsuccessful.
23
+ """
24
+ # System message to define the assistant's role
25
+ system_message = (
26
+ "You are a highly creative short story writer capable of crafting stories across any genre. "
27
+ "For every story created, ensure you generate a suitable title."
28
+ )
29
+
30
+ # Construct the user prompt
31
+ prompt = (
32
+ f"Write a creative short story of approximately {length} words in the {genre} genre. "
33
+ f"Use a {writing_style} writing style with a {tone} tone. "
34
+ f"The story should revolve around the theme of {theme}. "
35
+ f"Ensure the narrative is compelling and includes a suitable title."
36
+ )
37
+
38
+ # Retrieve the Hugging Face API key from the environment
39
+ HUGGINGFACE_API_KEY = os.getenv("HUGGINGFACE_API_KEY")
40
+ if not HUGGINGFACE_API_KEY:
41
+ return "Error: Hugging Face API key not found. Please set the HUGGINGFACE_API_KEY environment variable."
42
+
43
+ # Initialize the Hugging Face Inference Client
44
+ try:
45
+ client = InferenceClient(api_key=HUGGINGFACE_API_KEY)
46
+ except Exception as e:
47
+ return f"Error: Failed to initialize Hugging Face client. Details: {e}"
48
+
49
+ # Interact with the model
50
+ try:
51
+ result = client.chat.completions.create(
52
+ model="meta-llama/Llama-2-7b-chat-hf",
53
+ messages=[
54
+ {"role": "system", "content": system_message},
55
+ {"role": "user", "content": prompt},
56
+ ]
57
+ )
58
+ except Exception as e:
59
+ return f"Error: Failed to interact with the model. Details: {e}"
60
+
61
+ # Extract the story content from the response
62
+ if "choices" in result and len(result["choices"]) > 0:
63
+ return result["choices"][0]["message"]["content"]
64
+ else:
65
+ return "Error: No story generated. Please check your prompt or model configuration."
66
+
67
+
68
+
69
+ # Predefined options
70
+ Length = [100, 250, 750]
71
+ Length = [l for l in Length if l >= 100]
72
+ r_length = random.choice(Length)
73
+
74
+ Genre = [
75
+ "Fiction", "Nonfiction", "Drama", "Poetry", "Fantasy", "Horror", "Mystery",
76
+ "Science Fiction", "Suspense", "Women's fiction", "Supernatural/Paranormal", "Young adult"
77
+ ]
78
+ r_genre = random.choice(Genre)
79
+
80
+ Themes = [
81
+ "Love", "Redemption", "Forgiveness", "Coming of age", "Revenge", "Good vs evil",
82
+ "Bravery and hardship", "The power of social status", "The destructive nature of love",
83
+ "The fallibility of the human condition"
84
+ ]
85
+ r_themes = random.choice(Themes)
86
+
87
+ Writing_Styles = ["Expository", "Narrative", "Descriptive", "Persuasive", "Creative"]
88
+ r_Style = random.choice(Writing_Styles)
89
+
90
+ Tones = ["Formal", "Optimistic", "Worried", "Friendly", "Curious", "Assertive", "Encouraging"]
91
+ r_tones = random.choice(Tones)
92
+
93
+
94
+ # Gradio Interface setup
95
+ iface = gr.Interface(
96
+ fn=chat_short_story,
97
+ inputs=[
98
+ gr.Slider(value=100, label="Story_Length", minimum=100, maximum=2500),
99
+ gr.Dropdown(label="Story_Genre", choices=Genre),
100
+ gr.Dropdown(label="Story_Theme", choices=Themes),
101
+ gr.Dropdown(label="Writing_Styles", choices=Writing_Styles),
102
+ gr.Dropdown(label="Story_Tone", choices=Tones)
103
  ],
104
+ outputs=gr.Text(),
105
+ title="Welcome to the Patrick's Story Generator"
106
  )
107
 
108
+ iface.launch()