naonauno commited on
Commit
e106f51
·
verified ·
1 Parent(s): 4e1b21a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -111
app.py CHANGED
@@ -1,93 +1,90 @@
1
  import gradio as gr
2
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
3
- import torch
4
  from typing import List, Dict
5
  from datetime import datetime
6
 
7
- class MissionContext:
8
  def __init__(self):
9
  self.mission_counter = 1
10
- self.current_objectives = {}
11
- self.conversation_history = []
12
-
13
- def add_to_history(self, role: str, content: str):
14
- self.conversation_history.append({
15
- "role": role,
16
- "content": content,
17
- "timestamp": datetime.now().isoformat()
18
- })
19
- # Keep only last 5 messages for context
20
- if len(self.conversation_history) > 5:
21
- self.conversation_history.pop(0)
 
 
22
 
23
- class MissionGenerator:
24
- def __init__(self):
25
- # Using FLAN-T5-base, a free and lightweight model good for instruction following
26
- self.model_name = "google/flan-t5-base"
27
- self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
28
- self.model = AutoModelForSeq2SeqLM.from_pretrained(self.model_name)
29
- self.context = MissionContext()
30
 
31
- def format_conversation_history(self) -> str:
32
- """Format conversation history for the model input"""
33
- formatted = ""
34
- for msg in self.context.conversation_history:
35
- role = "User" if msg["role"] == "user" else "Assistant"
36
- formatted += f"{role}: {msg['content']}\n"
37
- return formatted
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
 
 
39
  def generate_response(self, user_input: str) -> tuple[str, str]:
40
- """Generate both conversational response and formatted mission objectives"""
41
- self.context.add_to_history("user", user_input)
42
 
43
- # Create prompt for the model
44
- conversation_history = self.format_conversation_history()
45
- prompt = f"""
46
- Previous conversation:
47
- {conversation_history}
48
-
49
- Task: Generate a mission for Original War game based on the conversation.
50
- Format the response as follows:
51
- 1. A conversational response understanding the mission
52
- 2. The mission objectives in Original War format using Add Main/Secondary/Alternative
53
 
54
- Current request: {user_input}
55
- """
 
56
 
57
- # Generate response using the model
58
- inputs = self.tokenizer(prompt, return_tensors="pt", max_length=512, truncation=True)
59
- outputs = self.model.generate(
60
- inputs["input_ids"],
61
- max_length=256,
62
- do_sample=True, # Enable sampling
63
- temperature=0.7, # Control randomness
64
- top_p=0.9, # Nucleus sampling
65
- num_beams=4, # Beam search
66
- no_repeat_ngram_size=2
67
- )
68
 
69
- full_response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
70
 
71
- # Split the response into conversational and formatted parts
72
- try:
73
- parts = full_response.split("# M1")
74
- chat_response = parts[0].strip()
75
- formatted_objectives = "# M1" + parts[1] if len(parts) > 1 else self.generate_fallback_objectives(user_input)
76
- except Exception:
77
- chat_response = full_response
78
- formatted_objectives = self.generate_fallback_objectives(user_input)
79
 
80
- self.context.add_to_history("assistant", chat_response)
81
- return chat_response, formatted_objectives
82
-
83
- def generate_fallback_objectives(self, user_input: str) -> str:
84
- """Generate basic objectives if the main generation fails"""
85
- return f"""# M1
86
- Add Main mission_objective
87
- - Complete the primary mission goal
88
- Add Secondary bonus_objective
89
- - Optional additional task
90
- #"""
91
 
92
  def create_gradio_interface():
93
  generator = MissionGenerator()
@@ -101,13 +98,14 @@ def create_gradio_interface():
101
  with gr.Blocks() as interface:
102
  gr.Markdown("""
103
  # Original War Mission Objective Generator
104
- Describe your mission scenario in natural language, and I'll help you create formatted mission objectives.
 
105
  """)
106
 
107
  chatbot = gr.Chatbot(height=400, type="messages")
108
  msg = gr.Textbox(
109
  label="Describe your mission scenario",
110
- placeholder="Tell me about the mission you want to create..."
111
  )
112
  clear = gr.Button("Clear Conversation")
113
  formatted_output = gr.Textbox(
@@ -123,9 +121,9 @@ def create_gradio_interface():
123
 
124
  gr.Examples(
125
  examples=[
126
- "I need a mission where players have to infiltrate an enemy base. They should try to avoid detection, but if they get spotted, they'll need to fight their way through.",
127
- "Create a defensive mission where players protect a convoy. They should also try to minimize civilian casualties.",
128
- "I want players to capture a strategic point. They can either do it by force or try diplomatic negotiations with the local faction."
129
  ],
130
  inputs=msg
131
  )
@@ -135,35 +133,4 @@ def create_gradio_interface():
135
  # Launch the interface
136
  if __name__ == "__main__":
137
  iface = create_gradio_interface()
138
- iface.launch()
139
-
140
- """
141
- # Discord bot implementation using the same generator
142
- import discord
143
- from discord.ext import commands
144
- import os
145
-
146
- class MissionBot(commands.Bot):
147
- def __init__(self):
148
- super().__init__(command_prefix="!")
149
- self.generator = MissionGenerator()
150
-
151
- async def on_ready(self):
152
- print(f'{self.user} has connected to Discord!')
153
-
154
- @commands.command(name='mission')
155
- async def generate_mission(self, ctx, *, description: str):
156
- chat_response, formatted_output = self.generator.generate_response(description)
157
-
158
- # Split response if it's too long for Discord
159
- if len(formatted_output) > 1990: # Discord has 2000 char limit
160
- await ctx.send(f"💭 {chat_response}")
161
- await ctx.send(f"```\n{formatted_output}\n```")
162
- else:
163
- await ctx.send(f"💭 {chat_response}\n\n```\n{formatted_output}\n```")
164
-
165
- # Initialize and run the bot
166
- if __name__ == "__main__":
167
- bot = MissionBot()
168
- bot.run(os.getenv('DISCORD_TOKEN'))
169
- """
 
1
  import gradio as gr
2
+ import re
 
3
  from typing import List, Dict
4
  from datetime import datetime
5
 
6
+ class MissionGenerator:
7
  def __init__(self):
8
  self.mission_counter = 1
9
+ self.keywords = {
10
+ 'main': [
11
+ 'must', 'need to', 'primary', 'main goal', 'objective is to',
12
+ 'task is to', 'have to', 'required to'
13
+ ],
14
+ 'secondary': [
15
+ 'optional', 'can also', 'bonus', 'additional', 'extra',
16
+ 'if possible', 'could also', 'might also'
17
+ ],
18
+ 'alternative': [
19
+ 'alternatively', 'another way', 'or', 'instead',
20
+ 'different approach', 'other option', 'different way'
21
+ ]
22
+ }
23
 
24
+ def extract_objectives(self, text: str) -> List[Dict]:
25
+ sentences = [s.strip() for s in re.split(r'[.!?]+', text) if s.strip()]
26
+ objectives = []
 
 
 
 
27
 
28
+ for sentence in sentences:
29
+ sentence_lower = sentence.lower()
30
+
31
+ # Determine objective type based on keywords and sentence position
32
+ obj_type = 'Main' # Default to Main for first sentence if no other indicators
33
+
34
+ if any(kw in sentence_lower for kw in self.keywords['alternative']):
35
+ obj_type = 'Alternative'
36
+ elif any(kw in sentence_lower for kw in self.keywords['secondary']):
37
+ obj_type = 'Secondary'
38
+ elif any(kw in sentence_lower for kw in self.keywords['main']) or not objectives:
39
+ obj_type = 'Main'
40
+
41
+ # Clean up the sentence
42
+ clean_sentence = sentence
43
+ for keyword_list in self.keywords.values():
44
+ for kw in keyword_list:
45
+ clean_sentence = re.sub(rf'\b{kw}\b', '', clean_sentence, flags=re.IGNORECASE)
46
+
47
+ # Further cleanup
48
+ clean_sentence = re.sub(r'^[\s,]+|[\s,]+$', '', clean_sentence)
49
+ clean_sentence = clean_sentence.strip()
50
+
51
+ if clean_sentence:
52
+ # Create identifier from key words
53
+ words = re.findall(r'\b\w+\b', clean_sentence.lower())
54
+ identifier = '_'.join(words[:2])
55
+
56
+ objectives.append({
57
+ 'type': obj_type,
58
+ 'identifier': identifier,
59
+ 'description': clean_sentence
60
+ })
61
 
62
+ return objectives
63
+
64
  def generate_response(self, user_input: str) -> tuple[str, str]:
65
+ objectives = self.extract_objectives(user_input)
 
66
 
67
+ # Generate formatted output
68
+ output = f"# M{self.mission_counter}\n"
 
 
 
 
 
 
 
 
69
 
70
+ for obj in objectives:
71
+ output += f"Add {obj['type']} {obj['identifier']}\n"
72
+ output += f"- {obj['description']}\n"
73
 
74
+ # Check for silent/suppress keywords
75
+ if any(word in user_input.lower() for word in ['silently', 'quietly', 'without notification', "don't notify"]):
76
+ output += "Dnd\n"
 
 
 
 
 
 
 
 
77
 
78
+ output += "#\n"
79
 
80
+ # Generate chat response
81
+ chat_response = f"I've created {len(objectives)} objectives based on your description. "
82
+ if objectives:
83
+ types = [obj['type'] for obj in objectives]
84
+ chat_response += f"This includes {', '.join(f'{t.lower()} objectives' for t in set(types))}. "
85
+ chat_response += "Would you like to modify any of them?"
 
 
86
 
87
+ return chat_response, output
 
 
 
 
 
 
 
 
 
 
88
 
89
  def create_gradio_interface():
90
  generator = MissionGenerator()
 
98
  with gr.Blocks() as interface:
99
  gr.Markdown("""
100
  # Original War Mission Objective Generator
101
+ Describe your mission scenario and I'll help you create formatted mission objectives.
102
+ Try phrases like "The player must...", "They can optionally...", or "Alternatively..."
103
  """)
104
 
105
  chatbot = gr.Chatbot(height=400, type="messages")
106
  msg = gr.Textbox(
107
  label="Describe your mission scenario",
108
+ placeholder="Describe what the player needs to do..."
109
  )
110
  clear = gr.Button("Clear Conversation")
111
  formatted_output = gr.Textbox(
 
121
 
122
  gr.Examples(
123
  examples=[
124
+ "The player must infiltrate the enemy base. They can optionally rescue prisoners along the way. Alternatively, they could create a diversion at the front gate.",
125
+ "Protect the convoy until it reaches the destination. You can also secure supply drops if possible.",
126
+ "Your main goal is to capture the strategic point. Alternatively, try negotiating with the local faction silently.",
127
  ],
128
  inputs=msg
129
  )
 
133
  # Launch the interface
134
  if __name__ == "__main__":
135
  iface = create_gradio_interface()
136
+ iface.launch()