lu-ny commited on
Commit
21633e5
·
1 Parent(s): de43e0c

Update app.py

Browse files

comments, bug fixes

Files changed (1) hide show
  1. app.py +23 -17
app.py CHANGED
@@ -3,25 +3,33 @@ import gradio as gr
3
  from huggingface_hub import InferenceClient
4
  import random
5
 
6
- # lists for random gen, not the best format here but it runs fine
7
- book_genres = ["Adventure", "Romance","Mystery", "Science Fiction","Fantasy","Thriller","Horror","Historical Fiction","Biography","Autobiography","Self-Help","Non-Fiction","Science","Cooking","Travel","Dystopian","Young Adult","Children's","Poetry","Classic","Graphic Novel","Humor","Crime","Western","Memoir","Religion","Psychology","Philosophy","Business","Finance","Parenting","Health","Fitness","Art","Music","Sports","Politics","Education","Technology","Science Fiction Fantasy","Steampunk","Drama","Historical Non-Fiction","Biographical Fiction","Mythology","Anthology","Short Stories","Essays","Fairy Tales","Magic Realism","True Crime","Satire","Romantic Suspense","Paranormal","Urban Fantasy","War","Epic Fantasy","Contemporary Fiction","Legal Thriller","Espionage","Post-Apocalyptic","Time Travel","Cultural","Medical","Environmental","Artificial Intelligence","Cyberpunk","Space Opera","Alternate History","Historical Romance","Science Fiction Romance","Young Adult Fantasy","Middle Grade","Adventure Fantasy","Superhero","Graphic Memoir","Travel Memoir","Political Thriller","Economic","Psychological Thriller","Nature","True Adventure","Historical Mystery","Social Science","Science Biography","Space Exploration","Pop Culture","Art History","Culinary","Nature Writing","Family Drama","Classic Literature","Cultural History","Political Science","Economics","Essays and Criticism","Art Criticism","Criminal Justice","Historical Biography","Personal Development","Cookbook","Fashion","Crafts and Hobbies","Memoir","Essays","Graphic Non-Fiction", "Fantasy Romance"]
8
  book_themes = ["Love and Relationships","Friendship","Family","Coming of Age","Identity and Self-discovery","Adventure and Exploration","Mystery and Intrigue","Science and Technology","Fantasy Worlds","Historical Events","War and Conflict","Survival","Good vs. Evil","Justice and Morality","Revenge","Betrayal","Hope and Resilience","Isolation and Loneliness","Social Justice","Environmental Conservation","Political Corruption","Human Rights","Dystopia","Utopia","Alien Encounters","Time Travel","Art and Creativity","Death and Mortality","Cultural Identity","Personal Growth","Addiction","Education and Knowledge","Freedom and Liberation","Equality and Inequality","Society and Class","Legacy and Inheritance","Religion and Spirituality","Grief and Loss","Ambition","Transformation","Humor and Satire","Survival of the Fittest","Dreams and Aspirations","Change and Adaptation","Forgiveness","Nature and the Environment","Exploration of the Unknown","Conflict Resolution","Fate and Destiny","Artificial Intelligence","Cybersecurity","Space Exploration","Parallel Universes","Economic Struggles","Social Media and Technology","Innovation and Invention","Psychological Thrills","Philosophical Contemplation","Ancient Mythology","Modern Mythology","Epic Journeys","The Power of Imagination","Unrequited Love","Secrets and Hidden Truths","Warriors and Heroes","Surviving Adversity","Dreams and Nightmares","Rivalry and Competition","Alien Worlds","Conspiracy","Apocalyptic Scenarios","Conformity vs. Individuality","Legacy and Heritage","Nature vs. Nurture","Moral Dilemmas","Adventure and Discovery","Journey of Self-Discovery","Unlikely Friendships","Struggle for Power","Exploration of Fear","The Supernatural","Cultural Clashes","Identity Crisis","The Quest for Knowledge","The Human Condition","Hidden Agendas","Escapism","The Pursuit of Happiness","Redemption","Rebellion","Feminism and Gender Issues","Exploration of Dreams","Innocence vs. Experience","Chaos and Order","Exploration of Evil"]
9
  writing_tones = ["Formal","Informal","Humorous","Serious","Sarcastic","Satirical","Melancholic","Optimistic","Pessimistic","Cynical","Hopeful","Lighthearted","Dark","Gothic","Whimsical","Mysterious","Eerie","Solemn","Playful","Thoughtful","Reflective","Ironic","Sensual","Nostalgic","Surreal","Dreamy","Awe-Inspiring","Introspective","Confessional","Dramatic","Exuberant","Melodramatic","Hypnotic","Inspirational","Tongue-in-Cheek","Witty","Calm","Passionate","Detached","Frightening","Intense","Calm","Suspenseful","Brave","Desperate","Eloquent","Vivid","Casual","Whispering","Eloquent","Bitter","Tragic","Pensive","Frenzied","Melodious","Resolute","Soothing","Brisk","Lyrical","Objective","Factual","Contemplative","Sardonic","Sympathetic","Objective","Sincere","Wistful","Stoic","Empathetic","Matter-of-fact","Sentimental","Sharp","Understated","Exaggerated","Casual","Bombastic","Poetic","Charming","Apologetic","Defensive","Confrontational","Inquisitive","Candid","Reverent","Matter-of-fact","Amusing","Enthusiastic","Questioning","Reproachful","Hopeless","Despondent","Wry","Sulking","Serene","Detached","Confident","Steadfast","Foolish","Impassioned","Indignant","Self-Deprecating","Wandering","Inspiring","Bewildered"]
10
 
11
-
12
  client = InferenceClient(
13
  "mistralai/Mixtral-8x7B-Instruct-v0.1"
14
  )
15
 
16
- def format_prompt(message, history, genres, moods, themes):
 
 
 
 
17
  if not genres:
18
  genres = ", ".join(random.sample(book_genres, random.randint(3, 5)))
19
- if not moods:
20
- moods = ", ".join(random.sample(writing_tones, random.randint(3, 5)))
21
  if not themes:
22
  themes = ", ".join(random.sample(book_themes, random.randint(3, 5)))
23
-
24
- prompt = f"Write a simple novel title and interesting summary for a book that falls under the following \n genres: {genres}, \n themes: {themes}, \n and moods: {moods}. \n Title:"
 
 
 
 
25
  for user_prompt, bot_response in history:
26
  prompt += f"[INST] {user_prompt} [/INST]"
27
  prompt += f" {bot_response}</s> "
@@ -29,9 +37,9 @@ def format_prompt(message, history, genres, moods, themes):
29
  return prompt
30
 
31
 
32
-
33
- def generate(genres, moods, themes, history, system_prompt, temperature=1.25, max_new_tokens=256, top_p=0.95, repetition_penalty=1.15,):
34
-
35
  temperature = float(temperature)
36
  if temperature < 1e-2:
37
  temperature = 1e-2
@@ -46,7 +54,7 @@ def generate(genres, moods, themes, history, system_prompt, temperature=1.25, m
46
  seed=42,
47
  )
48
 
49
- formatted_prompt = format_prompt(f"{system_prompt}, '' ", history, genres, moods, themes)
50
  stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
51
  output = ""
52
 
@@ -69,7 +77,7 @@ additional_inputs=[
69
  maximum=1.0,
70
  step=0.05,
71
  interactive=True,
72
- info="Higher values produce more diverse outputs",
73
  ),
74
  gr.Slider(
75
  label="Max new tokens",
@@ -78,7 +86,7 @@ additional_inputs=[
78
  maximum=1048,
79
  step=64,
80
  interactive=True,
81
- info="The maximum numbers of new tokens",
82
  ),
83
  gr.Slider(
84
  label="Top-p (nucleus sampling)",
@@ -96,7 +104,7 @@ additional_inputs=[
96
  maximum=2.0,
97
  step=0.05,
98
  interactive=True,
99
- info="Penalize repeated tokens",
100
  )
101
  ]
102
 
@@ -107,13 +115,11 @@ def launch_interface():
107
  gr.Textbox("", label="Book Genres (comma-separated, or leave blank!)"),
108
  gr.Textbox("", label="Book Themes (comma-separated, or leave blank!)"),
109
  gr.Textbox("", label="Writing Tone (comma-separated, or leave blank!)"),
110
- gr.Slider(0.1, 10.0, 1.3, label="Temperature (Creativity)"),
111
  ],
112
  additional_inputs=additional_inputs,
113
  outputs="text",
114
  live=False,
115
  title="Novel Title and Summary Generator",
116
- layout = 'panel'
117
  theme='ParityError/Interstellar',
118
  )
119
 
 
3
  from huggingface_hub import InferenceClient
4
  import random
5
 
6
+ # lists for random gen, not the best format here but it runs fine, might add these as json or txt files later
7
+ book_genres = ["Adventure", "Romance","Mystery", "Science Fiction","Fantasy","Thriller","Horror","Historical Fiction","Biography","Autobiography","Self-Help","Non-Fiction","Science","Cooking","Travel","Dystopian","Young Adult","Children's","Poetry","Classic","Graphic Novel","Humor","Crime","Western","Memoir","Religion","Psychology","Philosophy","Business","Finance","Parenting","Health","Fitness","Art","Music","Sports","Politics","Education","Technology","Science Fiction Fantasy","Steampunk","Drama","Historical Non-Fiction","Biographical Fiction","Mythology","Anthology","Short Stories","Essays","Fairy Tales","Magic Realism","True Crime","Satire","Romantic Suspense","Paranormal","Urban Fantasy","War","Epic Fantasy","Contemporary Fiction","Legal Thriller","Espionage","Post-Apocalyptic","Time Travel","Cultural","Medical","Environmental","Artificial Intelligence","Cyberpunk","Space Opera","Alternate History","Historical Romance","Science Fiction Romance","Young Adult Fantasy","Adventure Fantasy","Superhero","Graphic Memoir","Travel Memoir","Political Thriller","Economic","Psychological Thriller","Nature","True Adventure","Historical Mystery","Social Science","Science Biography","Space Exploration","Pop Culture","Art History","Culinary","Nature Writing","Family Drama","Classic Literature","Cultural History","Political Science","Economics","Essays and Criticism","Art Criticism","Criminal Justice","Historical Biography","Personal Development","Cookbook","Fashion","Crafts and Hobbies","Memoir","Essays","Graphic Non-Fiction", "Fantasy Romance"]
8
  book_themes = ["Love and Relationships","Friendship","Family","Coming of Age","Identity and Self-discovery","Adventure and Exploration","Mystery and Intrigue","Science and Technology","Fantasy Worlds","Historical Events","War and Conflict","Survival","Good vs. Evil","Justice and Morality","Revenge","Betrayal","Hope and Resilience","Isolation and Loneliness","Social Justice","Environmental Conservation","Political Corruption","Human Rights","Dystopia","Utopia","Alien Encounters","Time Travel","Art and Creativity","Death and Mortality","Cultural Identity","Personal Growth","Addiction","Education and Knowledge","Freedom and Liberation","Equality and Inequality","Society and Class","Legacy and Inheritance","Religion and Spirituality","Grief and Loss","Ambition","Transformation","Humor and Satire","Survival of the Fittest","Dreams and Aspirations","Change and Adaptation","Forgiveness","Nature and the Environment","Exploration of the Unknown","Conflict Resolution","Fate and Destiny","Artificial Intelligence","Cybersecurity","Space Exploration","Parallel Universes","Economic Struggles","Social Media and Technology","Innovation and Invention","Psychological Thrills","Philosophical Contemplation","Ancient Mythology","Modern Mythology","Epic Journeys","The Power of Imagination","Unrequited Love","Secrets and Hidden Truths","Warriors and Heroes","Surviving Adversity","Dreams and Nightmares","Rivalry and Competition","Alien Worlds","Conspiracy","Apocalyptic Scenarios","Conformity vs. Individuality","Legacy and Heritage","Nature vs. Nurture","Moral Dilemmas","Adventure and Discovery","Journey of Self-Discovery","Unlikely Friendships","Struggle for Power","Exploration of Fear","The Supernatural","Cultural Clashes","Identity Crisis","The Quest for Knowledge","The Human Condition","Hidden Agendas","Escapism","The Pursuit of Happiness","Redemption","Rebellion","Feminism and Gender Issues","Exploration of Dreams","Innocence vs. Experience","Chaos and Order","Exploration of Evil"]
9
  writing_tones = ["Formal","Informal","Humorous","Serious","Sarcastic","Satirical","Melancholic","Optimistic","Pessimistic","Cynical","Hopeful","Lighthearted","Dark","Gothic","Whimsical","Mysterious","Eerie","Solemn","Playful","Thoughtful","Reflective","Ironic","Sensual","Nostalgic","Surreal","Dreamy","Awe-Inspiring","Introspective","Confessional","Dramatic","Exuberant","Melodramatic","Hypnotic","Inspirational","Tongue-in-Cheek","Witty","Calm","Passionate","Detached","Frightening","Intense","Calm","Suspenseful","Brave","Desperate","Eloquent","Vivid","Casual","Whispering","Eloquent","Bitter","Tragic","Pensive","Frenzied","Melodious","Resolute","Soothing","Brisk","Lyrical","Objective","Factual","Contemplative","Sardonic","Sympathetic","Objective","Sincere","Wistful","Stoic","Empathetic","Matter-of-fact","Sentimental","Sharp","Understated","Exaggerated","Casual","Bombastic","Poetic","Charming","Apologetic","Defensive","Confrontational","Inquisitive","Candid","Reverent","Matter-of-fact","Amusing","Enthusiastic","Questioning","Reproachful","Hopeless","Despondent","Wry","Sulking","Serene","Detached","Confident","Steadfast","Foolish","Impassioned","Indignant","Self-Deprecating","Wandering","Inspiring","Bewildered"]
10
 
11
+ # initialize client
12
  client = InferenceClient(
13
  "mistralai/Mixtral-8x7B-Instruct-v0.1"
14
  )
15
 
16
+ # helper function to format the prompt appropriately.
17
+ # For this creative writing tool, the user doesn't design the prompt itself for rather genres, tones, & themes of a book to include
18
+ def format_prompt(message, history, genres, tones, themes):
19
+ # pick random ones if user leaves it blank
20
+ # TODO: use NLP or somethign so that there aren't contrasting ideas in the same prompt (ex. western and cyberpunk genres or dark and lighthearted tones)
21
  if not genres:
22
  genres = ", ".join(random.sample(book_genres, random.randint(3, 5)))
23
+ if not tones:
24
+ tones = ", ".join(random.sample(writing_tones, random.randint(3, 5)))
25
  if not themes:
26
  themes = ", ".join(random.sample(book_themes, random.randint(3, 5)))
27
+
28
+ #BOS token
29
+ prompt = '<s>'
30
+ #prompt we are using for now
31
+ user_prompt = f"Write a novel title and a detailed, creative summary/synopsis for a book that falls under the following \n genres: {genres}, \n themes: {themes}, \n and tones: {tones}."
32
+ # create our prompt according to Mistral's guidelines
33
  for user_prompt, bot_response in history:
34
  prompt += f"[INST] {user_prompt} [/INST]"
35
  prompt += f" {bot_response}</s> "
 
37
  return prompt
38
 
39
 
40
+ # main function
41
+ def generate(genres, themes, tones, history, system_prompt, temperature=1.25, max_new_tokens=256, top_p=0.95, repetition_penalty=1.15,):
42
+ # check the temperature value, should not be too low, and make sure the values are floats
43
  temperature = float(temperature)
44
  if temperature < 1e-2:
45
  temperature = 1e-2
 
54
  seed=42,
55
  )
56
 
57
+ formatted_prompt = format_prompt(f"{system_prompt}, '' ", history, genres, tones, themes)
58
  stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
59
  output = ""
60
 
 
77
  maximum=1.0,
78
  step=0.05,
79
  interactive=True,
80
+ info="Higher values produce more diverse outputs but can cause loss of coherence",
81
  ),
82
  gr.Slider(
83
  label="Max new tokens",
 
86
  maximum=1048,
87
  step=64,
88
  interactive=True,
89
+ info="The maximum numbers of new tokens (approx. wordcount) generated",
90
  ),
91
  gr.Slider(
92
  label="Top-p (nucleus sampling)",
 
104
  maximum=2.0,
105
  step=0.05,
106
  interactive=True,
107
+ info="Penalize repeated tokens, encourages creativity",
108
  )
109
  ]
110
 
 
115
  gr.Textbox("", label="Book Genres (comma-separated, or leave blank!)"),
116
  gr.Textbox("", label="Book Themes (comma-separated, or leave blank!)"),
117
  gr.Textbox("", label="Writing Tone (comma-separated, or leave blank!)"),
 
118
  ],
119
  additional_inputs=additional_inputs,
120
  outputs="text",
121
  live=False,
122
  title="Novel Title and Summary Generator",
 
123
  theme='ParityError/Interstellar',
124
  )
125