opinions=split_into_opinions(comments)mo.md(f""" ## Opinions - `{len(comments):,}` comments - `{len(opinions):,}` atomic opinions after splitting on sentence boundaries - `{opinions['answer_id'].n_unique():,}` respondents represented - A respondent can contribute to more than one opinion region """)
Opinions
1,291 comments
2,077 atomic opinions after splitting on sentence boundaries
326 respondents represented
A respondent can contribute to more than one opinion region
classOpenRouterClient:def__init__(self,api_key:str,embedding_model:str,generation_model:str,workers:int=5,):self.api_key=api_keyself.embedding_model=embedding_modelself.generation_model=generation_modelself.workers=workersself.base_url="https://openrouter.ai/api/v1"self.headers={"Authorization":f"Bearer {api_key}","Content-Type":"application/json","X-OpenRouter-Title":"Mapping public opinion with embeddings",}self._embedding_cache={}self._generation_cache={}def_post(self,endpoint:str,payload:dict)->dict:for_attemptinrange(5):try:_response=requests.post(f"{self.base_url}/{endpoint}",headers=self.headers,json=payload,timeout=120,)_response.raise_for_status()return_response.json()except(requests.RequestException,ValueError):if_attempt==4:raisetime.sleep(2**_attempt)raiseAssertionError("unreachable")defembed(self,texts,title="Embedding opinions")->np.ndarray:_texts=list(texts)_batches=[tuple(_texts[i:i+100])foriinrange(0,len(_texts),100)]_results=[]for_batchinmo.status.progress_bar(_batches,title=title):if_batchnotinself._embedding_cache:_response=self._post("embeddings",{"model":self.embedding_model,"input":list(_batch),"encoding_format":"float",},)self._embedding_cache[_batch]=np.asarray([_item["embedding"]for_itemin_response["data"]],dtype=np.float64,)_results.append(self._embedding_cache[_batch])returnnp.vstack(_results)defchat_json(self,prompt:str)->dict:ifpromptnotinself._generation_cache:_response=self._post("chat/completions",{"model":self.generation_model,"messages":[{"role":"system","content":"Return only valid JSON matching the requested format.",},{"role":"user","content":prompt},],"temperature":0.3,"response_format":{"type":"json_object"},},)_content=_response["choices"][0]["message"]["content"]self._generation_cache[prompt]=json.loads(_content)returnself._generation_cache[prompt]defchat_json_many(self,prompts,title:str):_prompts=list(prompts)_results=[]for_startinmo.status.progress_bar(range(0,len(_prompts),self.workers),total=len(_prompts),title=title,):_batch=_prompts[_start:_start+self.workers]withThreadPoolExecutor(max_workers=self.workers)as_executor:_results.extend(_executor.map(self.chat_json,_batch))return_results
api_key=os.environ.get("OPENROUTER_API_KEY","")embedding_model="qwen/qwen3-embedding-8b"generation_model="mistralai/mistral-small-3.2-24b-instruct"llm=OpenRouterClient(api_key,embedding_model,generation_model)start=mo.ui.run_button(label="Run the analysis")mo.vstack([mo.md(f""" ## Models - Embeddings: `{embedding_model}` - Generation: `{generation_model}` - Authentication: `OPENROUTER_API_KEY` - API key available: `{bool(api_key)}` """),start,])
mo.stop(notstart.value,mo.md("- Select **Run the analysis** to call OpenRouter."))assertapi_key,"Set OPENROUTER_API_KEY before running the analysis"short_opinions=opinions.filter(pl.col("length")<100)assertlen(short_opinions)>=200calibration_sample=short_opinions.sample(200,seed=42)
_prompts=[f""" - Survey: City of York consultation on its draft taxi licensing policy - Policy topic: {_row['topic']} - Original opinion: {_row['text']} Write two opinions that clearly express the same idea as the original. - Change style and register. - Vary their length. - Preserve meaning. Return JSON: {{"opinions": ["first", "second"]}} """for_rowincalibration_sample.iter_rows(named=True)]_outputs=llm.chat_json_many(_prompts,"Generating paraphrases")_rows=[]for_source,_outputinzip(calibration_sample.iter_rows(named=True),_outputs):for_paraphrasein_output["opinions"]:_rows.append({"topic":_source["topic"],"original":_source["text"],"paraphrase":_paraphrase,})paraphrases=pl.DataFrame(_rows)
_template=("Survey: City of York consultation on its draft taxi licensing policy\n""Policy topic: {topic}\nOpinion: {text}")_original_inputs=[_template.format(topic=_row["topic"],text=_row["original"])for_rowinparaphrases.iter_rows(named=True)]_paraphrase_inputs=[_template.format(topic=_row["topic"],text=_row["paraphrase"])for_rowinparaphrases.iter_rows(named=True)]original_embeddings=llm.embed(_original_inputs,"Embedding original opinions")paraphrase_embeddings=llm.embed(_paraphrase_inputs,"Embedding paraphrases")_pca=decomposition.PCA(n_components=20,random_state=42)_pca.fit(original_embeddings-paraphrase_embeddings)rewording_axes=_pca.components_rewording_variance=float(_pca.explained_variance_ratio_.sum())
_prompts=[f""" - Survey: City of York consultation on its draft taxi licensing policy - Policy topic: {_row['topic']} - Survey response: {_row['text']} Write two short opinions: - One clearly supporting the response's position. - One clearly opposing the response's position. - Use at most 20 words for each. - Preserve the original register. Return JSON: {{"supporting": "...", "opposing": "..."}} """for_rowincalibration_sample.iter_rows(named=True)]_outputs=llm.chat_json_many(_prompts,"Generating opposing opinions")oppositions=pl.DataFrame([{"topic":_source["topic"],"supporting":_output["supporting"],"opposing":_output["opposing"],}for_source,_outputinzip(calibration_sample.iter_rows(named=True),_outputs)])
_template=("Survey: City of York consultation on its draft taxi licensing policy\n""Policy topic: {topic}\nOpinion: {text}")_supporting=llm.embed([_template.format(topic=_row["topic"],text=_row["supporting"])for_rowinoppositions.iter_rows(named=True)],"Embedding supporting opinions",)_opposing=llm.embed([_template.format(topic=_row["topic"],text=_row["opposing"])for_rowinoppositions.iter_rows(named=True)],"Embedding opposing opinions",)_differences=_supporting-_opposing_differences-=(_differences@rewording_axes.T)@rewording_axes_pca=decomposition.PCA(n_components=15,random_state=42)_pca.fit(_differences)opinion_axes=_pca.components_opinion_variance=float(_pca.explained_variance_ratio_.sum())
embedding_template=("Survey: City of York consultation on its draft taxi licensing policy\n""Policy topic: {topic}\nOpinion: {text}")_inputs=[embedding_template.format(topic=_row["topic"],text=_row["text"])for_rowinopinions.iter_rows(named=True)]_raw=llm.embed(_inputs,"Embedding all opinions")_empty=llm.embed([embedding_template.format(topic="General",text=_text)for_textin["",".","-","N/A","\n"]],"Embedding empty responses",).mean(axis=0)_reworded=_raw-_empty_reworded-=(_reworded@rewording_axes.T)@rewording_axes_clean=_reworded+(_reworded@opinion_axes.T)@opinion_axes_median_norm=np.median(np.linalg.norm(_clean,axis=1))embeddings=_clean/_median_norm
_samples=(ancestry.join(taxonomy,left_on="ancestor",right_on="id").join(opinions,on="id").group_by(id="ancestor").agg(pl.struct("topic","text").sample(10,with_replacement=True,seed=42).alias("samples")))_prompts=[]for_rowin_samples.iter_rows(named=True):_examples="\n".join(f"- [{_sample['topic']}] {_sample['text']}"for_samplein_row["samples"])_prompts.append(f""" The following opinions come from one cluster in York's taxi licensing consultation:{_examples} - Write two representative opinion statements. - Use no more than five words per statement. - Do not claim that every respondent agrees. Return JSON: {{"statements": ["first", "second"]}} """)_outputs=llm.chat_json_many(_prompts,"Labelling opinion regions")topics=pl.DataFrame({"id":_samples["id"],"topic":["\n".join(_output["statements"])for_outputin_outputs],})
alt.theme.enable("carbong10")_layout=compute_layout(taxonomy)_taxonomy_topics=(taxonomy.join(topics,on="id").join(tree.select("id","parent"),on="id").join(regions,on="id",how="left").join(stats,on="id").select("topic","id","region","cardinality",topic_text=pl.format("{}: {}",pl.col("id"),pl.col("topic").fill_null("")),parent=pl.col("parent"),is_region=pl.col("region").is_not_null(),))_selection=alt.selection_point(fields=["region"])_opinion_data=(coordinates_2d(embeddings).join(opinions,on="id").join(ancestry,on="id").rename({"ancestor":"region"}).join(_taxonomy_topics,on="region").join(compute_depth(tree),on="id").with_columns(size=1/pl.col("depth")))_cloud=(alt.Chart(_opinion_data).mark_point(strokeWidth=1).encode(alt.X("x",axis=None),alt.Y("y",axis=None),alt.Tooltip(["text","topic","topic_text"]),alt.Size("size",legend=None),alt.Shape("region:N"),alt.Color("region:N"),opacity=alt.condition(_selection,alt.value(1),alt.value(0.25)),).add_params(_selection))_tree_data=_taxonomy_topics.join(_layout,on="id")_paths=(taxonomy.filter(pl.col("parent").is_not_null()).with_columns(_endpoint=pl.lit([0,1])).explode("_endpoint").with_columns(_join_id=pl.when(pl.col("_endpoint")==0).then("id").otherwise("parent")).join(_layout,left_on="_join_id",right_on="id"))_x_max=float(_layout["x"].max())_y_max=float(_layout["y"].max())_categories=alt.layer(alt.Chart(_paths).mark_line(interpolate="step-before",color="black").encode(alt.X("x",axis=None),alt.Y("y",axis=None),alt.Detail("id")),alt.Chart(_tree_data).mark_point(size=200,strokeWidth=3).encode(alt.X("x:Q",axis=None,scale=alt.Scale(domain=[-1,_x_max*2])),alt.Y("y:Q",axis=None,scale=alt.Scale(reverse=True,domain=[-0.5,_y_max])),alt.Tooltip(["topic_text:N","cardinality:Q"]),opacity=alt.condition(_selection,alt.value(1),alt.value(0.25)),color="region:N",shape=alt.condition(alt.datum.is_region,"region:N",alt.value("square")),).add_params(_selection),alt.Chart(_tree_data).mark_text(dx=15,align="left",lineBreak="\n",baseline="middle").encode(alt.X("x"),alt.Y("y"),text=alt.condition(alt.datum.is_region,"topic_text",alt.value("")),opacity=alt.condition(_selection,alt.value(1),alt.value(0.25)),),)_topic_data=(regions.join(_layout,on="id").join(topics,on="id").join(stats,on="id").sort("y").with_row_index("idx"))_means=np.vstack(_topic_data["mean"].to_numpy())_means/=np.linalg.norm(_means,axis=1,keepdims=True)_heatmap_data=(matrix_frame(1-_means@_means.T).join(_topic_data.select("idx","topic","region"),left_on="i",right_on="idx").join(_topic_data.select("idx","topic","region"),left_on="j",right_on="idx",suffix="_other",).with_columns(horizontal=pl.format("{}: {}",pl.col("region"),pl.col("topic")),vertical=pl.format("{}: {}",pl.col("region_other"),pl.col("topic_other")),))_heatmap=(alt.Chart(_heatmap_data).mark_rect().encode(alt.X("horizontal:N",sort=alt.EncodingSortField("i"),axis=alt.Axis(labelAngle=-45)),alt.Y("vertical:N",sort=alt.EncodingSortField("j")),alt.Color("value:Q"),alt.Tooltip(["topic","topic_other","value"]),))visualization=alt.vconcat(_cloud.properties(width=800,height=600,title="Opinion space — select a point to highlight its region",),_categories.properties(width=800,height=int(40*n_regions),title="Opinion taxonomy",),_heatmap.properties(width=500,height=500,title="Distance between opinion regions",),).resolve_legend(color="shared",fill="shared")visualization
_prompt=f"""Create a concise report from this automated analysis of York's taxi licensing consultation.- Return JSON with one field named "bullets" containing a list of strings.- Use bullets only, not paragraphs.- Cover major themes, consensus, and disagreement.- Mention approximate respondent counts.- Include short examples grounded in the supplied samples.- Treat cluster labels and counts as approximate.Data:{json.dumps(report_data,ensure_ascii=False)}"""report_bullets=llm.chat_json(_prompt)["bullets"]mo.md("## Findings\n\n"+"\n".join(f"- {_item}"for_iteminreport_bullets))
Findings
326 respondents in total.
Major themes: wheelchair-accessible vehicles (WAVs), vehicle age and standards, taxi identification, and out-of-town taxis.
Approx. 118 respondents believe there are enough WAVs in York, while others mention difficulties in accessing them.
Approx. 177 respondents argue for higher investment recovery for WAVs and electrifying the taxi fleet.
Approx. 137 respondents suggest extending licenses for existing vehicles and enforcing stricter rules for non-York taxis.
Approx. 116 respondents support drivers in replacing vehicles and linking vehicle age to mileage.
Approx. 131 respondents believe factory tinted windows should be allowed, while others argue for clear identification of taxis.
Approx. 150 respondents think black taxis are unnecessary and lights suffice for identification.
Approx. 95 respondents emphasize the importance of clearly identifying private hire vehicles.
Approx. 143 respondents believe cameras improve passenger safety but may add cost for drivers.
Approx. 129 respondents think drivers must know the area and out-of-town taxis are concerning.
Approx. 92 respondents consider subcontracting unsafe and prefer York taxis to stay York-based.
Approx. 125 respondents advocate for enforcing York-registered taxis only and stopping taxis from other areas.
Disagreement exists on vehicle age limits, with some finding 36 months too long and others too lenient.
Consensus on the need for clear identification of taxis and addressing out-of-town taxis working in York.