proteusr commited on
Commit
2566959
·
verified ·
1 Parent(s): d804b0c

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +173 -177
  2. chromadb_storage/.gitkeep +0 -0
app.py CHANGED
@@ -1,9 +1,11 @@
1
  import os;
2
  import cohere;
3
- import numpy as np;
4
- from dotenv import load_dotenv;
5
  import chromadb;
 
6
  import gradio as gr;
 
 
 
7
 
8
  load_dotenv()
9
 
@@ -13,213 +15,207 @@ co = cohere.Client( CO_API_KEY );
13
  EMBED_MODEL = "embed-v4.0"
14
  CHAT_MODEL = "command-r-08-2024"
15
 
 
 
 
 
16
 
17
- client = chromadb.Client();
18
  collection = client.get_or_create_collection( name="brampton" );
19
 
20
- brampton_docs = [
21
- # Shopping Centres
22
- "Bramalea City Centre is one of Canada’s largest malls, with 1.5 million sq ft of retail space and over 300 stores.",
23
- "Trinity Common Mall is a large outdoor shopping centre spanning over 850,000 sq ft with 69 retail stores, services, and restaurants at Hwy 410 & Bovaird Dr.",
24
- "Shoppers World Brampton is a community shopping destination featuring over 180 shops and services at 499 Main St S, Suite 56, L6Y 1N7.",
25
- "Brampton Mall houses 38 brand‑name stores at 152–160 Main St S, L6W 2C9, with services, restaurants, and customer amenities.",
26
- # Entertainment & Recreation
27
- "Toprock Climbing is Brampton’s first rockclimbing gym (opened 2017), a community hub to meet new friends, challenge yourself, and stay fit.",
28
- "Glow Zone 360 offers glow‑in‑the‑dark mini‑golf, laser tag, and arcade games at 9446 McLaughlin Rd N, Unit 7.",
29
- "The CAA Centre is Brampton’s indoor sports and entertainment complex, hosting hockey games, trade shows, and community events at 7575 Kennedy Rd.",
30
- # Parks & Outdoors
31
- "Gage Park is an urban park at 45 Main St S offering strolling paths, picnic areas, flower gardens, free evening concerts, and a seasonal ice rink.",
32
- "Professor’s Lake Recreation Centre features a 65‑acre lake with sandy beach, paddleboat/canoe/kayak rentals, walking trails, and fishing spots.",
33
- "Eldorado Park is a scenic riverside park on the Credit River with picnic areas, walking trails, and a small lake for outdoor recreation.",
34
- "Chinguacousy Park features a water park, splash pads, mini golf, ski hills, and biking trails at 9050 Bramalea Rd.",
35
- "Heart Lake Conservation Park offers hiking, fishing, treetop trek canopy tours, and skiing at 11073 Heart Lake Rd.",
36
- "Loafer’s Lake Recreation Centre is a community facility with ice rinks, outdoor pool, basketball courts, and scenic walking paths.",
37
- "Claireville Conservation Area spans over 2,000 acres of wildlife habitat along the Humber River, with trails, picnic areas, and off‑road biking.",
38
- # Culture & History
39
- "Peel Art Gallery, Museum and Archives (PAMA) is a museum, art gallery, and archives for the Peel Region located at 9 Wellington St E in Brampton :contentReference[oaicite:3]{index=3}.",
40
- "Rose Theatre Brampton is a municipally‑owned performing arts centre with an 868‑seat main hall and a smaller studio venue at 1 Theatre Ln :contentReference[oaicite:4]{index=4}.",
41
- "Historic Bovaird House is a restored 1860s heritage farmhouse offering guided tours and seasonal events at 10 Chinguacousy Rd.",
42
- "Historic Churchville Village is a preserved 19thcentury rural settlement, featuring St. James Anglican Church and original pioneer buildings.",
43
- # Transit & Infrastructure
44
- "Brampton GO Station connects downtown Brampton to Toronto via the GO Transit rail network at 27 Railway St.",
45
- "Brampton Gateway Terminal is a major Brampton Transit bus hub offering city‑wide connections at Steeles Ave E & Main St.",
46
- # Education & Health
47
- "University of Guelph‑Humber is a joint campus offering undergraduate degrees in business, health, and arts at 207 Humber College Blvd.",
48
- "Sheridan College Davis Campus offers programs in applied health, community studies, and media at 7899 McLaughlin Rd S.",
49
- "Peel Memorial Centre for Integrated Health and Wellness provides hospital and outpatient services at 50 Queen St E.",
50
- # Events & Festivals
51
- "Carabram is an annual multicultural festival every July at Garden Square, showcasing pavilions, food, and performances from around the world.",
52
- "The Brampton Santa Claus Parade, held every November along Queen St, features colourful floats, marching bands, and a visit from Santa.",
53
- # Neighbourhoods & Demographics
54
- "Springdale is a northern suburban district nicknamed “Singhdale” for its large Sikh Canadian community, bounded by Bovaird Dr, Heart Lake Rd, and Airport Rd :contentReference[oaicite:5]{index=5}.",
55
-
56
- # General City Facts
57
- "Official Name: City of Brampton.",
58
- "Settlement Type: lower-tier city.",
59
- "Nickname: Flower City (formerly 'Flower Town of Canada').",
60
- "Part of the Greater Toronto Area.",
61
- "Regional seat of the Regional Municipality of Peel.",
62
- "Incorporated as a village in 1853.",
63
- "Incorporated as a town in 1873.",
64
- "Incorporated as a city in 1974.",
65
- "Major highways: Highway 410 and Highway 407 ETR.",
66
- # Geography & Climate
67
- "Borders Vaughan to the east.",
68
- "Borders Halton Hills to the west.",
69
- "Borders Caledon to the north.",
70
- "Borders Mississauga to the south.",
71
- "Borders Etobicoke (Toronto) to the southeast.",
72
- "Climate: Humid continental (Köppen Dfa).",
73
- # Sister Cities
74
- "Miami Beach, Florida.",
75
- "Plano, Texas.",
76
- "Ribeira Grande, Azores, Portugal.",
77
- "Xuzhou, Jiangsu, China.",
78
- "Brampton, Cumbria, England.",
79
- "Marikina, Philippines.",
80
- "Gapyeong, South Korea.",
81
- # Neighbourhoods
82
- "Alloa: rural former community in northwest Brampton.",
83
- "Bramalea: Canada’s first planned satellite town.",
84
- "Castlemore: suburban area with luxury homes in West Humber River valley.",
85
- "Churchville: preserved 19th-century village on the Credit River.",
86
- "Claireville: neighbourhood around Claireville Conservation Area.",
87
- "Mount Pleasant: fast‑growing community since 2006 GO station.",
88
- "Snelgrove: straddles Mayfield Road between Brampton and Caledon.",
89
- "Springdale: 4,000acre northern district with large Sikh Canadian community.",
90
- "Tullamore: small residential neighbourhood in Brampton.",
91
- # History Highlights
92
- "Originally inhabited by the Mississaugas of the Credit First Nation.",
93
- "Treaty 19 (Ajetance Purchase) signed October 1818.",
94
- "Village incorporation: 1853.",
95
- "Town incorporation: 1873.",
96
- "City status granted: 1974.",
97
- "Named after Brampton, Cumberland (England).",
98
- "Dale’s Nursery: once North America’s largest cut‑flower business.",
99
- "Historic Bovaird House (1860s farmhouse) offers tours.",
100
- "Historic Churchville Village preserves pioneer buildings.",
101
- "Rose Theatre opened in September 2006.",
102
- # Landmarks & Culture
103
- "Peel Art Gallery, Museum and Archives (PAMA) at 9 Wellington St E.",
104
- "Rose Theatre Brampton: 868‑seat main hall + studio theatre.",
105
- "Heritage Theatre (former Capitol Theatre) preceded Rose Theatre.",
106
- "Brampton City Hall at 2 Wellington St W; nine‑storey tower added 2014.",
107
- "Garden Square: public plaza for concerts and events.",
108
- "A. Grenville & W. Davis Courthouse at Hurontario & County Court St.",
109
- # Shopping Centres
110
- "Bramalea City Centre: 1.5 million sq ft, 300+ stores.",
111
- "Trinity Common Mall: 850,000 sq ft open‑air centre, 69 retailers.",
112
- "Shoppers World Brampton: 180+ shops at 499 Main St S.",
113
- "Brampton Mall: 38 brand‑name stores at 152–160 Main St S.",
114
- # Markets & Festivals
115
- "Downtown Brampton Farmers’ Market at 30 Church St E (since 1859).",
116
- "Carabram: annual multicultural festival every July.",
117
- # Parks & Recreation
118
- "Gage Park: oldest municipal park (est. 1903) with gardens, concerts.",
119
- "Professor’s Lake Recreation Centre: 65‑acre lake, beach, rentals.",
120
- "Eldorado Park: riverside park with playgrounds and pool on Credit River.",
121
- "Chinguacousy Park: 100 acre green space with zoo, mini‑golf, ski hill.",
122
- "Heart Lake Conservation Park: hiking, fishing, canopy tours.",
123
- "Loafer’s Lake Recreation Centre: rinks, pool, courts, walking trails.",
124
- "Claireville Conservation Area: 2,000 acre wildlife habitat.",
125
- # Transit & Infrastructure
126
- "Brampton GO Station connects via GO Transit rail (27 Railway St).",
127
- "Mount Pleasant GO Station opened 2006 on Bradford line.",
128
- "Lisgar GO Station serves western Brampton on Barrie line.",
129
- "Bramalea GO Station hub at Fennell Blvd.",
130
- "Brampton Gateway Terminal: central Brampton Transit bus hub.",
131
- # Sports Teams
132
- "Brampton Battalion: OHL team (1998–2013).",
133
- "Brampton Beast: ECHL hockey (2013–2018).",
134
- "Bramalea Blues: junior A ice hockey (OPJHL).",
135
- "Bramalea Satellites: junior B hockey team.",
136
- "Brampton City United FC: semi‑pro soccer club (founded 2007).",
137
- "Brampton Honey Badgers: CEBL basketball champions (2022).",
138
- "Brampton Excelsiors (MSL): Senior A box lacrosse (est. 1883).",
139
- "Brampton Excelsiors Jr. A: OLA Junior A lacrosse league.",
140
- "Brampton Excelsiors Jr. B: OJBLL box lacrosse expansion team (2012).",
141
- # Education & Health
142
- "University of Guelph–Humber: joint undergraduate campus in Brampton.",
143
- "Sheridan College Davis Campus: applied health and media programs.",
144
- "Peel Memorial Centre for Integrated Health and Wellness at 50 Queen St E.",
145
- "William Osler Health System operates Brampton Civic Hospital on Bovaird Dr."
146
- ]
147
-
148
- doc_embeddings = co.embed(
149
- model=EMBED_MODEL,
150
- texts=brampton_docs
151
- ).embeddings;
152
-
153
- brampton_vector = np.mean( doc_embeddings, axis=0 );
154
-
155
- collection.add(
156
- ids=[f"doc_{i}" for i in range(len(brampton_docs))],
157
- documents=brampton_docs,
158
- embeddings=doc_embeddings,
159
- metadatas=[{"source": f"doc_{i}"} for i in range(len(brampton_docs))]
160
- )
 
 
 
 
161
 
162
  SYSTEM_INSTR = (
163
  "You are a Brampton-focused assistant. "
164
  "Only discuss topics related to Brampton. "
165
  "If the user asks about anything else, politely redirect them back to Brampton topics."
166
- )
167
 
168
 
169
- def generate_response(prompt: str, max_tokens: int = 200) -> str:
170
  resp = co.generate(
171
  model=CHAT_MODEL,
172
  prompt=prompt,
173
  max_tokens=max_tokens,
174
  return_likelihoods="NONE"
175
- )
176
- return resp.generations[0].text
177
 
178
  def brampton_response( query: str, k: int = 5, steering_scale: float = 0.5, sim_threshold: float = 0.3 ) -> str:
179
 
180
- q_emb = np.array(co.embed(model=EMBED_MODEL, texts=[query]).embeddings[0])
181
- sim = np.dot(q_emb, brampton_vector) / (np.linalg.norm(q_emb) * np.linalg.norm(brampton_vector))
182
  if sim < sim_threshold:
183
- return "I’m here to discuss Bramptonlet's keep our conversation focused on this city!"
184
- steered_emb = q_emb + steering_scale * brampton_vector
185
 
186
- results = collection.query(
187
- query_embeddings=[steered_emb.tolist()],
188
- n_results=k
189
- )
190
- context = "\n".join(results["documents"][0])
191
 
192
  prompt = (
193
  f"{SYSTEM_INSTR}\n"
194
  f"Context:\n{context}\n\n"
195
  f"User: {query}\n"
196
  f"Assistant:"
197
- )
198
 
199
  return generate_response( prompt );
200
 
201
  def respond(message, chat_history):
202
- bot_reply = brampton_response(message)
203
- # append the new turn as a tuple (user_msg, bot_reply)
204
- chat_history = chat_history + [(message, bot_reply)]
205
- # return empty str to clear the box, and the updated history
206
- return "", chat_history
207
 
208
  with gr.Blocks() as demo:
209
- gr.Markdown("# Brampton Model")
210
- chatbot = gr.Chatbot()
211
- user_input = gr.Textbox(
212
- show_label=False,
213
- placeholder="Ask me about anything"
214
- )
215
- # submit maps (user_input, chatbot) → (user_input, chatbot)
216
- user_input.submit(
217
- fn=respond,
218
- inputs=[user_input, chatbot],
219
- outputs=[user_input, chatbot]
220
- )
221
- gr.Markdown("Powered by Cohere command-r, embed-v4.0.")
222
 
223
  # share=True creates a public URL when not on HF Spaces
224
  if __name__ == "__main__":
225
- demo.launch(share=True)
 
1
  import os;
2
  import cohere;
 
 
3
  import chromadb;
4
+ import numpy as np;
5
  import gradio as gr;
6
+ from dotenv import load_dotenv;
7
+ from chromadb.config import Settings
8
+
9
 
10
  load_dotenv()
11
 
 
15
  EMBED_MODEL = "embed-v4.0"
16
  CHAT_MODEL = "command-r-08-2024"
17
 
18
+ PERSIST_DIR = "/mnt/data/chromadb_storage"
19
+ os.makedirs(PERSIST_DIR, exist_ok=True)
20
+
21
+ client = chromadb.Client( Settings( chroma_db_impl="duckdb+parquet", persist_directory=PERSIST_DIR ) );
22
 
 
23
  collection = client.get_or_create_collection( name="brampton" );
24
 
25
+ if len(collection.count()['count']) == 0:
26
+
27
+ brampton_docs = [
28
+ # Shopping Centres
29
+ "Bramalea City Centre is one of Canada’s largest malls, with 1.5 million sq ft of retail space and over 300 stores.",
30
+ "Trinity Common Mall is a large outdoor shopping centre spanning over 850,000 sq ft with 69 retail stores, services, and restaurants at Hwy 410 & Bovaird Dr.",
31
+ "Shoppers World Brampton is a community shopping destination featuring over 180 shops and services at 499 Main St S, Suite 56, L6Y 1N7.",
32
+ "Brampton Mall houses 38 brandname stores at 152–160 Main St S, L6W 2C9, with services, restaurants, and customer amenities.",
33
+ # Entertainment & Recreation
34
+ "Toprock Climbing is Brampton’s first rock‑climbing gym (opened 2017), a community hub to meet new friends, challenge yourself, and stay fit.",
35
+ "Glow Zone 360 offers glow‑in‑the‑dark mini‑golf, laser tag, and arcade games at 9446 McLaughlin Rd N, Unit 7.",
36
+ "The CAA Centre is Brampton’s indoor sports and entertainment complex, hosting hockey games, trade shows, and community events at 7575 Kennedy Rd.",
37
+ # Parks & Outdoors
38
+ "Gage Park is an urban park at 45 Main St S offering strolling paths, picnic areas, flower gardens, free evening concerts, and a seasonal ice rink.",
39
+ "Professor’s Lake Recreation Centre features a 65‑acre lake with sandy beach, paddleboat/canoe/kayak rentals, walking trails, and fishing spots.",
40
+ "Eldorado Park is a scenic riverside park on the Credit River with picnic areas, walking trails, and a small lake for outdoor recreation.",
41
+ "Chinguacousy Park features a water park, splash pads, mini golf, ski hills, and biking trails at 9050 Bramalea Rd.",
42
+ "Heart Lake Conservation Park offers hiking, fishing, treetop trek canopy tours, and skiing at 11073 Heart Lake Rd.",
43
+ "Loafer’s Lake Recreation Centre is a community facility with ice rinks, outdoor pool, basketball courts, and scenic walking paths.",
44
+ "Claireville Conservation Area spans over 2,000 acres of wildlife habitat along the Humber River, with trails, picnic areas, and off‑road biking.",
45
+ # Culture & History
46
+ "Peel Art Gallery, Museum and Archives (PAMA) is a museum, art gallery, and archives for the Peel Region located at 9 Wellington St E in Brampton :contentReference[oaicite:3]{index=3}.",
47
+ "Rose Theatre Brampton is a municipallyowned performing arts centre with an 868‑seat main hall and a smaller studio venue at 1 Theatre Ln :contentReference[oaicite:4]{index=4}.",
48
+ "Historic Bovaird House is a restored 1860s heritage farmhouse offering guided tours and seasonal events at 10 Chinguacousy Rd.",
49
+ "Historic Churchville Village is a preserved 19th‑century rural settlement, featuring St. James Anglican Church and original pioneer buildings.",
50
+ # Transit & Infrastructure
51
+ "Brampton GO Station connects downtown Brampton to Toronto via the GO Transit rail network at 27 Railway St.",
52
+ "Brampton Gateway Terminal is a major Brampton Transit bus hub offering city‑wide connections at Steeles Ave E & Main St.",
53
+ # Education & Health
54
+ "University of Guelph‑Humber is a joint campus offering undergraduate degrees in business, health, and arts at 207 Humber College Blvd.",
55
+ "Sheridan College Davis Campus offers programs in applied health, community studies, and media at 7899 McLaughlin Rd S.",
56
+ "Peel Memorial Centre for Integrated Health and Wellness provides hospital and outpatient services at 50 Queen St E.",
57
+ # Events & Festivals
58
+ "Carabram is an annual multicultural festival every July at Garden Square, showcasing pavilions, food, and performances from around the world.",
59
+ "The Brampton Santa Claus Parade, held every November along Queen St, features colourful floats, marching bands, and a visit from Santa.",
60
+ # Neighbourhoods & Demographics
61
+ "Springdale is a northern suburban district nicknamed “Singhdale” for its large Sikh Canadian community, bounded by Bovaird Dr, Heart Lake Rd, and Airport Rd :contentReference[oaicite:5]{index=5}.",
62
+
63
+ # General City Facts
64
+ "Official Name: City of Brampton.",
65
+ "Settlement Type: lower-tier city.",
66
+ "Nickname: Flower City (formerly 'Flower Town of Canada').",
67
+ "Part of the Greater Toronto Area.",
68
+ "Regional seat of the Regional Municipality of Peel.",
69
+ "Incorporated as a village in 1853.",
70
+ "Incorporated as a town in 1873.",
71
+ "Incorporated as a city in 1974.",
72
+ "Major highways: Highway 410 and Highway 407 ETR.",
73
+ # Geography & Climate
74
+ "Borders Vaughan to the east.",
75
+ "Borders Halton Hills to the west.",
76
+ "Borders Caledon to the north.",
77
+ "Borders Mississauga to the south.",
78
+ "Borders Etobicoke (Toronto) to the southeast.",
79
+ "Climate: Humid continental (Köppen Dfa).",
80
+ # Sister Cities
81
+ "Miami Beach, Florida.",
82
+ "Plano, Texas.",
83
+ "Ribeira Grande, Azores, Portugal.",
84
+ "Xuzhou, Jiangsu, China.",
85
+ "Brampton, Cumbria, England.",
86
+ "Marikina, Philippines.",
87
+ "Gapyeong, South Korea.",
88
+ # Neighbourhoods
89
+ "Alloa: rural former community in northwest Brampton.",
90
+ "Bramalea: Canada’s first planned satellite town.",
91
+ "Castlemore: suburban area with luxury homes in West Humber River valley.",
92
+ "Churchville: preserved 19th-century village on the Credit River.",
93
+ "Claireville: neighbourhood around Claireville Conservation Area.",
94
+ "Mount Pleasant: fastgrowing community since 2006 GO station.",
95
+ "Snelgrove: straddles Mayfield Road between Brampton and Caledon.",
96
+ "Springdale: 4,000‑acre northern district with large Sikh Canadian community.",
97
+ "Tullamore: small residential neighbourhood in Brampton.",
98
+ # History Highlights
99
+ "Originally inhabited by the Mississaugas of the Credit First Nation.",
100
+ "Treaty 19 (Ajetance Purchase) signed October 1818.",
101
+ "Village incorporation: 1853.",
102
+ "Town incorporation: 1873.",
103
+ "City status granted: 1974.",
104
+ "Named after Brampton, Cumberland (England).",
105
+ "Dale’s Nursery: once North America’s largest cut‑flower business.",
106
+ "Historic Bovaird House (1860s farmhouse) offers tours.",
107
+ "Historic Churchville Village preserves pioneer buildings.",
108
+ "Rose Theatre opened in September 2006.",
109
+ # Landmarks & Culture
110
+ "Peel Art Gallery, Museum and Archives (PAMA) at 9 Wellington St E.",
111
+ "Rose Theatre Brampton: 868‑seat main hall + studio theatre.",
112
+ "Heritage Theatre (former Capitol Theatre) preceded Rose Theatre.",
113
+ "Brampton City Hall at 2 Wellington St W; nine‑storey tower added 2014.",
114
+ "Garden Square: public plaza for concerts and events.",
115
+ "A. Grenville & W. Davis Courthouse at Hurontario & County Court St.",
116
+ # Shopping Centres
117
+ "Bramalea City Centre: 1.5 million sq ft, 300+ stores.",
118
+ "Trinity Common Mall: 850,000 sq ft open‑air centre, 69 retailers.",
119
+ "Shoppers World Brampton: 180+ shops at 499 Main St S.",
120
+ "Brampton Mall: 38 brand‑name stores at 152–160 Main St S.",
121
+ # Markets & Festivals
122
+ "Downtown Brampton Farmers’ Market at 30 Church St E (since 1859).",
123
+ "Carabram: annual multicultural festival every July.",
124
+ # Parks & Recreation
125
+ "Gage Park: oldest municipal park (est. 1903) with gardens, concerts.",
126
+ "Professor’s Lake Recreation Centre: 65‑acre lake, beach, rentals.",
127
+ "Eldorado Park: riverside park with playgrounds and pool on Credit River.",
128
+ "Chinguacousy Park: 100 acre green space with zoo, mini‑golf, ski hill.",
129
+ "Heart Lake Conservation Park: hiking, fishing, canopy tours.",
130
+ "Loafer’s Lake Recreation Centre: rinks, pool, courts, walking trails.",
131
+ "Claireville Conservation Area: 2,000 acre wildlife habitat.",
132
+ # Transit & Infrastructure
133
+ "Brampton GO Station connects via GO Transit rail (27 Railway St).",
134
+ "Mount Pleasant GO Station opened 2006 on Bradford line.",
135
+ "Lisgar GO Station serves western Brampton on Barrie line.",
136
+ "Bramalea GO Station hub at Fennell Blvd.",
137
+ "Brampton Gateway Terminal: central Brampton Transit bus hub.",
138
+ # Sports Teams
139
+ "Brampton Battalion: OHL team (1998–2013).",
140
+ "Brampton Beast: ECHL hockey (2013–2018).",
141
+ "Bramalea Blues: junior A ice hockey (OPJHL).",
142
+ "Bramalea Satellites: junior B hockey team.",
143
+ "Brampton City United FC: semi‑pro soccer club (founded 2007).",
144
+ "Brampton Honey Badgers: CEBL basketball champions (2022).",
145
+ "Brampton Excelsiors (MSL): Senior A box lacrosse (est. 1883).",
146
+ "Brampton Excelsiors Jr. A: OLA Junior A lacrosse league.",
147
+ "Brampton Excelsiors Jr. B: OJBLL box lacrosse expansion team (2012).",
148
+ # Education & Health
149
+ "University of Guelph–Humber: joint undergraduate campus in Brampton.",
150
+ "Sheridan College Davis Campus: applied health and media programs.",
151
+ "Peel Memorial Centre for Integrated Health and Wellness at 50 Queen St E.",
152
+ "William Osler Health System operates Brampton Civic Hospital on Bovaird Dr."
153
+ ];
154
+
155
+ doc_embeddings = co.embed(
156
+ model=EMBED_MODEL,
157
+ texts=brampton_docs
158
+ ).embeddings;
159
+
160
+ brampton_vector = np.mean( doc_embeddings, axis=0 );
161
+
162
+ collection.add(
163
+ ids=[f"doc_{i}" for i in range( len( brampton_docs ) )],
164
+ documents=brampton_docs,
165
+ embeddings=doc_embeddings,
166
+ metadatas=[{"source": f"doc_{i}"} for i in range( len( brampton_docs ) )]
167
+ );
168
+
169
+ client.persist();
170
 
171
  SYSTEM_INSTR = (
172
  "You are a Brampton-focused assistant. "
173
  "Only discuss topics related to Brampton. "
174
  "If the user asks about anything else, politely redirect them back to Brampton topics."
175
+ );
176
 
177
 
178
+ def generate_response( prompt: str, max_tokens: int = 200 ) -> str:
179
  resp = co.generate(
180
  model=CHAT_MODEL,
181
  prompt=prompt,
182
  max_tokens=max_tokens,
183
  return_likelihoods="NONE"
184
+ );
185
+ return resp.generations[0].text;
186
 
187
  def brampton_response( query: str, k: int = 5, steering_scale: float = 0.5, sim_threshold: float = 0.3 ) -> str:
188
 
189
+ q_emb = np.array( co.embed(model=EMBED_MODEL, texts=[query]).embeddings[0] );
190
+ sim = np.dot( q_emb, brampton_vector ) / ( np.linalg.norm( q_emb ) * np.linalg.norm( brampton_vector ) );
191
  if sim < sim_threshold:
192
+ return "I’m here to discuss Brampton, let's keep our conversation focused on this city!";
193
+ steered_emb = q_emb + steering_scale * brampton_vector;
194
 
195
+ results = collection.query( query_embeddings=[steered_emb.tolist()], n_results=k );
196
+ context = "\n".join( results["documents"][0] );
 
 
 
197
 
198
  prompt = (
199
  f"{SYSTEM_INSTR}\n"
200
  f"Context:\n{context}\n\n"
201
  f"User: {query}\n"
202
  f"Assistant:"
203
+ );
204
 
205
  return generate_response( prompt );
206
 
207
  def respond(message, chat_history):
208
+ bot_reply = brampton_response( message );
209
+ chat_history = chat_history + [( message, bot_reply )];
210
+ return "", chat_history;
 
 
211
 
212
  with gr.Blocks() as demo:
213
+ gr.Markdown( "# Brampton Model" );
214
+ chatbot = gr.Chatbot();
215
+ user_input = gr.Textbox( show_label=False, placeholder="Ask me about anything" );
216
+ user_input.submit( fn=respond, inputs=[user_input, chatbot], outputs=[user_input, chatbot] );
217
+ gr.Markdown( "Powered by Cohere command-r, embed-v4.0." );
 
 
 
 
 
 
 
 
218
 
219
  # share=True creates a public URL when not on HF Spaces
220
  if __name__ == "__main__":
221
+ demo.launch( share=True );
chromadb_storage/.gitkeep ADDED
File without changes